tracehub 0.0.0-stage → 0.5.2
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 +431 -2
- package/dist/cli/args.js +28 -0
- package/dist/cli/clipboard.js +46 -0
- package/dist/cli/commands/context.js +115 -0
- package/dist/cli/commands/hook.js +215 -0
- package/dist/cli/commands/providers.js +55 -0
- package/dist/cli/commands/setup.js +448 -0
- package/dist/cli/commands/uninstall.js +156 -0
- package/dist/cli/io.js +26 -0
- package/dist/cli/remote.js +81 -0
- package/dist/cli/repo.js +70 -0
- package/dist/cli/signin.js +90 -0
- package/dist/cli/ui.js +130 -0
- package/dist/cli/usage.js +151 -0
- package/dist/cli.js +38 -0
- package/dist/client/auth.js +70 -0
- package/dist/client/consent.js +94 -0
- package/dist/client/errors.js +4 -0
- package/dist/client/github.js +129 -0
- package/dist/client/registry.js +112 -0
- package/dist/client/tracehub.js +98 -0
- package/dist/client/upload.js +106 -0
- package/dist/client/uploadPolicy.js +60 -0
- package/dist/git/git.js +163 -0
- package/dist/git/global-hooks.js +221 -0
- package/dist/git/hooks.js +67 -0
- package/dist/git/markers.js +93 -0
- package/dist/git/trailers.js +36 -0
- package/dist/local/commitBoundary.js +38 -0
- package/dist/local/discover.js +283 -0
- package/dist/local/files.js +55 -0
- package/dist/local/lines.js +16 -0
- package/dist/local/opencode.js +124 -0
- package/dist/local/paths.js +51 -0
- package/dist/local/providers.js +171 -0
- package/dist/local/subagents.js +63 -0
- package/dist/protocol/context.js +202 -0
- package/dist/protocol/sessionRef.js +24 -0
- package/dist/protocol/trace.js +111 -0
- package/dist/redact/deny.js +25 -0
- package/dist/redact/redact.js +189 -0
- package/dist/trace/build.js +256 -0
- package/dist/transcript/parseClaude.js +105 -0
- package/dist/transcript/parseCodex.js +164 -0
- package/dist/transcript/parseOpencode.js +84 -0
- package/dist/transcript/title.js +27 -0
- package/dist/transcript/transcript.js +120 -0
- package/package.json +44 -4
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { isExpired, readAuth } from "../client/auth.js";
|
|
2
|
+
import { TracehubClient, tracehubUrl, } from "../client/tracehub.js";
|
|
3
|
+
import { ENV_TEST, ENV_TEST_PUSH_BUDGET, home } from "../local/paths.js";
|
|
4
|
+
import { formatSessionRef } from "../protocol/sessionRef.js";
|
|
5
|
+
import { readDenyList } from "../redact/deny.js";
|
|
6
|
+
import { formatFindings } from "../redact/redact.js";
|
|
7
|
+
import { warn } from "./io.js";
|
|
8
|
+
export const UPLOAD_BUDGET_MS = 15_000;
|
|
9
|
+
// What a push leaves unfinished goes on in the background, for this long.
|
|
10
|
+
export const BACKGROUND_BUDGET_MS = 10 * 60_000;
|
|
11
|
+
// How long a push waits for its upload. Tests shorten it.
|
|
12
|
+
export function pushBudgetMs() {
|
|
13
|
+
const test = Number(process.env[ENV_TEST_PUSH_BUDGET]);
|
|
14
|
+
return process.env[ENV_TEST] !== undefined && test > 0
|
|
15
|
+
? test
|
|
16
|
+
: UPLOAD_BUDGET_MS;
|
|
17
|
+
}
|
|
18
|
+
// The stored sign-in, if there is one that has not expired.
|
|
19
|
+
export function usableAuth() {
|
|
20
|
+
const auth = readAuth();
|
|
21
|
+
return auth && !isExpired(auth) ? auth : undefined;
|
|
22
|
+
}
|
|
23
|
+
// budgetMs is how long all requests of the client may take together.
|
|
24
|
+
export function clientFor(auth, budgetMs) {
|
|
25
|
+
const opts = budgetMs === undefined ? {} : { deadline: Date.now() + budgetMs };
|
|
26
|
+
return new TracehubClient(tracehubUrl(), auth.accessToken, opts);
|
|
27
|
+
}
|
|
28
|
+
export function redactOptions() {
|
|
29
|
+
return { homeDir: home(), deny: readDenyList() };
|
|
30
|
+
}
|
|
31
|
+
function reportMasked(masked) {
|
|
32
|
+
for (const m of masked) {
|
|
33
|
+
if (m.findings.length) {
|
|
34
|
+
warn(`${m.session}: masked ${formatFindings(m.findings)} before upload`);
|
|
35
|
+
}
|
|
36
|
+
if (m.withheld) {
|
|
37
|
+
warn(`${m.session}: tracehub withheld ${m.withheld} message(s) that look sensitive`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
// A commit has one trace id and a marker per session.
|
|
42
|
+
export function commitCount(markers) {
|
|
43
|
+
return new Set(markers.map((m) => m.traceId)).size;
|
|
44
|
+
}
|
|
45
|
+
function describeUpload(result) {
|
|
46
|
+
const sessions = new Set(result.uploaded.map((m) => m.session)).size;
|
|
47
|
+
const commits = commitCount(result.uploaded);
|
|
48
|
+
const pending = result.skipped.length
|
|
49
|
+
? `, ${result.skipped.length} left pending`
|
|
50
|
+
: "";
|
|
51
|
+
return `uploaded the traces of ${commits} commit(s) from ${sessions} session(s) to ${tracehubUrl()}${pending}`;
|
|
52
|
+
}
|
|
53
|
+
// Where tracehub shows the sessions of a commit.
|
|
54
|
+
function traceUrls(target, markers) {
|
|
55
|
+
const repo = `${tracehubUrl()}/t/${target.owner}/${target.repo}`;
|
|
56
|
+
return [...new Set(markers.map((m) => `${repo}/${m.traceId}`))];
|
|
57
|
+
}
|
|
58
|
+
// A failure that only means the time ran out: the rest can go on later.
|
|
59
|
+
export function ranOutOfTime(result) {
|
|
60
|
+
return (!!result.failed &&
|
|
61
|
+
/budget exhausted|timeout|timed out/i.test(result.failed.error));
|
|
62
|
+
}
|
|
63
|
+
export function reportUpload(result, target, emit, background) {
|
|
64
|
+
if (result.failed) {
|
|
65
|
+
warn(`WARNING: trace upload incomplete; ${result.failed.what}: ${result.failed.error}`);
|
|
66
|
+
warn(background
|
|
67
|
+
? `Your Git push can continue. The upload goes on in the background (log: ${background}).`
|
|
68
|
+
: "Your Git push can continue. Pending traces are retried on your next push.");
|
|
69
|
+
}
|
|
70
|
+
reportMasked(result.masked);
|
|
71
|
+
for (const ref of result.missing) {
|
|
72
|
+
warn(`session ${formatSessionRef(ref)} not found on this machine; its markers stay pending`);
|
|
73
|
+
}
|
|
74
|
+
for (const session of new Set(result.outside.map((m) => m.session)))
|
|
75
|
+
warn(`session ${session} ran outside the repository and none of its subagents changed it; nothing uploaded`);
|
|
76
|
+
for (const { ref, reason } of result.contextFailed)
|
|
77
|
+
warn(`context ${ref}: ${reason}; uploaded without it`);
|
|
78
|
+
emit(describeUpload(result));
|
|
79
|
+
for (const url of traceUrls(target, result.uploaded))
|
|
80
|
+
emit(url);
|
|
81
|
+
}
|
package/dist/cli/repo.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { getConsent, readConsent } from "../client/consent.js";
|
|
4
|
+
import { gitDir, headTimestampMs, originUrl, remoteUrls } from "../git/git.js";
|
|
5
|
+
import { sameTarget, targetOfUploadRemotes } from "../client/uploadPolicy.js";
|
|
6
|
+
import { pendingCommitCall } from "../local/commitBoundary.js";
|
|
7
|
+
import { sessionLines } from "../local/lines.js";
|
|
8
|
+
import { opencodePendingCommitCall } from "../local/opencode.js";
|
|
9
|
+
import { discoverActiveSessions, ROOT_COMMIT_WINDOW_MS, } from "../local/discover.js";
|
|
10
|
+
import { consentFile, ENV_DISABLE, ENV_SESSION_ID, GIT_STATE_DIR, } from "../local/paths.js";
|
|
11
|
+
import { parseSessionRef, uniqueRefs, } from "../protocol/sessionRef.js";
|
|
12
|
+
import { fail } from "./io.js";
|
|
13
|
+
export function hooksDisabled() {
|
|
14
|
+
return process.env[ENV_DISABLE] === "0";
|
|
15
|
+
}
|
|
16
|
+
// Where the CLI keeps its per-repository state: .git/tracehub.
|
|
17
|
+
export function stateDir(cwd) {
|
|
18
|
+
const git = gitDir(cwd);
|
|
19
|
+
if (!git)
|
|
20
|
+
fail("not a git repository");
|
|
21
|
+
const dir = join(git, GIT_STATE_DIR);
|
|
22
|
+
mkdirSync(dir, { recursive: true });
|
|
23
|
+
return dir;
|
|
24
|
+
}
|
|
25
|
+
function forcedSessions() {
|
|
26
|
+
const forced = process.env[ENV_SESSION_ID] ?? "";
|
|
27
|
+
return forced
|
|
28
|
+
.split(",")
|
|
29
|
+
.map((s) => parseSessionRef(s))
|
|
30
|
+
.filter((ref) => ref !== undefined);
|
|
31
|
+
}
|
|
32
|
+
// The sessions a commit made now would attach: the ones the environment
|
|
33
|
+
// forces, else the ones active since the last commit.
|
|
34
|
+
export function resolveSessions(cwd, root) {
|
|
35
|
+
const forced = forcedSessions();
|
|
36
|
+
if (forced.length)
|
|
37
|
+
return { refs: forced, source: `env ${ENV_SESSION_ID}` };
|
|
38
|
+
const since = headTimestampMs(cwd) ?? Date.now() - ROOT_COMMIT_WINDOW_MS;
|
|
39
|
+
const found = discoverActiveSessions(root, since);
|
|
40
|
+
const committing = found.filter((ref) => ref.committing ??
|
|
41
|
+
(ref.agent === "opencode"
|
|
42
|
+
? opencodePendingCommitCall(ref.id)
|
|
43
|
+
: pendingCommitCall(ref.agent, sessionLines(ref, ref.file))));
|
|
44
|
+
const refs = uniqueRefs((committing.length ? committing : found).map((f) => ({
|
|
45
|
+
agent: f.agent,
|
|
46
|
+
id: f.id,
|
|
47
|
+
})));
|
|
48
|
+
return { refs, source: committing.length ? "active commit" : "discovery" };
|
|
49
|
+
}
|
|
50
|
+
export function consentFor(cwd) {
|
|
51
|
+
const remote = originUrl(cwd);
|
|
52
|
+
if (!remote)
|
|
53
|
+
return undefined;
|
|
54
|
+
return getConsent(readConsent(consentFile()), remote);
|
|
55
|
+
}
|
|
56
|
+
// The repository traces upload to is origin's: every effective fetch/push
|
|
57
|
+
// URL of origin must name it. Other remotes (contributors' forks kept for
|
|
58
|
+
// review) play no part. A push must go to that same repository: the URLs of
|
|
59
|
+
// the remote being pushed to, when it is a configured remote, and the URL Git
|
|
60
|
+
// passes to the hook.
|
|
61
|
+
export function uploadTargetFor(cwd, push) {
|
|
62
|
+
const target = targetOfUploadRemotes(remoteUrls(cwd, "origin"));
|
|
63
|
+
if (!target || !push)
|
|
64
|
+
return target;
|
|
65
|
+
const pushed = [push.url];
|
|
66
|
+
if (push.remote && push.remote !== push.url)
|
|
67
|
+
pushed.push(...remoteUrls(cwd, push.remote));
|
|
68
|
+
const destination = targetOfUploadRemotes(pushed);
|
|
69
|
+
return destination && sameTarget(destination, target) ? target : undefined;
|
|
70
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { styleText } from "node:util";
|
|
3
|
+
import { isCancel, log, text } from "@clack/prompts";
|
|
4
|
+
import { writeAuth } from "../client/auth.js";
|
|
5
|
+
import { awaitTokens, GitHubRefusal, githubClient, loginOf, startDeviceLogin, } from "../client/github.js";
|
|
6
|
+
import { copyToClipboard } from "./clipboard.js";
|
|
7
|
+
import { accent, bold, dim, done, Stopped, waiting } from "./ui.js";
|
|
8
|
+
function browserCommand(url) {
|
|
9
|
+
if (process.platform === "darwin")
|
|
10
|
+
return ["open", [url]];
|
|
11
|
+
if (process.platform === "win32")
|
|
12
|
+
return ["cmd", ["/c", "start", "", url]];
|
|
13
|
+
return ["xdg-open", [url]];
|
|
14
|
+
}
|
|
15
|
+
function openInBrowser(url) {
|
|
16
|
+
const [cmd, args] = browserCommand(url);
|
|
17
|
+
spawn(cmd, args, { detached: true, stdio: "ignore" })
|
|
18
|
+
.on("error", () => { })
|
|
19
|
+
.unref();
|
|
20
|
+
}
|
|
21
|
+
function loginFailure(err) {
|
|
22
|
+
if (!(err instanceof GitHubRefusal))
|
|
23
|
+
return err.message;
|
|
24
|
+
if (err.code === "access_denied")
|
|
25
|
+
return "The sign-in was cancelled in the browser.";
|
|
26
|
+
if (err.code === "expired_token")
|
|
27
|
+
return "The code expired before it was confirmed.";
|
|
28
|
+
return `GitHub refused the sign-in: ${err.message}`;
|
|
29
|
+
}
|
|
30
|
+
// GitHub's device flow, in the browser. The stored sign-in is replaced only
|
|
31
|
+
// once GitHub has authorized and named the account; Stopped when the user
|
|
32
|
+
// stops before that.
|
|
33
|
+
export async function signIn(options) {
|
|
34
|
+
const io = options.streams ?? {};
|
|
35
|
+
const github = githubClient(process.env, options.fetchFn);
|
|
36
|
+
let device;
|
|
37
|
+
try {
|
|
38
|
+
device = await waiting("Asking GitHub for a code", () => startDeviceLogin(github), io);
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
if (err instanceof Stopped)
|
|
42
|
+
throw err;
|
|
43
|
+
throw new Error(`Couldn't reach GitHub to start the sign-in: ${loginFailure(err)}`);
|
|
44
|
+
}
|
|
45
|
+
// The code on a line of its own, so it is easy to read and to select.
|
|
46
|
+
const code = styleText(["bold", "inverse"], ` ${device.userCode} `);
|
|
47
|
+
log.message([
|
|
48
|
+
`Your one-time code ${code === ` ${device.userCode} ` ? bold(device.userCode) : code}`,
|
|
49
|
+
dim(`Enter it at ${device.verificationUri}`),
|
|
50
|
+
].join("\n"), { ...io, symbol: accent("●") });
|
|
51
|
+
const ready = await text({
|
|
52
|
+
...io,
|
|
53
|
+
message: "Press Enter to copy the code and open GitHub",
|
|
54
|
+
placeholder: "Enter ↵",
|
|
55
|
+
defaultValue: "",
|
|
56
|
+
});
|
|
57
|
+
if (isCancel(ready))
|
|
58
|
+
throw new Stopped();
|
|
59
|
+
if (await (options.copy ?? copyToClipboard)(device.userCode))
|
|
60
|
+
done("Code copied", io, 0);
|
|
61
|
+
else
|
|
62
|
+
log.message(dim("No clipboard here: type the code above on that page."), {
|
|
63
|
+
...io,
|
|
64
|
+
spacing: 0,
|
|
65
|
+
});
|
|
66
|
+
(options.openBrowser ?? openInBrowser)(device.verificationUri);
|
|
67
|
+
let auth;
|
|
68
|
+
try {
|
|
69
|
+
auth = await waiting("Waiting for you to authorize tracehub in the browser", async (signal) => {
|
|
70
|
+
const pause = (ms) => new Promise((resolve, reject) => {
|
|
71
|
+
if (signal.aborted)
|
|
72
|
+
return reject(new Stopped());
|
|
73
|
+
const timer = setTimeout(resolve, ms);
|
|
74
|
+
signal.addEventListener("abort", () => {
|
|
75
|
+
clearTimeout(timer);
|
|
76
|
+
reject(new Stopped());
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
const tokens = await awaitTokens(github, device, pause);
|
|
80
|
+
return { login: await loginOf(github, tokens.accessToken), ...tokens };
|
|
81
|
+
}, io);
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
if (err instanceof Stopped)
|
|
85
|
+
throw err;
|
|
86
|
+
throw new Error(loginFailure(err));
|
|
87
|
+
}
|
|
88
|
+
writeAuth(auth);
|
|
89
|
+
return auth;
|
|
90
|
+
}
|
package/dist/cli/ui.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// The look of setup and uninstall, on top of @clack/prompts: one palette,
|
|
2
|
+
// one set of symbols, and a wait indicator that Ctrl-C can stop. Colors go
|
|
3
|
+
// through styleText, which drops them for NO_COLOR, FORCE_COLOR=0 and output
|
|
4
|
+
// that is not a terminal; symbols fall back to ASCII where clack's do.
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { styleText } from "node:util";
|
|
7
|
+
import { log, S_BAR, unicodeOr } from "@clack/prompts";
|
|
8
|
+
// Line by line, so a style survives the guide clack draws before each line.
|
|
9
|
+
const paint = (style) => (text) => text
|
|
10
|
+
.split("\n")
|
|
11
|
+
.map((line) => styleText(style, line))
|
|
12
|
+
.join("\n");
|
|
13
|
+
export const bold = paint("bold");
|
|
14
|
+
export const dim = paint("dim");
|
|
15
|
+
export const accent = paint("cyan");
|
|
16
|
+
export const good = paint("green");
|
|
17
|
+
export const bad = paint("red");
|
|
18
|
+
const S_DONE = unicodeOr("✓", "√");
|
|
19
|
+
const S_STEP = unicodeOr("●", "*");
|
|
20
|
+
const S_SKIP = unicodeOr("–", "-");
|
|
21
|
+
const FRAMES = unicodeOr("◒◐◓◑", "-\\|/").split("");
|
|
22
|
+
// The name in the intro: a badge where there is color.
|
|
23
|
+
export function title(command) {
|
|
24
|
+
const badge = styleText(["bgCyan", "black"], " tracehub ");
|
|
25
|
+
return badge === " tracehub "
|
|
26
|
+
? `tracehub ${command}`
|
|
27
|
+
: `${badge} ${bold(command)}`;
|
|
28
|
+
}
|
|
29
|
+
// "Step 1 of 3 · Account", above the prompts of a step.
|
|
30
|
+
export function step(n, of, name, io) {
|
|
31
|
+
log.message(`${dim(`Step ${n} of ${of} ·`)} ${bold(name)}`, {
|
|
32
|
+
...io,
|
|
33
|
+
symbol: accent(S_STEP),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
// A finished action: "✓ Signed in as bob". `spacing: 0` draws it right
|
|
37
|
+
// under a prompt whose answer is empty.
|
|
38
|
+
export function done(message, io, spacing = 1) {
|
|
39
|
+
log.message(message, { ...io, symbol: good(S_DONE), spacing });
|
|
40
|
+
}
|
|
41
|
+
// Something that was left alone: "– No rule added".
|
|
42
|
+
export function skipped(message, io) {
|
|
43
|
+
log.message(dim(message), { ...io, symbol: dim(S_SKIP) });
|
|
44
|
+
}
|
|
45
|
+
// Lines of label and value, the labels padded to one column.
|
|
46
|
+
export function rows(entries) {
|
|
47
|
+
const width = Math.max(...entries.map(([label]) => label.length));
|
|
48
|
+
return entries
|
|
49
|
+
.map(([label, value]) => `${dim(label.padEnd(width))} ${value}`)
|
|
50
|
+
.join("\n");
|
|
51
|
+
}
|
|
52
|
+
// A path under the home directory as ~/….
|
|
53
|
+
export function tilde(path) {
|
|
54
|
+
const home = homedir();
|
|
55
|
+
return path === home || path.startsWith(`${home}/`)
|
|
56
|
+
? `~${path.slice(home.length)}`
|
|
57
|
+
: path;
|
|
58
|
+
}
|
|
59
|
+
export const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
60
|
+
export class Stopped extends Error {
|
|
61
|
+
constructor() {
|
|
62
|
+
super("stopped");
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// Shows `message` with a spinner until `work` settles; Ctrl-C (or Escape)
|
|
66
|
+
// stops waiting: the AbortSignal given to `work` fires and Stopped is thrown.
|
|
67
|
+
// Work done in under 200 ms shows nothing. Without a terminal it draws one
|
|
68
|
+
// line instead of animating.
|
|
69
|
+
export async function waiting(message, work, io) {
|
|
70
|
+
const output = (io.output ?? process.stdout);
|
|
71
|
+
const input = (io.input ?? process.stdin);
|
|
72
|
+
const animate = output.isTTY === true;
|
|
73
|
+
const abort = new AbortController();
|
|
74
|
+
let stop = () => { };
|
|
75
|
+
const stopped = new Promise((_, reject) => {
|
|
76
|
+
stop = () => {
|
|
77
|
+
abort.abort();
|
|
78
|
+
reject(new Stopped());
|
|
79
|
+
};
|
|
80
|
+
});
|
|
81
|
+
stopped.catch(() => { });
|
|
82
|
+
const onKey = (chunk) => {
|
|
83
|
+
const key = String(chunk);
|
|
84
|
+
if (key.includes("\x03") || key === "\x1b")
|
|
85
|
+
stop();
|
|
86
|
+
};
|
|
87
|
+
const raw = input.isTTY === true && !input.isRaw;
|
|
88
|
+
if (raw)
|
|
89
|
+
input.setRawMode(true);
|
|
90
|
+
input.on("data", onKey);
|
|
91
|
+
input.resume();
|
|
92
|
+
let frame = 0;
|
|
93
|
+
let drawn = false;
|
|
94
|
+
const line = () => `${accent(FRAMES[frame++ % FRAMES.length])} ${message} ${dim("(Ctrl-C to stop)")}`;
|
|
95
|
+
const draw = () => {
|
|
96
|
+
if (!drawn) {
|
|
97
|
+
output.write(`${styleText("gray", S_BAR)}\n`);
|
|
98
|
+
drawn = true;
|
|
99
|
+
if (!animate) {
|
|
100
|
+
output.write(`${line()}\n`);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
output.write("\x1b[?25l");
|
|
104
|
+
}
|
|
105
|
+
if (animate)
|
|
106
|
+
output.write(`\r\x1b[2K${line()}`);
|
|
107
|
+
};
|
|
108
|
+
const late = setTimeout(draw, 200);
|
|
109
|
+
const timer = animate ? setInterval(() => drawn && draw(), 100) : undefined;
|
|
110
|
+
const clear = () => {
|
|
111
|
+
clearTimeout(late);
|
|
112
|
+
clearInterval(timer);
|
|
113
|
+
input.off("data", onKey);
|
|
114
|
+
input.pause();
|
|
115
|
+
if (raw)
|
|
116
|
+
input.setRawMode(false);
|
|
117
|
+
if (drawn && animate)
|
|
118
|
+
// The spinner gives way to what comes next: on success the result
|
|
119
|
+
// brings its own guide line, so that one goes too.
|
|
120
|
+
output.write(abort.signal.aborted
|
|
121
|
+
? "\r\x1b[2K\x1b[?25h"
|
|
122
|
+
: "\r\x1b[2K\x1b[1A\x1b[2K\r\x1b[?25h");
|
|
123
|
+
};
|
|
124
|
+
try {
|
|
125
|
+
return await Promise.race([work(abort.signal), stopped]);
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
clear();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Every command, flag and environment variable of the CLI, in one place: `tracehub --help` and the docs' CLI reference
|
|
2
|
+
// page (docs/pages/cli-reference.mdx, through `virtual:cli-reference` in docs/vite.config.ts) are both rendered from
|
|
3
|
+
// here, so they can't disagree. cli.ts dispatches by `name`, typed against this list. The Git hooks' entry point,
|
|
4
|
+
// `tracehub hook prepare-commit-msg|pre-push`, is internal and left out.
|
|
5
|
+
import { styleText } from "node:util";
|
|
6
|
+
import { ENV_TRACEHUB } from "../client/tracehub.js";
|
|
7
|
+
import { ENV_CONTEXT, ENV_DISABLE, ENV_SESSION_ID } from "../local/paths.js";
|
|
8
|
+
export const COMMANDS = [
|
|
9
|
+
{
|
|
10
|
+
name: "setup",
|
|
11
|
+
usage: "setup",
|
|
12
|
+
summary: "sign in, choose where sessions upload, and install the Git hooks",
|
|
13
|
+
about: "Each step is saved as you go, so stopping with Ctrl-C keeps the steps already done. Needs an interactive terminal.",
|
|
14
|
+
steps: [
|
|
15
|
+
[
|
|
16
|
+
"Account",
|
|
17
|
+
"keep the GitHub account you're signed in with, or sign in with another one in the browser",
|
|
18
|
+
],
|
|
19
|
+
[
|
|
20
|
+
"Permission rules",
|
|
21
|
+
"allow or revoke uploads for a GitHub organization (owner) or repository (owner/repo); only allowed repositories get traces. The rules are registered with TraceHub for its roster; offline, on the next push or setup",
|
|
22
|
+
],
|
|
23
|
+
[
|
|
24
|
+
"Git hooks",
|
|
25
|
+
"install, keep or remove the global Git hooks that attach sessions on commit and upload them on push",
|
|
26
|
+
],
|
|
27
|
+
],
|
|
28
|
+
examples: ["tracehub setup"],
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: "uninstall",
|
|
32
|
+
usage: "uninstall",
|
|
33
|
+
summary: "remove the Git hooks, the permission rules and the sign-in",
|
|
34
|
+
about: "Lists what it removes and asks first. Restores the global Git hooks setting from before setup, then asks whether to delete the deny list and this repository's local trace state too. Needs an interactive terminal.",
|
|
35
|
+
examples: ["tracehub uninstall"],
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
name: "providers",
|
|
39
|
+
usage: "providers add|list|remove",
|
|
40
|
+
summary: "register the local commands that print context conversations",
|
|
41
|
+
about: "add <name> [--timeout <ms>] -- <command…> registers a provider: a command, run without a shell, with every {id} replaced by a conversation's id, that prints its messages as a JSON list of {id?, author, text, at, source: {kind, url?, label?}}. A session names a conversation with a \"tracehub-context: <name>:<id>\" line in its first message (or a subagent's brief), or a commit with TRACEHUB_CONTEXT; the provider runs on upload, only for allowed repositories. list prints them; remove <name> removes one. Kept in ~/.config/tracehub/providers.json.",
|
|
42
|
+
examples: [
|
|
43
|
+
"tracehub providers add nomos -- nomos thread export {id} --format tracehub",
|
|
44
|
+
"tracehub providers list",
|
|
45
|
+
"tracehub providers remove nomos",
|
|
46
|
+
],
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: "context",
|
|
50
|
+
usage: "context add|remove --pr <n> (<provider>:<id>… | --from <file>)",
|
|
51
|
+
summary: "attach or detach the context of a pull request",
|
|
52
|
+
about: "Fetches each conversation from its provider, or reads messages in a provider's format from --from <file> or \"-\" (stdin), redacts them like a trace, and attaches them to the pull request of this clone's repository; running it again replaces messages by id. --dry-run prints what would be attached and sends nothing. Needs a sign-in and a permission rule, as traces do. remove --pr <number> <provider>:<id>… detaches conversations, whoever attached them (a pasted one is manual:<id>, as the pull request's .json shows), and renders the page again; it needs a sign-in with push access to the repository, as add does, but no permission rule.",
|
|
53
|
+
examples: [
|
|
54
|
+
"tracehub context add --pr 12 nomos:t_16da1c327635",
|
|
55
|
+
"tracehub context add --pr 12 --from messages.json",
|
|
56
|
+
"tracehub context remove --pr 12 manual:5f2de08703b94d2b",
|
|
57
|
+
],
|
|
58
|
+
},
|
|
59
|
+
];
|
|
60
|
+
export const ENV = [
|
|
61
|
+
{
|
|
62
|
+
name: ENV_SESSION_ID,
|
|
63
|
+
value: "<claude|codex|opencode>:<id>",
|
|
64
|
+
description: "attach this session to the commit",
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
name: ENV_CONTEXT,
|
|
68
|
+
value: "<provider>:<id>",
|
|
69
|
+
description: "attach this context conversation to the commit's sessions",
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
name: ENV_DISABLE,
|
|
73
|
+
value: "0",
|
|
74
|
+
description: "skip the hooks for one command",
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
name: ENV_TRACEHUB,
|
|
78
|
+
value: "<url>",
|
|
79
|
+
description: "use another Tracehub server",
|
|
80
|
+
},
|
|
81
|
+
];
|
|
82
|
+
const WIDTH = 80;
|
|
83
|
+
/** `text` wrapped to WIDTH, every line after the first indented by `indent` spaces. */
|
|
84
|
+
function wrap(text, indent) {
|
|
85
|
+
const lines = [];
|
|
86
|
+
let line = "";
|
|
87
|
+
for (const word of text.split(" ")) {
|
|
88
|
+
if (line && indent + line.length + 1 + word.length > WIDTH) {
|
|
89
|
+
lines.push(line);
|
|
90
|
+
line = word;
|
|
91
|
+
}
|
|
92
|
+
else
|
|
93
|
+
line = line ? `${line} ${word}` : word;
|
|
94
|
+
}
|
|
95
|
+
lines.push(line);
|
|
96
|
+
return lines.map((l, i) => (i ? " ".repeat(indent) + l : l));
|
|
97
|
+
}
|
|
98
|
+
/** Rows of a left column and a wrapped right one. */
|
|
99
|
+
function table(entries) {
|
|
100
|
+
const column = Math.max(...entries.map(([left]) => left.length)) + 4;
|
|
101
|
+
return entries.flatMap(([left, right]) => {
|
|
102
|
+
const lines = wrap(right, column);
|
|
103
|
+
lines[0] = ` ${left}`.padEnd(column) + lines[0];
|
|
104
|
+
return lines;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const capital = (text) => text[0].toUpperCase() + text.slice(1);
|
|
108
|
+
/** Bold headings where `styled` and the terminal allow it. */
|
|
109
|
+
function heading(text, styled) {
|
|
110
|
+
return styled ? styleText("bold", text) : text;
|
|
111
|
+
}
|
|
112
|
+
/** `tracehub --help`. Plain text unless `styled`, which the CLI asks for. */
|
|
113
|
+
export function usage(styled = false) {
|
|
114
|
+
return [
|
|
115
|
+
"tracehub: attach coding-agent sessions to your commits and pull requests",
|
|
116
|
+
"",
|
|
117
|
+
heading("Usage", styled),
|
|
118
|
+
" tracehub <command>",
|
|
119
|
+
"",
|
|
120
|
+
heading("Commands", styled),
|
|
121
|
+
...table(COMMANDS.map((c) => [c.usage, capital(c.summary)])),
|
|
122
|
+
"",
|
|
123
|
+
heading("Environment", styled),
|
|
124
|
+
...table(ENV.map((e) => [`${e.name}=${e.value}`, capital(e.description)])),
|
|
125
|
+
"",
|
|
126
|
+
'Run "tracehub <command> --help" for more.',
|
|
127
|
+
"",
|
|
128
|
+
].join("\n");
|
|
129
|
+
}
|
|
130
|
+
/** `tracehub <command> --help`. */
|
|
131
|
+
export function commandUsage(name) {
|
|
132
|
+
const command = COMMANDS.find((c) => c.name === name);
|
|
133
|
+
return [
|
|
134
|
+
`Usage: tracehub ${command.usage}`,
|
|
135
|
+
"",
|
|
136
|
+
...wrap(`${capital(command.summary)}.`, 0),
|
|
137
|
+
...(command.steps
|
|
138
|
+
? [
|
|
139
|
+
"",
|
|
140
|
+
...table(command.steps.map(([step, text], i) => [
|
|
141
|
+
`${i + 1}. ${step}`,
|
|
142
|
+
capital(text),
|
|
143
|
+
])),
|
|
144
|
+
]
|
|
145
|
+
: []),
|
|
146
|
+
...(command.about ? ["", ...wrap(command.about, 0)] : []),
|
|
147
|
+
...(command.examples
|
|
148
|
+
? ["", "Example", ...command.examples.map((e) => ` ${e}`)]
|
|
149
|
+
: []),
|
|
150
|
+
].join("\n");
|
|
151
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from "./cli/args.js";
|
|
3
|
+
import { cmdHook } from "./cli/commands/hook.js";
|
|
4
|
+
import { cmdContext } from "./cli/commands/context.js";
|
|
5
|
+
import { cmdProviders } from "./cli/commands/providers.js";
|
|
6
|
+
import { cmdSetup } from "./cli/commands/setup.js";
|
|
7
|
+
import { cmdUninstall } from "./cli/commands/uninstall.js";
|
|
8
|
+
import { fail, Reported } from "./cli/io.js";
|
|
9
|
+
import { usage } from "./cli/usage.js";
|
|
10
|
+
const COMMAND_HANDLERS = {
|
|
11
|
+
setup: cmdSetup,
|
|
12
|
+
uninstall: cmdUninstall,
|
|
13
|
+
providers: cmdProviders,
|
|
14
|
+
context: cmdContext,
|
|
15
|
+
};
|
|
16
|
+
async function main() {
|
|
17
|
+
const args = parseArgs(process.argv.slice(2));
|
|
18
|
+
const name = args.positional[0];
|
|
19
|
+
// What the Git hooks run; internal, so not in the usage.
|
|
20
|
+
if (name === "hook")
|
|
21
|
+
return cmdHook(args, process.cwd());
|
|
22
|
+
if (name && Object.hasOwn(COMMAND_HANDLERS, name)) {
|
|
23
|
+
await COMMAND_HANDLERS[name](args, process.cwd());
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
process.stdout.write(usage(true));
|
|
27
|
+
if (name && !args.flags["help"] && !args.flags["h"] && name !== "help") {
|
|
28
|
+
process.stderr.write(`\ntracehub: unknown command "${name}"\n`);
|
|
29
|
+
process.exit(1);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
main().catch((err) => {
|
|
33
|
+
if (process.argv[2] === "hook")
|
|
34
|
+
process.exit(0);
|
|
35
|
+
if (err instanceof Reported)
|
|
36
|
+
process.exit(1);
|
|
37
|
+
fail(err.message);
|
|
38
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { readJsonObject } from "../local/files.js";
|
|
4
|
+
import { configDir } from "../local/paths.js";
|
|
5
|
+
import { GitHubRefusal, githubClient, refreshTokens, } from "./github.js";
|
|
6
|
+
const REFRESH_BEFORE_EXPIRY_MS = 5 * 60 * 1000;
|
|
7
|
+
export class AuthError extends Error {
|
|
8
|
+
}
|
|
9
|
+
export function authFile() {
|
|
10
|
+
return join(configDir(), "auth.json");
|
|
11
|
+
}
|
|
12
|
+
export function readAuth() {
|
|
13
|
+
const { login, accessToken, refreshToken, expiresAt } = readJsonObject(authFile());
|
|
14
|
+
if (typeof login !== "string" || typeof accessToken !== "string") {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
if (typeof expiresAt !== "number")
|
|
18
|
+
return undefined;
|
|
19
|
+
return {
|
|
20
|
+
login,
|
|
21
|
+
accessToken,
|
|
22
|
+
refreshToken: typeof refreshToken === "string" ? refreshToken : null,
|
|
23
|
+
expiresAt,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export function writeAuth(auth) {
|
|
27
|
+
const file = authFile();
|
|
28
|
+
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
29
|
+
writeFileSync(file, `${JSON.stringify(auth, null, 2)}\n`, { mode: 0o600 });
|
|
30
|
+
chmodSync(file, 0o600);
|
|
31
|
+
return file;
|
|
32
|
+
}
|
|
33
|
+
export function clearAuth() {
|
|
34
|
+
const file = authFile();
|
|
35
|
+
const existed = existsSync(file);
|
|
36
|
+
rmSync(file, { force: true });
|
|
37
|
+
return existed;
|
|
38
|
+
}
|
|
39
|
+
// Without a refresh token the login ends with the access token.
|
|
40
|
+
export function isExpired(auth, now = Date.now()) {
|
|
41
|
+
return auth.expiresAt <= now && !auth.refreshToken;
|
|
42
|
+
}
|
|
43
|
+
function refreshFailure(err) {
|
|
44
|
+
if (err instanceof GitHubRefusal) {
|
|
45
|
+
return new AuthError(`your tracehub sign-in expired (GitHub answered ${err.code}); run "tracehub setup" to sign in again`);
|
|
46
|
+
}
|
|
47
|
+
const reason = err.message;
|
|
48
|
+
return new AuthError(`could not refresh the tracehub sign-in: ${reason}`);
|
|
49
|
+
}
|
|
50
|
+
// The sign-in with an access token that has time left, refreshed through
|
|
51
|
+
// GitHub otherwise; a rotated set replaces the file, and a sign-in GitHub
|
|
52
|
+
// refuses is forgotten so the next command asks for "tracehub setup".
|
|
53
|
+
export async function freshAuth(auth, env = process.env, fetchFn) {
|
|
54
|
+
const { refreshToken } = auth;
|
|
55
|
+
if (!refreshToken || auth.expiresAt - Date.now() > REFRESH_BEFORE_EXPIRY_MS) {
|
|
56
|
+
return auth;
|
|
57
|
+
}
|
|
58
|
+
let tokens;
|
|
59
|
+
try {
|
|
60
|
+
tokens = await refreshTokens(githubClient(env, fetchFn), refreshToken);
|
|
61
|
+
}
|
|
62
|
+
catch (err) {
|
|
63
|
+
if (err instanceof GitHubRefusal)
|
|
64
|
+
clearAuth();
|
|
65
|
+
throw refreshFailure(err);
|
|
66
|
+
}
|
|
67
|
+
const next = { login: auth.login, ...tokens };
|
|
68
|
+
writeAuth(next);
|
|
69
|
+
return next;
|
|
70
|
+
}
|