conare 0.7.4 → 0.9.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 +217 -0
- package/dist/cli/args.js +69 -0
- package/dist/cli/config.js +37 -0
- package/dist/cli/documents.js +82 -0
- package/dist/cli/main.js +127 -0
- package/dist/cli/project.js +61 -0
- package/dist/cli/render.js +69 -0
- package/dist/cli/schedule.js +177 -0
- package/dist/cli/scrub.js +102 -0
- package/dist/cli/sources/claude.js +313 -0
- package/dist/cli/sources/codex.js +266 -0
- package/dist/cli/state.js +87 -0
- package/dist/cli/sync.js +186 -0
- package/dist/cli/transcript.js +103 -0
- package/dist/cli/upload.js +137 -0
- package/dist/index.d.ts +190 -0
- package/dist/index.js +283 -6693
- package/package.json +22 -28
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// The background schedule: `conare sync --quiet` every 10 minutes, from a copy of the built
|
|
2
|
+
// package under ~/.conare/sync/<version>/ so it does not depend on the npx cache.
|
|
3
|
+
// macOS: a launchd agent. Linux: a systemd user timer.
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { join, resolve } from "node:path";
|
|
8
|
+
export const LABEL = "ai.conare.sync";
|
|
9
|
+
export const UNIT = "conare-sync";
|
|
10
|
+
export const INTERVAL_SECONDS = 600;
|
|
11
|
+
/** Variables passed on to the scheduled run when set at install time. */
|
|
12
|
+
export const PASSED_ENV = ["CONARE_BASE_URL", "CLAUDE_CONFIG_DIR", "CODEX_HOME"];
|
|
13
|
+
/**
|
|
14
|
+
* Copy the built package (the directory holding index.js and cli/) to <root>/<version> and
|
|
15
|
+
* return the installed script path. Other versions stay until the new schedule is loaded
|
|
16
|
+
* (pruneVersions), so a failed reinstall leaves the running schedule its script.
|
|
17
|
+
*/
|
|
18
|
+
export function installCopy(distDir, root, version) {
|
|
19
|
+
if (!existsSync(join(distDir, "cli", "main.js")) || !existsSync(join(distDir, "index.js"))) {
|
|
20
|
+
throw new Error("Install from the published package: npx conare sync --install");
|
|
21
|
+
}
|
|
22
|
+
const target = join(root, version);
|
|
23
|
+
if (resolve(distDir) !== resolve(target)) {
|
|
24
|
+
rmSync(target, { recursive: true, force: true });
|
|
25
|
+
mkdirSync(target, { recursive: true });
|
|
26
|
+
cpSync(distDir, target, { recursive: true });
|
|
27
|
+
// The files are ES modules; outside the package, Node needs to be told.
|
|
28
|
+
writeFileSync(join(target, "package.json"), `${JSON.stringify({ type: "module", private: true })}\n`);
|
|
29
|
+
}
|
|
30
|
+
return join(target, "cli", "main.js");
|
|
31
|
+
}
|
|
32
|
+
/** Remove every installed version but `version`, once the schedule runs it. */
|
|
33
|
+
export function pruneVersions(root, version) {
|
|
34
|
+
for (const entry of readdirSync(root)) {
|
|
35
|
+
if (entry !== version)
|
|
36
|
+
rmSync(join(root, entry), { recursive: true, force: true });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// ---- launchd ---------------------------------------------------------------
|
|
40
|
+
export function launchdPlistPath(home = homedir()) {
|
|
41
|
+
return join(home, "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
42
|
+
}
|
|
43
|
+
export function launchdPlist(job) {
|
|
44
|
+
const args = [job.node, job.script, "sync", "--quiet"].map((a) => ` <string>${xml(a)}</string>`).join("\n");
|
|
45
|
+
const env = Object.entries(job.env)
|
|
46
|
+
.map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`)
|
|
47
|
+
.join("\n");
|
|
48
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
49
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
50
|
+
<plist version="1.0">
|
|
51
|
+
<dict>
|
|
52
|
+
<key>Label</key>
|
|
53
|
+
<string>${LABEL}</string>
|
|
54
|
+
<key>ProgramArguments</key>
|
|
55
|
+
<array>
|
|
56
|
+
${args}
|
|
57
|
+
</array>
|
|
58
|
+
<key>StartInterval</key>
|
|
59
|
+
<integer>${INTERVAL_SECONDS}</integer>
|
|
60
|
+
<key>RunAtLoad</key>
|
|
61
|
+
<true/>
|
|
62
|
+
<key>ProcessType</key>
|
|
63
|
+
<string>Background</string>
|
|
64
|
+
<key>StandardOutPath</key>
|
|
65
|
+
<string>${xml(job.logFile)}</string>
|
|
66
|
+
<key>StandardErrorPath</key>
|
|
67
|
+
<string>${xml(job.logFile)}</string>
|
|
68
|
+
${env ? ` <key>EnvironmentVariables</key>\n <dict>\n${env}\n </dict>\n` : ""}</dict>
|
|
69
|
+
</plist>
|
|
70
|
+
`;
|
|
71
|
+
}
|
|
72
|
+
function xml(s) {
|
|
73
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
74
|
+
}
|
|
75
|
+
// ---- systemd ---------------------------------------------------------------
|
|
76
|
+
export function systemdDir(env = process.env, home = homedir()) {
|
|
77
|
+
return join(env.XDG_CONFIG_HOME || join(home, ".config"), "systemd", "user");
|
|
78
|
+
}
|
|
79
|
+
export function systemdService(job) {
|
|
80
|
+
const exec = [job.node, job.script, "sync", "--quiet"].map(quoteArg).join(" ");
|
|
81
|
+
const env = Object.entries(job.env).map(([k, v]) => `Environment=${quoteArg(`${k}=${v}`)}\n`).join("");
|
|
82
|
+
return `[Unit]
|
|
83
|
+
Description=Conare sync of Claude Code and Codex sessions
|
|
84
|
+
|
|
85
|
+
[Service]
|
|
86
|
+
Type=oneshot
|
|
87
|
+
ExecStart=${exec}
|
|
88
|
+
${env}StandardOutput=append:${unitPath(job.logFile)}
|
|
89
|
+
StandardError=append:${unitPath(job.logFile)}
|
|
90
|
+
Nice=10
|
|
91
|
+
`;
|
|
92
|
+
}
|
|
93
|
+
export function systemdTimer() {
|
|
94
|
+
return `[Unit]
|
|
95
|
+
Description=Run the Conare sync every 10 minutes
|
|
96
|
+
|
|
97
|
+
[Timer]
|
|
98
|
+
OnCalendar=*:0/10
|
|
99
|
+
Persistent=true
|
|
100
|
+
|
|
101
|
+
[Install]
|
|
102
|
+
WantedBy=timers.target
|
|
103
|
+
`;
|
|
104
|
+
}
|
|
105
|
+
/** A double-quoted systemd argument: quotes and backslashes escaped, % doubled (specifiers). */
|
|
106
|
+
function quoteArg(s) {
|
|
107
|
+
return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
|
|
108
|
+
}
|
|
109
|
+
function unitPath(s) {
|
|
110
|
+
return s.replace(/%/g, "%%");
|
|
111
|
+
}
|
|
112
|
+
const run = (cmd, args) => {
|
|
113
|
+
execFileSync(cmd, args, { stdio: "ignore" });
|
|
114
|
+
};
|
|
115
|
+
function tryRun(r, cmd, args) {
|
|
116
|
+
try {
|
|
117
|
+
r(cmd, args);
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Write and load the schedule. Returns a short description of what was installed. */
|
|
125
|
+
export function installSchedule(job, s) {
|
|
126
|
+
const r = s.run ?? run;
|
|
127
|
+
const home = s.home ?? homedir();
|
|
128
|
+
if (s.platform === "darwin") {
|
|
129
|
+
const plist = launchdPlistPath(home);
|
|
130
|
+
mkdirSync(join(home, "Library", "LaunchAgents"), { recursive: true });
|
|
131
|
+
writeFileSync(plist, launchdPlist(job));
|
|
132
|
+
const domain = `gui/${s.uid ?? process.getuid?.() ?? 0}`;
|
|
133
|
+
tryRun(r, "launchctl", ["bootout", `${domain}/${LABEL}`]);
|
|
134
|
+
if (!tryRun(r, "launchctl", ["bootstrap", domain, plist]))
|
|
135
|
+
r("launchctl", ["load", "-w", plist]);
|
|
136
|
+
return `launchd agent ${plist}`;
|
|
137
|
+
}
|
|
138
|
+
if (s.platform === "linux") {
|
|
139
|
+
const dir = systemdDir(s.env, home);
|
|
140
|
+
mkdirSync(dir, { recursive: true });
|
|
141
|
+
writeFileSync(join(dir, `${UNIT}.service`), systemdService(job));
|
|
142
|
+
writeFileSync(join(dir, `${UNIT}.timer`), systemdTimer());
|
|
143
|
+
r("systemctl", ["--user", "daemon-reload"]);
|
|
144
|
+
r("systemctl", ["--user", "enable", "--now", `${UNIT}.timer`]);
|
|
145
|
+
return `systemd user timer ${join(dir, `${UNIT}.timer`)}`;
|
|
146
|
+
}
|
|
147
|
+
throw new Error(`--install supports macOS and Linux. On ${s.platform}, run \`npx conare sync --quiet\` every 10 minutes with your scheduler.`);
|
|
148
|
+
}
|
|
149
|
+
/** Stop and remove the schedule. Returns false when there was nothing to remove. */
|
|
150
|
+
export function uninstallSchedule(s) {
|
|
151
|
+
const r = s.run ?? run;
|
|
152
|
+
const home = s.home ?? homedir();
|
|
153
|
+
if (s.platform === "darwin") {
|
|
154
|
+
const plist = launchdPlistPath(home);
|
|
155
|
+
const domain = `gui/${s.uid ?? process.getuid?.() ?? 0}`;
|
|
156
|
+
if (!tryRun(r, "launchctl", ["bootout", `${domain}/${LABEL}`]))
|
|
157
|
+
tryRun(r, "launchctl", ["unload", plist]);
|
|
158
|
+
return remove(plist);
|
|
159
|
+
}
|
|
160
|
+
if (s.platform === "linux") {
|
|
161
|
+
const dir = systemdDir(s.env, home);
|
|
162
|
+
tryRun(r, "systemctl", ["--user", "disable", "--now", `${UNIT}.timer`]);
|
|
163
|
+
const removed = [remove(join(dir, `${UNIT}.timer`)), remove(join(dir, `${UNIT}.service`))].some(Boolean);
|
|
164
|
+
tryRun(r, "systemctl", ["--user", "daemon-reload"]);
|
|
165
|
+
return removed;
|
|
166
|
+
}
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
function remove(path) {
|
|
170
|
+
try {
|
|
171
|
+
unlinkSync(path);
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Secret scrubbing. Every document text passes through scrub() before it is hashed or
|
|
2
|
+
// uploaded. A rule replaces the secret itself (not the label in front of it) with
|
|
3
|
+
// [REDACTED:<kind>]. Specific key formats run before the generic rules, and a redaction
|
|
4
|
+
// marker never matches again, so scrub(scrub(x)) === scrub(x).
|
|
5
|
+
const hasDigit = (s) => /\d/.test(s);
|
|
6
|
+
const REFERENCE = /^[$%{<([~/.#*]|\(|\$\{|\{\{|->|::/; // $VAR, %VAR%, {{x}}, <token>, [REDACTED:…], paths, calls
|
|
7
|
+
const DOTTED = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)+$/; // process.env.TOKEN, config.auth.token
|
|
8
|
+
const CODE = /[([]/; // readPassword(prompt), os.environ["TOKEN"]
|
|
9
|
+
const ENV_NAME = /^[A-Z][A-Z0-9_]*$/; // GITHUB_TOKEN, YOUR_TOKEN_HERE
|
|
10
|
+
const TYPE_OR_LITERAL = /^(?:string|number|boolean|null|none|nil|undefined|true|false|required|optional)$/i;
|
|
11
|
+
/**
|
|
12
|
+
* The value of password=…, token: … and the like, unless it is code, a variable name or a
|
|
13
|
+
* placeholder. Any other value counts, letters or digits alone included: a chosen password
|
|
14
|
+
* ("supersecretpassword") or a numeric token is still a secret.
|
|
15
|
+
*/
|
|
16
|
+
function assignedSecret(value) {
|
|
17
|
+
return !(REFERENCE.test(value) || DOTTED.test(value) || CODE.test(value) || ENV_NAME.test(value) || TYPE_OR_LITERAL.test(value));
|
|
18
|
+
}
|
|
19
|
+
/** An Authorization value: anything but a reference, a dotted name or a short plain word. */
|
|
20
|
+
function credentialLike(value) {
|
|
21
|
+
if (REFERENCE.test(value) || DOTTED.test(value))
|
|
22
|
+
return false;
|
|
23
|
+
return !/^[A-Za-z]+$/.test(value) || value.length >= 24;
|
|
24
|
+
}
|
|
25
|
+
const RULES = [
|
|
26
|
+
// PEM private keys: the whole block, or the base64 lines after a header whose END is missing.
|
|
27
|
+
{
|
|
28
|
+
kind: "private_key",
|
|
29
|
+
re: /-----BEGIN[A-Z0-9 ]{0,30} PRIVATE KEY(?: BLOCK)?-----(?:[A-Za-z0-9+/=\s\\:,.-]{0,16384}?-----END[A-Z0-9 ]{0,30} PRIVATE KEY(?: BLOCK)?-----|(?:(?:\r?\n|\\n)[A-Za-z0-9+/=]{16,})*)/g,
|
|
30
|
+
},
|
|
31
|
+
{ kind: "conare_key", re: /\b(?:sk-conare-|cmem_)[A-Za-z0-9]{16,}/g },
|
|
32
|
+
{ kind: "anthropic_key", re: /\bsk-ant-[A-Za-z0-9_-]{20,}/g },
|
|
33
|
+
// OpenAI (sk-, sk-proj-, sk-svcacct-), OpenRouter (sk-or-v1-), DeepSeek and the like. A
|
|
34
|
+
// hyphenated slug ("sk-some-component-name") has no digit, or is short and lowercase.
|
|
35
|
+
{
|
|
36
|
+
kind: "api_key",
|
|
37
|
+
re: /\bsk-[A-Za-z0-9][A-Za-z0-9_-]{19,}/g,
|
|
38
|
+
accept: (s) => hasDigit(s) && (/[A-Z]/.test(s) || s.length >= 35),
|
|
39
|
+
},
|
|
40
|
+
{ kind: "github_token", re: /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})/g },
|
|
41
|
+
{ kind: "aws_access_key", re: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g },
|
|
42
|
+
{ kind: "slack_token", re: /\bxox[abposr]-[A-Za-z0-9-]{10,}/g },
|
|
43
|
+
{ kind: "google_api_key", re: /\bAIza[0-9A-Za-z_-]{35}/g },
|
|
44
|
+
{ kind: "jwt", re: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g },
|
|
45
|
+
// Authorization: Bearer <token>, also Basic/Token/Bot, JSON and curl -H forms.
|
|
46
|
+
{
|
|
47
|
+
kind: "bearer_token",
|
|
48
|
+
re: /(\bAuthorization["']?\s*[:=]\s*["']?(?:(?:Bearer|Basic|Token|Bot)\s+)?)([^\s"'`,;]{8,})/gi,
|
|
49
|
+
label: true,
|
|
50
|
+
accept: credentialLike,
|
|
51
|
+
},
|
|
52
|
+
{ kind: "bearer_token", re: /(\bBearer\s+)([A-Za-z0-9._~+/-]{16,}=*)/g, label: true, accept: hasDigit },
|
|
53
|
+
// scheme://user:password@host
|
|
54
|
+
{
|
|
55
|
+
kind: "password",
|
|
56
|
+
re: /(\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@"'<>]+:)([^\s@/"'<>]{3,})(?=@)/gi,
|
|
57
|
+
label: true,
|
|
58
|
+
accept: (s) => !/^[$%{<[]/.test(s),
|
|
59
|
+
},
|
|
60
|
+
// password=…, secret: "…", api_key=…, token=…; the keyword ends the name, so
|
|
61
|
+
// max_tokens=4096 and tokenizer=… are not matched. A password is chosen by a person and
|
|
62
|
+
// can be short (6+); the other values are generated (12+).
|
|
63
|
+
{
|
|
64
|
+
kind: "secret",
|
|
65
|
+
re: /((?:password|passwd)["']?\s*[:=]\s*["']?)([^\s"'`,;)}\]]{6,})/gi,
|
|
66
|
+
label: true,
|
|
67
|
+
accept: assignedSecret,
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
kind: "secret",
|
|
71
|
+
re: /((?:secret|token|api[_-]?key|access[_-]?key|private[_-]?key)["']?\s*[:=]\s*["']?)([^\s"'`,;)}\]]{12,})/gi,
|
|
72
|
+
label: true,
|
|
73
|
+
accept: assignedSecret,
|
|
74
|
+
},
|
|
75
|
+
// --password …, --token=…
|
|
76
|
+
{
|
|
77
|
+
kind: "secret",
|
|
78
|
+
re: /(--(?:password|passwd)(?:=|\s+)["']?)([^\s"'`]{6,})/gi,
|
|
79
|
+
label: true,
|
|
80
|
+
accept: assignedSecret,
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
kind: "secret",
|
|
84
|
+
re: /(--(?:secret|token|api-key|access-key|auth-token|client-secret)(?:=|\s+)["']?)([^\s"'`]{12,})/gi,
|
|
85
|
+
label: true,
|
|
86
|
+
accept: assignedSecret,
|
|
87
|
+
},
|
|
88
|
+
];
|
|
89
|
+
/** Replace every secret in text with [REDACTED:<kind>]. */
|
|
90
|
+
export function scrub(text) {
|
|
91
|
+
let out = text;
|
|
92
|
+
for (const rule of RULES) {
|
|
93
|
+
out = out.replace(rule.re, (match, group1) => {
|
|
94
|
+
const label = rule.label ? String(group1) : "";
|
|
95
|
+
const secret = match.slice(label.length);
|
|
96
|
+
if (rule.accept && !rule.accept(secret))
|
|
97
|
+
return match;
|
|
98
|
+
return `${label}[REDACTED:${rule.kind}]`;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// Claude Code transcripts.
|
|
2
|
+
//
|
|
3
|
+
// Layout (Claude Code 2.x, checked against real transcripts):
|
|
4
|
+
// <config>/projects/<project-dir>/<sessionId>.jsonl the session
|
|
5
|
+
// <config>/projects/<project-dir>/<sessionId>/subagents/[<dir>/]agent-<agentId>.jsonl
|
|
6
|
+
// <config>/projects/<project-dir>/<sessionId>/subagents/[<dir>/]agent-<agentId>.meta.json
|
|
7
|
+
// where <config> is $CLAUDE_CONFIG_DIR or ~/.claude and <dir> is optional (workflows/<run>).
|
|
8
|
+
// Each line is one record: user, assistant, attachment, system, and bookkeeping types
|
|
9
|
+
// (custom-title, ai-title, summary, mode, cost-state, queue-operation, last-prompt, ...).
|
|
10
|
+
//
|
|
11
|
+
// Rules kept, each justified by the format:
|
|
12
|
+
// - Only user and assistant records are conversation; attachment records are harness
|
|
13
|
+
// context (reminders, tool listings, environment snapshots, edited-file snippets) except
|
|
14
|
+
// queued_command, which is how a prompt typed while the agent works reaches it.
|
|
15
|
+
// - isMeta user records are injected by the harness (skill bodies, caveats, "continue"
|
|
16
|
+
// nudges, coordinator relays), not typed by the user: skipped.
|
|
17
|
+
// - isCompactSummary / isVisibleInTranscriptOnly records restate earlier turns of the same
|
|
18
|
+
// file after /compact: skipped.
|
|
19
|
+
// - isApiErrorMessage and "<synthetic>" assistant records are harness messages: skipped.
|
|
20
|
+
// - thinking blocks: skipped (model-internal; Claude Code stores most of them empty).
|
|
21
|
+
// - Tool calls become one summary line; tool output is kept only when it is an error
|
|
22
|
+
// (is_error), clipped, or when it is the user's answer (AskUserQuestion). Successful output
|
|
23
|
+
// is the bulk of a transcript and restates files and commands a reader can re-run.
|
|
24
|
+
// - <system-reminder> blocks in user text and tool output are harness-injected: removed.
|
|
25
|
+
// - Slash commands (<command-name>) render as "/name args"; their local output
|
|
26
|
+
// (<local-command-stdout>) and shell-mode output (<bash-stdout>) are dropped.
|
|
27
|
+
// - <task-notification> (a background task or agent finished) renders as one event line,
|
|
28
|
+
// once per task and status; its <result> is the subagent report, its own document.
|
|
29
|
+
// Notifications with status "pending" announce something to read, not an outcome: skipped.
|
|
30
|
+
// - isSidechain records in a parent file are subagent turns (older versions wrote them
|
|
31
|
+
// inline): rendered under "Subagent" headings so they do not read as the user's words.
|
|
32
|
+
// - Subagent transcripts agent-acompact-* and agent-aprompt_* (compaction and prompt
|
|
33
|
+
// suggestion) restate the parent conversation: skipped. Known from the retired CLI;
|
|
34
|
+
// none exist in the transcripts this was checked against.
|
|
35
|
+
// Dropped from the retired CLI: the 50-character minimum turn length, the "narration"
|
|
36
|
+
// filter ("Let me ..."), folding short prompts into the previous round, and the owner's
|
|
37
|
+
// custom tag list (vibe-rules, good-behaviour, ...). They were content heuristics that lost
|
|
38
|
+
// short answers and decisions such as "yes, use Postgres".
|
|
39
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
40
|
+
import { join, relative, sep } from "node:path";
|
|
41
|
+
import { clip, dropBinary, oneLine, stripReminders, summarizeTool, toIso, } from "../transcript.js";
|
|
42
|
+
const SKIPPED_AGENT = /^(acompact|aprompt_)/;
|
|
43
|
+
const ERROR_MAX = 1_000;
|
|
44
|
+
const ANSWER_MAX = 2_000;
|
|
45
|
+
const PLAN_MAX = 4_000;
|
|
46
|
+
const NOTE_MAX = 300;
|
|
47
|
+
/** Tools whose successful output is the user's own decision. */
|
|
48
|
+
const KEEP_OUTPUT = new Set(["AskUserQuestion"]);
|
|
49
|
+
const AGENT_ROLES = new Set(["Assistant", "Subagent"]);
|
|
50
|
+
/** Every session and subagent transcript under <config>/projects. */
|
|
51
|
+
export function findClaudeFiles(configDir) {
|
|
52
|
+
const projects = join(configDir, "projects");
|
|
53
|
+
const files = [];
|
|
54
|
+
for (const project of list(projects)) {
|
|
55
|
+
if (!project.isDirectory())
|
|
56
|
+
continue;
|
|
57
|
+
const dir = join(projects, project.name);
|
|
58
|
+
for (const entry of list(dir)) {
|
|
59
|
+
if (entry.isFile() && entry.name.endsWith(".jsonl")) {
|
|
60
|
+
files.push({ path: join(dir, entry.name), sessionId: entry.name.slice(0, -".jsonl".length) });
|
|
61
|
+
}
|
|
62
|
+
else if (entry.isDirectory()) {
|
|
63
|
+
files.push(...subagentFiles(join(dir, entry.name, "subagents"), entry.name));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return files;
|
|
68
|
+
}
|
|
69
|
+
function subagentFiles(dir, sessionId) {
|
|
70
|
+
const found = [];
|
|
71
|
+
const walk = (d) => {
|
|
72
|
+
for (const entry of list(d)) {
|
|
73
|
+
const path = join(d, entry.name);
|
|
74
|
+
if (entry.isDirectory())
|
|
75
|
+
walk(path);
|
|
76
|
+
else if (entry.isFile() && /^agent-.+\.jsonl$/.test(entry.name)) {
|
|
77
|
+
const agentId = entry.name.slice("agent-".length, -".jsonl".length);
|
|
78
|
+
if (!SKIPPED_AGENT.test(agentId))
|
|
79
|
+
found.push({ path, agentId, nested: relative(dir, path).includes(sep) });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
walk(dir);
|
|
84
|
+
// A resumed run is written to subagents/agent-<id>.jsonl beside its first run under
|
|
85
|
+
// workflows/<run>/: same agent id, different content. The top-level copy gets "-resumed"
|
|
86
|
+
// (the retired CLI's key, kept so both documents survive and ids stay stable).
|
|
87
|
+
const nestedIds = new Set(found.filter((f) => f.nested).map((f) => f.agentId));
|
|
88
|
+
return found
|
|
89
|
+
.sort((a, b) => a.path.localeCompare(b.path))
|
|
90
|
+
.map((f) => ({ path: f.path, sessionId, agentId: !f.nested && nestedIds.has(f.agentId) ? `${f.agentId}-resumed` : f.agentId }));
|
|
91
|
+
}
|
|
92
|
+
/** Parse one transcript file (and the subagent's .meta.json next to it). */
|
|
93
|
+
export function readClaudeFile(file) {
|
|
94
|
+
let meta = {};
|
|
95
|
+
if (file.agentId) {
|
|
96
|
+
try {
|
|
97
|
+
meta = JSON.parse(readFileSync(file.path.replace(/\.jsonl$/, ".meta.json"), "utf8"));
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// No meta file: the header names the agent generically.
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return parseClaude(readFileSync(file.path, "utf8"), {
|
|
104
|
+
sessionId: file.sessionId,
|
|
105
|
+
agentId: file.agentId,
|
|
106
|
+
agentType: typeof meta.agentType === "string" ? meta.agentType : undefined,
|
|
107
|
+
description: typeof meta.description === "string" ? meta.description : undefined,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/** Parse a transcript's JSONL text. Pure: no file access. */
|
|
111
|
+
export function parseClaude(jsonl, ctx) {
|
|
112
|
+
const isSubagent = ctx.agentId !== undefined;
|
|
113
|
+
const messages = [];
|
|
114
|
+
const toolNames = new Map();
|
|
115
|
+
const seenTasks = new Set();
|
|
116
|
+
const uuids = new Set();
|
|
117
|
+
const summaries = [];
|
|
118
|
+
let customTitle;
|
|
119
|
+
let aiTitle;
|
|
120
|
+
let cwd;
|
|
121
|
+
let branch;
|
|
122
|
+
let startedAt;
|
|
123
|
+
let endedAt;
|
|
124
|
+
// Agent output merges under one heading; each user prompt opens its own (it carries a time).
|
|
125
|
+
const push = (role, part, time) => {
|
|
126
|
+
const last = messages.at(-1);
|
|
127
|
+
if (last && last.role === role && (AGENT_ROLES.has(role) || time === undefined))
|
|
128
|
+
last.parts.push(part);
|
|
129
|
+
else
|
|
130
|
+
messages.push({ role, time, parts: [part] });
|
|
131
|
+
};
|
|
132
|
+
const event = (text, side) => {
|
|
133
|
+
const status = /<status>([^<]*)<\/status>/.exec(text)?.[1]?.trim();
|
|
134
|
+
if (status === "pending")
|
|
135
|
+
return; // announces something to read, not an outcome
|
|
136
|
+
// The same notification can arrive both queued and as a user record.
|
|
137
|
+
const id = /<task-id>([^<]*)<\/task-id>/.exec(text)?.[1];
|
|
138
|
+
if (id !== undefined) {
|
|
139
|
+
if (seenTasks.has(`${id} ${status}`))
|
|
140
|
+
return;
|
|
141
|
+
seenTasks.add(`${id} ${status}`);
|
|
142
|
+
}
|
|
143
|
+
const summary = /<summary>([\s\S]*?)<\/summary>/.exec(text)?.[1]?.trim();
|
|
144
|
+
push(side ? "Subagent" : "Assistant", { type: "event", text: oneLine(`task ${status ?? "update"}: ${summary ?? ""}`, NOTE_MAX) });
|
|
145
|
+
};
|
|
146
|
+
for (const line of jsonl.split("\n")) {
|
|
147
|
+
if (!line.trim())
|
|
148
|
+
continue;
|
|
149
|
+
let r;
|
|
150
|
+
try {
|
|
151
|
+
r = JSON.parse(line);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
continue; // A line cut off mid-write by a running session.
|
|
155
|
+
}
|
|
156
|
+
if (!r || typeof r !== "object")
|
|
157
|
+
continue;
|
|
158
|
+
if (r.uuid)
|
|
159
|
+
uuids.add(r.uuid);
|
|
160
|
+
if (r.type === "custom-title" && r.customTitle)
|
|
161
|
+
customTitle = r.customTitle;
|
|
162
|
+
if (r.type === "ai-title" && r.aiTitle)
|
|
163
|
+
aiTitle = r.aiTitle;
|
|
164
|
+
if (r.type === "summary" && r.summary)
|
|
165
|
+
summaries.push({ summary: r.summary, leafUuid: r.leafUuid });
|
|
166
|
+
if (r.type !== "user" && r.type !== "assistant" && r.type !== "attachment")
|
|
167
|
+
continue;
|
|
168
|
+
const time = toIso(r.timestamp);
|
|
169
|
+
const side = Boolean(r.isSidechain) && !isSubagent;
|
|
170
|
+
const userRole = side ? "Subagent task" : isSubagent ? "Task" : "User";
|
|
171
|
+
const agentRole = side ? "Subagent" : "Assistant";
|
|
172
|
+
let spoke = false;
|
|
173
|
+
if (r.type === "attachment") {
|
|
174
|
+
const a = r.attachment;
|
|
175
|
+
if (a?.type !== "queued_command" || a.isMeta)
|
|
176
|
+
continue;
|
|
177
|
+
const prompt = typeof a.prompt === "string" ? a.prompt : blocksText(a.prompt);
|
|
178
|
+
if (a.commandMode === "task-notification")
|
|
179
|
+
event(prompt, side);
|
|
180
|
+
else if (a.commandMode === undefined || a.commandMode === "prompt" || a.commandMode === "bash") {
|
|
181
|
+
const text = userText(a.commandMode === "bash" ? `! ${prompt}` : prompt);
|
|
182
|
+
if (text) {
|
|
183
|
+
push(userRole, { type: "text", text }, time);
|
|
184
|
+
spoke = true;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
else if (r.type === "user") {
|
|
189
|
+
if (r.isMeta || r.isCompactSummary || r.isVisibleInTranscriptOnly)
|
|
190
|
+
continue;
|
|
191
|
+
const content = r.message?.content;
|
|
192
|
+
const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content : [];
|
|
193
|
+
const texts = [];
|
|
194
|
+
for (const b of blocks) {
|
|
195
|
+
if (!b || typeof b !== "object")
|
|
196
|
+
continue;
|
|
197
|
+
if (b.type === "text" && typeof b.text === "string") {
|
|
198
|
+
if (r.origin?.kind === "task-notification" || b.text.trimStart().startsWith("<task-notification>"))
|
|
199
|
+
event(b.text, side);
|
|
200
|
+
else
|
|
201
|
+
texts.push(userText(b.text));
|
|
202
|
+
}
|
|
203
|
+
else if (b.type === "image")
|
|
204
|
+
texts.push("[image]");
|
|
205
|
+
else if (b.type === "document")
|
|
206
|
+
texts.push("[document]");
|
|
207
|
+
else if (b.type === "tool_result") {
|
|
208
|
+
const name = toolNames.get(b.tool_use_id ?? "") ?? "";
|
|
209
|
+
if (b.is_error || KEEP_OUTPUT.has(name)) {
|
|
210
|
+
const out = toolOutput(b.content);
|
|
211
|
+
if (out)
|
|
212
|
+
push(agentRole, { type: "output", text: clip(out, b.is_error ? ERROR_MAX : ANSWER_MAX), error: Boolean(b.is_error) });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const text = texts.filter(Boolean).join("\n\n");
|
|
217
|
+
if (text) {
|
|
218
|
+
push(userRole, { type: "text", text }, time);
|
|
219
|
+
spoke = true;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
if (r.isApiErrorMessage || r.message?.model === "<synthetic>")
|
|
224
|
+
continue;
|
|
225
|
+
const content = r.message?.content;
|
|
226
|
+
const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content : [];
|
|
227
|
+
for (const b of blocks) {
|
|
228
|
+
if (!b || typeof b !== "object")
|
|
229
|
+
continue;
|
|
230
|
+
if (b.type === "text" && typeof b.text === "string") {
|
|
231
|
+
const text = dropBinary(b.text).trim();
|
|
232
|
+
if (text)
|
|
233
|
+
push(agentRole, { type: "text", text });
|
|
234
|
+
}
|
|
235
|
+
else if (b.type === "tool_use" && typeof b.name === "string") {
|
|
236
|
+
if (b.id)
|
|
237
|
+
toolNames.set(b.id, b.name);
|
|
238
|
+
push(agentRole, { type: "tool", text: summarizeTool(b.name, b.input) });
|
|
239
|
+
const plan = b.name === "ExitPlanMode" ? b.input?.plan : undefined;
|
|
240
|
+
if (typeof plan === "string" && plan.trim())
|
|
241
|
+
push(agentRole, { type: "text", text: clip(plan, PLAN_MAX) });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
spoke = blocks.some((b) => b?.type === "text" || b?.type === "tool_use");
|
|
245
|
+
}
|
|
246
|
+
if (spoke || r.type === "user") {
|
|
247
|
+
if (time) {
|
|
248
|
+
startedAt ??= time;
|
|
249
|
+
endedAt = time;
|
|
250
|
+
}
|
|
251
|
+
if (r.cwd)
|
|
252
|
+
cwd ??= r.cwd;
|
|
253
|
+
if (r.gitBranch)
|
|
254
|
+
branch = r.gitBranch;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
// A summary line titles the conversation that ends at leafUuid, which may live in another file.
|
|
258
|
+
const summary = summaries.filter((s) => !s.leafUuid || uuids.has(s.leafUuid)).pop()?.summary;
|
|
259
|
+
const agent = isSubagent
|
|
260
|
+
? `Claude Code subagent${ctx.agentType ? ` (${ctx.agentType})` : ""}${ctx.description ? `: ${oneLine(ctx.description, 200)}` : ""}`
|
|
261
|
+
: "Claude Code session";
|
|
262
|
+
return {
|
|
263
|
+
source: "claude-code",
|
|
264
|
+
sessionId: ctx.sessionId,
|
|
265
|
+
agentId: ctx.agentId,
|
|
266
|
+
agent,
|
|
267
|
+
title: customTitle ?? aiTitle ?? summary,
|
|
268
|
+
cwd,
|
|
269
|
+
branch,
|
|
270
|
+
startedAt,
|
|
271
|
+
endedAt,
|
|
272
|
+
messages,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/** User text with harness markup removed or rewritten; "" when nothing the user wrote is left. */
|
|
276
|
+
export function userText(raw) {
|
|
277
|
+
let text = stripReminders(raw);
|
|
278
|
+
// Slash command: <command-name>/review</command-name> <command-message>…</command-message> <command-args>x</command-args>
|
|
279
|
+
const command = /<command-name>([\s\S]*?)<\/command-name>/.exec(text)?.[1]?.trim();
|
|
280
|
+
if (command) {
|
|
281
|
+
const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(text)?.[1]?.trim();
|
|
282
|
+
text = text
|
|
283
|
+
.replace(/<command-(name|message|args)>[\s\S]*?<\/command-\1>/g, "")
|
|
284
|
+
.concat(`\n${command.startsWith("/") ? command : `/${command}`}${args ? ` ${args}` : ""}`);
|
|
285
|
+
}
|
|
286
|
+
text = text
|
|
287
|
+
.replace(/<local-command-(stdout|stderr|caveat)>[\s\S]*?<\/local-command-\1>/g, "")
|
|
288
|
+
.replace(/<bash-(stdout|stderr)>[\s\S]*?<\/bash-\1>/g, "")
|
|
289
|
+
.replace(/<bash-input>([\s\S]*?)<\/bash-input>/g, (_, cmd) => `! ${cmd.trim()}`);
|
|
290
|
+
return dropBinary(text).trim();
|
|
291
|
+
}
|
|
292
|
+
function toolOutput(content) {
|
|
293
|
+
const text = typeof content === "string" ? content : blocksText(content);
|
|
294
|
+
return stripReminders(text)
|
|
295
|
+
.replace(/<\/?tool_use_error>/g, "")
|
|
296
|
+
.trim();
|
|
297
|
+
}
|
|
298
|
+
function blocksText(content) {
|
|
299
|
+
if (!Array.isArray(content))
|
|
300
|
+
return "";
|
|
301
|
+
return content
|
|
302
|
+
.map((b) => (b?.type === "text" && typeof b.text === "string" ? b.text : b?.type === "image" ? "[image]" : ""))
|
|
303
|
+
.filter(Boolean)
|
|
304
|
+
.join("\n");
|
|
305
|
+
}
|
|
306
|
+
function list(dir) {
|
|
307
|
+
try {
|
|
308
|
+
return readdirSync(dir, { withFileTypes: true });
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
return [];
|
|
312
|
+
}
|
|
313
|
+
}
|