conare 0.8.0 → 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.
@@ -0,0 +1,266 @@
1
+ // Codex transcripts ("rollouts").
2
+ //
3
+ // Layout: <home>/sessions/YYYY/MM/DD/rollout-<time>-<thread id>.jsonl, <home> being
4
+ // $CODEX_HOME or ~/.codex. Each line is {timestamp, type, payload} with type session_meta,
5
+ // turn_context, response_item, event_msg or compacted (codex-rs protocol RolloutLine).
6
+ // Early 2025 files have no envelope: a first line {id, timestamp, instructions, git} and
7
+ // then bare response items. No real Codex file was available when this was written; the
8
+ // shapes come from the codex-rs protocol source and the retired CLI.
9
+ //
10
+ // Rules kept, each justified by the format:
11
+ // - response_item lines are the conversation. event_msg lines are UI events that repeat
12
+ // them (user_message, agent_message, token counts): skipped. compacted lines restate
13
+ // earlier turns: skipped.
14
+ // - developer and system role messages are harness instructions (permissions, sandbox):
15
+ // skipped.
16
+ // - User-role items Codex injects rather than the user types: <environment_context>,
17
+ // <user_instructions>, "# AGENTS.md instructions for …", and the other context blocks
18
+ // codex-rs defines (<skills_instructions>, <collaboration_mode>, …): removed. Text before
19
+ // "## My request for Codex:" is injected context too (codex-rs strip_user_message_prefix).
20
+ // - reasoning items: skipped (model-internal; usually encrypted).
21
+ // - Tool calls become one summary line; output is kept only for failures (exit code not
22
+ // 0), clipped. Images and base64 become markers.
23
+ // Dropped from the retired CLI: the "narration" filter, short-prompt folding and skipping
24
+ // <user_action> messages (they carry review results, which a reader wants).
25
+ import { readdirSync, readFileSync } from "node:fs";
26
+ import { join } from "node:path";
27
+ import { clip, dropBinary, oneLine, summarizeTool, toIso } from "../transcript.js";
28
+ const ERROR_MAX = 1_000;
29
+ /** Every rollout under <home>/sessions. The id is the file name, as the retired CLI keyed it. */
30
+ export function findCodexFiles(codexHome) {
31
+ const files = [];
32
+ const walk = (dir) => {
33
+ let entries;
34
+ try {
35
+ entries = readdirSync(dir, { withFileTypes: true });
36
+ }
37
+ catch {
38
+ return;
39
+ }
40
+ for (const entry of entries) {
41
+ const path = join(dir, entry.name);
42
+ if (entry.isDirectory())
43
+ walk(path);
44
+ else if (entry.isFile() && entry.name.endsWith(".jsonl"))
45
+ files.push({ path, sessionId: entry.name.slice(0, -".jsonl".length) });
46
+ }
47
+ };
48
+ walk(join(codexHome, "sessions"));
49
+ return files.sort((a, b) => a.path.localeCompare(b.path));
50
+ }
51
+ export function readCodexFile(file) {
52
+ return parseCodex(readFileSync(file.path, "utf8"), file.sessionId);
53
+ }
54
+ const ITEM_TYPES = new Set([
55
+ "message",
56
+ "reasoning",
57
+ "function_call",
58
+ "function_call_output",
59
+ "custom_tool_call",
60
+ "custom_tool_call_output",
61
+ "local_shell_call",
62
+ "web_search_call",
63
+ "agent_message",
64
+ ]);
65
+ /** Parse a rollout's JSONL text. Pure: no file access. */
66
+ export function parseCodex(jsonl, sessionId) {
67
+ const messages = [];
68
+ let meta = {};
69
+ let cwd;
70
+ let startedAt;
71
+ let endedAt;
72
+ const push = (role, part, time) => {
73
+ const last = messages.at(-1);
74
+ if (last && last.role === role && (role === "Assistant" || time === undefined))
75
+ last.parts.push(part);
76
+ else
77
+ messages.push({ role, time, parts: [part] });
78
+ };
79
+ for (const line of jsonl.split("\n")) {
80
+ if (!line.trim())
81
+ continue;
82
+ let rec;
83
+ try {
84
+ rec = JSON.parse(line);
85
+ }
86
+ catch {
87
+ continue; // A line cut off mid-write by a running session.
88
+ }
89
+ if (!rec || typeof rec !== "object")
90
+ continue;
91
+ const time = toIso(rec.timestamp);
92
+ let item;
93
+ if (rec.type === "session_meta") {
94
+ meta = (rec.payload ?? {});
95
+ cwd ??= meta.cwd;
96
+ startedAt ??= toIso(meta.timestamp) ?? time;
97
+ continue;
98
+ }
99
+ else if (rec.type === "turn_context") {
100
+ cwd ??= rec.payload?.cwd;
101
+ continue;
102
+ }
103
+ else if (rec.type === "response_item") {
104
+ item = rec.payload;
105
+ }
106
+ else if (rec.type === undefined && rec.id && !rec.payload) {
107
+ meta = rec; // Early 2025: the first line is the session meta, unwrapped.
108
+ startedAt ??= time;
109
+ continue;
110
+ }
111
+ else if (rec.type && ITEM_TYPES.has(rec.type) && rec.payload === undefined) {
112
+ item = rec; // Early 2025: bare response items.
113
+ }
114
+ if (!item || typeof item !== "object")
115
+ continue;
116
+ let spoke = true;
117
+ switch (item.type) {
118
+ case "message": {
119
+ if (item.role === "user") {
120
+ const text = userText(item.content);
121
+ if (text)
122
+ push("User", { type: "text", text }, time);
123
+ else
124
+ spoke = false;
125
+ }
126
+ else if (item.role === "assistant") {
127
+ const text = contentText(item.content);
128
+ if (text)
129
+ push("Assistant", { type: "text", text });
130
+ else
131
+ spoke = false;
132
+ }
133
+ else
134
+ spoke = false;
135
+ break;
136
+ }
137
+ case "function_call": {
138
+ let args = item.arguments;
139
+ if (typeof args === "string") {
140
+ try {
141
+ args = JSON.parse(args);
142
+ }
143
+ catch {
144
+ // Not JSON: summarized as a string.
145
+ }
146
+ }
147
+ push("Assistant", { type: "tool", text: summarizeTool(item.name ?? "tool", args) });
148
+ break;
149
+ }
150
+ case "custom_tool_call":
151
+ push("Assistant", { type: "tool", text: summarizeTool(item.name ?? "tool", item.name === "apply_patch" ? { input: item.input } : item.input) });
152
+ break;
153
+ case "local_shell_call":
154
+ push("Assistant", { type: "tool", text: summarizeTool("local_shell", { command: item.action?.command }) });
155
+ break;
156
+ case "web_search_call": {
157
+ const a = item.action ?? {};
158
+ const what = a.query ?? a.queries?.join(" | ") ?? a.url;
159
+ push("Assistant", { type: "tool", text: summarizeTool("web_search", { query: what }) });
160
+ break;
161
+ }
162
+ case "function_call_output":
163
+ case "custom_tool_call_output": {
164
+ const failure = failedOutput(item.output);
165
+ if (failure)
166
+ push("Assistant", { type: "output", text: clip(failure, ERROR_MAX), error: true });
167
+ break;
168
+ }
169
+ case "agent_message": {
170
+ const text = contentText(item.content);
171
+ if (text)
172
+ push("Assistant", { type: "text", text: `[${item.author ?? "agent"} → ${item.recipient ?? "agent"}] ${text}` });
173
+ break;
174
+ }
175
+ default:
176
+ spoke = false; // reasoning and anything newer
177
+ }
178
+ if (spoke && time) {
179
+ startedAt ??= time;
180
+ endedAt = time;
181
+ }
182
+ }
183
+ const role = meta.agent_role ?? meta.agent_type ?? meta.agent_nickname;
184
+ return {
185
+ source: "codex",
186
+ sessionId,
187
+ agent: meta.parent_thread_id || role ? `Codex subagent${role ? ` (${oneLine(role, 80)})` : ""}` : "Codex session",
188
+ cwd,
189
+ branch: meta.git?.branch || undefined,
190
+ startedAt,
191
+ endedAt: endedAt ?? startedAt,
192
+ messages,
193
+ };
194
+ }
195
+ // Context blocks codex-rs injects as user-role text (protocol.rs *_OPEN_TAG constants).
196
+ const INJECTED_TAGS = [
197
+ "user_instructions",
198
+ "environment_context",
199
+ "environments_instructions",
200
+ "apps_instructions",
201
+ "skills_instructions",
202
+ "plugins_instructions",
203
+ "tools",
204
+ "collaboration_mode",
205
+ "multi_agent_mode",
206
+ "realtime_conversation",
207
+ "context_window",
208
+ "context_window_guidance",
209
+ "INSTRUCTIONS",
210
+ ];
211
+ const INJECTED_BLOCK = new RegExp(`<(${INJECTED_TAGS.join("|")})>[\\s\\S]*?</\\1>`, "g");
212
+ const REQUEST_MARK = "## My request for Codex:";
213
+ const IMAGE_TAG = /^\s*<\/?(image|audio)\b[^>]*>\s*$/;
214
+ /** What the user typed, from a user message's content items; "" when all of it is injected. */
215
+ export function userText(content) {
216
+ if (!Array.isArray(content))
217
+ return typeof content === "string" ? cleanUser(content) : "";
218
+ const parts = [];
219
+ for (const c of content) {
220
+ if (c?.type === "input_image")
221
+ parts.push("[image]");
222
+ else if (typeof c?.text === "string" && !IMAGE_TAG.test(c.text))
223
+ parts.push(cleanUser(c.text));
224
+ }
225
+ return parts.filter(Boolean).join("\n\n");
226
+ }
227
+ function cleanUser(raw) {
228
+ if (raw.trimStart().startsWith("# AGENTS.md instructions for "))
229
+ return "";
230
+ const mark = raw.indexOf(REQUEST_MARK);
231
+ const text = mark >= 0 ? raw.slice(mark + REQUEST_MARK.length) : raw;
232
+ return dropBinary(text.replace(INJECTED_BLOCK, "")).trim();
233
+ }
234
+ function contentText(content) {
235
+ if (typeof content === "string")
236
+ return dropBinary(content).trim();
237
+ if (!Array.isArray(content))
238
+ return "";
239
+ return content
240
+ .map((c) => (typeof c?.text === "string" ? dropBinary(c.text).trim() : c?.type === "input_image" ? "[image]" : ""))
241
+ .filter(Boolean)
242
+ .join("\n\n");
243
+ }
244
+ /**
245
+ * The output text of a failed call, or undefined. Codex writes output as a string (older
246
+ * versions: JSON {"output", "metadata": {"exit_code"}}; newer: "Exit code: N" lines) or
247
+ * as content items.
248
+ */
249
+ export function failedOutput(output) {
250
+ const text = typeof output === "string" ? output : contentText(output);
251
+ if (!text)
252
+ return undefined;
253
+ if (text.trimStart().startsWith("{")) {
254
+ try {
255
+ const parsed = JSON.parse(text);
256
+ const code = parsed.metadata?.exit_code;
257
+ if (typeof code === "number")
258
+ return code !== 0 ? String(parsed.output ?? "") || `exit code ${code}` : undefined;
259
+ }
260
+ catch {
261
+ // Not the JSON form.
262
+ }
263
+ }
264
+ const code = /^(?:Exit code|Process exited with code):? (-?\d+)/m.exec(text)?.[1];
265
+ return code !== undefined && code !== "0" ? text : undefined;
266
+ }
@@ -0,0 +1,87 @@
1
+ // What the server already has: ~/.conare/sync-state.json maps each document id to the
2
+ // content_hash the server accepted. It is written only after the server accepts a batch,
3
+ // so a failed batch leaves its ids unsynced for the next run.
4
+ import { createHash } from "node:crypto";
5
+ import { closeSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeSync } from "node:fs";
6
+ import { dirname } from "node:path";
7
+ import { writePrivate } from "./config.js";
8
+ /** Bump when rendering changes, so files skipped by their stamp are read again. */
9
+ export const RENDERER = 1;
10
+ export function accountOf(baseURL, apiKey) {
11
+ return createHash("sha256").update(`${baseURL}\n${apiKey}`).digest("hex").slice(0, 16);
12
+ }
13
+ export function loadState(path, account) {
14
+ const empty = { account, renderer: RENDERER, documents: {}, parts: {}, files: {} };
15
+ let saved;
16
+ try {
17
+ saved = JSON.parse(readFileSync(path, "utf8"));
18
+ }
19
+ catch {
20
+ return empty; // Missing or corrupt: everything uploads again, which is safe (same ids).
21
+ }
22
+ if (saved.account !== account || typeof saved.documents !== "object" || !saved.documents)
23
+ return empty;
24
+ return {
25
+ account,
26
+ renderer: RENDERER,
27
+ documents: saved.documents,
28
+ parts: saved.parts && typeof saved.parts === "object" ? saved.parts : {},
29
+ files: saved.renderer === RENDERER && saved.files && typeof saved.files === "object" ? saved.files : {},
30
+ };
31
+ }
32
+ export function saveState(path, state) {
33
+ writePrivate(path, JSON.stringify(state));
34
+ }
35
+ /** True when the file is unchanged since all of its documents reached the server. */
36
+ export function isStamped(state, path, stat) {
37
+ const s = state.files[path];
38
+ return !!s && s.size === stat.size && s.mtimeMs === stat.mtimeMs;
39
+ }
40
+ const STALE_LOCK_MS = 60 * 60 * 1000;
41
+ /**
42
+ * Take the run lock, or return undefined when another sync holds it. A lock older than an
43
+ * hour, or held by a process that is gone, is taken over.
44
+ */
45
+ export function acquireLock(path) {
46
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
47
+ for (let attempt = 0; attempt < 2; attempt++) {
48
+ try {
49
+ const fd = openSync(path, "wx", 0o600);
50
+ writeSync(fd, String(process.pid));
51
+ closeSync(fd);
52
+ return () => {
53
+ try {
54
+ unlinkSync(path);
55
+ }
56
+ catch {
57
+ // Already gone.
58
+ }
59
+ };
60
+ }
61
+ catch (err) {
62
+ if (err.code !== "EEXIST" || !isStaleLock(path))
63
+ return undefined;
64
+ try {
65
+ unlinkSync(path);
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ }
71
+ }
72
+ return undefined;
73
+ }
74
+ function isStaleLock(path) {
75
+ try {
76
+ if (Date.now() - statSync(path).mtimeMs > STALE_LOCK_MS)
77
+ return true;
78
+ const pid = Number(readFileSync(path, "utf8"));
79
+ if (!Number.isInteger(pid) || pid <= 0)
80
+ return true;
81
+ process.kill(pid, 0);
82
+ return false;
83
+ }
84
+ catch (err) {
85
+ return err.code !== "EPERM"; // ESRCH: the holder is gone
86
+ }
87
+ }
@@ -0,0 +1,186 @@
1
+ // One sync run: find transcripts, render the new or changed ones, upload them in batches,
2
+ // and record what the server accepted.
3
+ import { statSync } from "node:fs";
4
+ import { NAMESPACE, baseId, toDocuments } from "./documents.js";
5
+ import { projectName } from "./project.js";
6
+ import { findClaudeFiles, readClaudeFile } from "./sources/claude.js";
7
+ import { findCodexFiles, readCodexFile } from "./sources/codex.js";
8
+ import { isStamped, loadState, saveState } from "./state.js";
9
+ import { BATCH_BYTES, BATCH_DOCUMENTS, heldAs, listLayouts, removeStaleParts, sendBatch } from "./upload.js";
10
+ export function findTranscripts(paths) {
11
+ return [
12
+ ...findClaudeFiles(paths.claudeDir).map((f) => ({ path: f.path, read: () => readClaudeFile(f) })),
13
+ ...findCodexFiles(paths.codexDir).map((f) => ({ path: f.path, read: () => readCodexFile(f) })),
14
+ ];
15
+ }
16
+ export async function runSync(opts) {
17
+ const dryRun = !opts.client;
18
+ const ns = opts.client?.namespace(NAMESPACE);
19
+ const log = opts.log ?? (() => { });
20
+ const state = loadState(opts.stateFile, opts.account);
21
+ const report = { sessions: 0, documents: 0, bytes: 0, unchanged: 0, deleted: 0, rejected: [], planned: [] };
22
+ // The layout the server holds for a session: what this run's state says this tool stored
23
+ // last; on a fresh state (the first sync, after the migration of older history), one
24
+ // listing of the namespace, read once, gaps included; else unknown, and probed.
25
+ const fresh = Object.keys(state.parts).length === 0;
26
+ let layouts;
27
+ const held = async (base) => {
28
+ const previous = state.parts[base];
29
+ if (previous)
30
+ return heldAs(previous);
31
+ if (!fresh || !ns)
32
+ return undefined;
33
+ layouts ??= listLayouts(ns);
34
+ return (await layouts).get(base) ?? { whole: false, parts: [] };
35
+ };
36
+ const owner = new Map();
37
+ const produced = new Set();
38
+ let queue = [];
39
+ let queuedBytes = 0;
40
+ const flush = async () => {
41
+ if (queue.length === 0 || !ns)
42
+ return;
43
+ const batch = queue;
44
+ queue = [];
45
+ queuedBytes = 0;
46
+ const result = await sendBatch(ns, batch);
47
+ const touched = new Set();
48
+ for (const doc of result.accepted) {
49
+ state.documents[doc.id] = String(doc.metadata.content_hash);
50
+ report.documents++;
51
+ report.bytes += Buffer.byteLength(doc.text);
52
+ const entry = owner.get(doc.id);
53
+ entry.waiting.delete(doc.id);
54
+ touched.add(entry);
55
+ }
56
+ for (const { doc, error } of result.rejected) {
57
+ report.rejected.push({ id: doc.id, message: `${error.code}: ${error.message}` });
58
+ const entry = owner.get(doc.id);
59
+ entry.failed = true;
60
+ touched.add(entry);
61
+ }
62
+ for (const entry of touched)
63
+ if (entry.waiting.size === 0 && !entry.failed)
64
+ await settle(ns, state, entry, report, held);
65
+ saveState(opts.stateFile, state);
66
+ log(`Uploaded ${report.documents} documents (${formatBytes(report.bytes)})`);
67
+ };
68
+ try {
69
+ const files = newestFirst(opts.files);
70
+ for (const file of files)
71
+ await visit(file);
72
+ await flush();
73
+ // Forget the stamps of transcripts that were deleted.
74
+ const present = new Set(files.map((f) => f.path));
75
+ for (const path of Object.keys(state.files))
76
+ if (!present.has(path))
77
+ delete state.files[path];
78
+ }
79
+ finally {
80
+ // Accepted batches are already saved; this keeps the probes and stamps of a cut-short run.
81
+ if (!dryRun)
82
+ saveState(opts.stateFile, state);
83
+ }
84
+ return report;
85
+ async function visit(file) {
86
+ if (isStamped(state, file.path, file.stamp)) {
87
+ report.unchanged++;
88
+ return;
89
+ }
90
+ let docs;
91
+ let base;
92
+ try {
93
+ const transcript = file.read();
94
+ base = baseId(transcript);
95
+ docs = transcript.messages.length > 0 ? toDocuments(transcript, projectName(transcript.cwd)) : [];
96
+ }
97
+ catch (err) {
98
+ log(`Skipped ${file.path}: ${err instanceof Error ? err.message : String(err)}`);
99
+ return;
100
+ }
101
+ // Two files claiming one id (a session copied between projects): the most recently
102
+ // modified wins. The other is stamped too, so a later run, which skips the stamped
103
+ // winner, does not upload it over the winner; it uploads again only once it changes.
104
+ if (docs.some((d) => produced.has(d.id))) {
105
+ if (!dryRun)
106
+ state.files[file.path] = file.stamp;
107
+ report.unchanged++;
108
+ return;
109
+ }
110
+ docs.forEach((d) => produced.add(d.id));
111
+ const changed = docs.filter((d) => state.documents[d.id] !== d.metadata.content_hash);
112
+ const entry = {
113
+ path: file.path,
114
+ stamp: file.stamp,
115
+ base,
116
+ count: docs.length,
117
+ // First sight included: the migration of older history may hold another layout.
118
+ probe: docs.length > 0 && state.parts[base] !== docs.length,
119
+ waiting: new Set(changed.map((d) => d.id)),
120
+ failed: false,
121
+ };
122
+ if (changed.length === 0 && !entry.probe) {
123
+ if (!dryRun)
124
+ state.files[file.path] = file.stamp;
125
+ report.unchanged++;
126
+ return;
127
+ }
128
+ if (changed.length > 0)
129
+ report.sessions++;
130
+ if (dryRun) {
131
+ for (const d of changed)
132
+ report.planned.push({ id: d.id, bytes: Buffer.byteLength(d.text) });
133
+ report.documents += changed.length;
134
+ report.bytes += changed.reduce((n, d) => n + Buffer.byteLength(d.text), 0);
135
+ return;
136
+ }
137
+ if (changed.length === 0) {
138
+ await settle(ns, state, entry, report, held);
139
+ return;
140
+ }
141
+ for (const doc of changed) {
142
+ const size = Buffer.byteLength(doc.text);
143
+ if (queue.length >= BATCH_DOCUMENTS || (queue.length > 0 && queuedBytes + size > BATCH_BYTES))
144
+ await flush();
145
+ owner.set(doc.id, entry);
146
+ queue.push(doc);
147
+ queuedBytes += size;
148
+ }
149
+ }
150
+ }
151
+ /**
152
+ * Every document of the file is on the server: when the session's document count is new
153
+ * to the state, remove its older layout, record the count, then stamp the file. Deleting
154
+ * only now means a crash in between leaves a duplicate, never a gap.
155
+ */
156
+ async function settle(ns, state, entry, report, held) {
157
+ if (entry.probe) {
158
+ for (const id of await removeStaleParts(ns, entry.base, entry.count, await held(entry.base))) {
159
+ delete state.documents[id];
160
+ report.deleted++;
161
+ }
162
+ state.parts[entry.base] = entry.count;
163
+ }
164
+ state.files[entry.path] = entry.stamp;
165
+ }
166
+ /** Stat every file (skipping ones that vanished) and order newest first, so a cut-short run keeps the recent work. */
167
+ function newestFirst(files) {
168
+ const out = [];
169
+ for (const f of files) {
170
+ try {
171
+ const s = statSync(f.path);
172
+ out.push({ ...f, stamp: { size: s.size, mtimeMs: s.mtimeMs } });
173
+ }
174
+ catch {
175
+ // Removed since it was listed.
176
+ }
177
+ }
178
+ return out.sort((a, b) => b.stamp.mtimeMs - a.stamp.mtimeMs);
179
+ }
180
+ export function formatBytes(n) {
181
+ if (n < 1000)
182
+ return `${n} B`;
183
+ if (n < 1_000_000)
184
+ return `${(n / 1000).toFixed(1)} KB`;
185
+ return `${(n / 1_000_000).toFixed(1)} MB`;
186
+ }
@@ -0,0 +1,103 @@
1
+ // The parsed form of one agent session, shared by the sources and the renderer.
2
+ /** RFC 3339 UTC for a timestamp string or epoch number, or undefined. */
3
+ export function toIso(value) {
4
+ if (typeof value !== "string" && typeof value !== "number")
5
+ return undefined;
6
+ const ms = typeof value === "number" ? (value < 1e11 ? value * 1000 : value) : Date.parse(value);
7
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
8
+ }
9
+ /** Keeps the head and the tail of a long text (errors carry their cause at either end). */
10
+ export function clip(text, max) {
11
+ const t = text.trim();
12
+ if (t.length <= max)
13
+ return t;
14
+ const head = Math.floor(max * 0.6);
15
+ const tail = max - head;
16
+ return `${t.slice(0, head)}\n… [${t.length - max} characters omitted] …\n${t.slice(t.length - tail)}`;
17
+ }
18
+ /** One line of at most max characters. */
19
+ export function oneLine(text, max) {
20
+ const t = text.replace(/\s+/g, " ").trim();
21
+ return t.length <= max ? t : `${t.slice(0, max - 1)}…`;
22
+ }
23
+ // Images and inline binary have no text value; a data URI or a long unbroken base64 run is
24
+ // replaced by a marker. 200 characters of the base64 alphabet with no space, dot or dash is
25
+ // never prose, code or a path.
26
+ const DATA_URI = /data:[\w.+-]+\/[\w.+-]+;base64,[A-Za-z0-9+/=]+/g;
27
+ const BASE64_RUN = /[A-Za-z0-9+/]{200,}={0,2}/g;
28
+ export function dropBinary(text) {
29
+ return text.replace(DATA_URI, "[binary data]").replace(BASE64_RUN, (run) => (/[+/]/.test(run) || /\d/.test(run) ? "[binary data]" : run));
30
+ }
31
+ // Harness-injected context inside user and tool text, never typed by the user: Claude Code
32
+ // wraps it in <system-reminder>.
33
+ export function stripReminders(text) {
34
+ return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "");
35
+ }
36
+ /** Command shown for a shell call: argv ["bash", "-lc", "cmd"] becomes "cmd". */
37
+ export function shellCommand(command) {
38
+ if (typeof command === "string")
39
+ return command;
40
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string"))
41
+ return undefined;
42
+ const argv = command;
43
+ if (argv.length === 3 && /(^|\/)(ba|z)?sh$/.test(argv[0]) && /^-l?c$/.test(argv[1]))
44
+ return argv[2];
45
+ return argv.join(" ");
46
+ }
47
+ const COMMAND_MAX = 500;
48
+ const ARG_MAX = 200;
49
+ /**
50
+ * One line (a shell command may keep its own lines) for a tool call: what ran, on which
51
+ * path, with which pattern. File contents and patches are left out; they are in the repo.
52
+ */
53
+ export function summarizeTool(name, input) {
54
+ const i = (input && typeof input === "object" ? input : {});
55
+ const s = (key) => (typeof i[key] === "string" ? i[key] : undefined);
56
+ const cmd = shellCommand(i.command) ?? shellCommand(i.cmd);
57
+ switch (name) {
58
+ case "Bash":
59
+ case "shell":
60
+ case "shell_command":
61
+ case "exec_command":
62
+ case "local_shell":
63
+ case "container.exec":
64
+ return cmd ? `$ ${clip(cmd, COMMAND_MAX)}` : name;
65
+ case "Read":
66
+ case "Write":
67
+ case "Edit":
68
+ case "MultiEdit":
69
+ case "NotebookEdit":
70
+ case "view_image":
71
+ return `${name} ${s("file_path") ?? s("notebook_path") ?? s("path") ?? ""}`.trim();
72
+ case "Grep":
73
+ return `Grep "${oneLine(s("pattern") ?? "", ARG_MAX)}"${s("path") ? ` in ${s("path")}` : ""}${s("glob") ? ` (${s("glob")})` : ""}`;
74
+ case "Glob":
75
+ return `Glob ${s("pattern") ?? ""}${s("path") ? ` in ${s("path")}` : ""}`;
76
+ case "WebFetch":
77
+ return `WebFetch ${s("url") ?? ""}`.trim();
78
+ case "WebSearch":
79
+ case "web_search":
80
+ return `${name} "${oneLine(s("query") ?? "", ARG_MAX)}"`;
81
+ case "AskUserQuestion": {
82
+ const questions = Array.isArray(i.questions) ? i.questions : [];
83
+ return `AskUserQuestion: ${oneLine(questions.map((q) => String(q?.question ?? "")).join(" | "), ARG_MAX * 2)}`;
84
+ }
85
+ case "Task":
86
+ case "Agent":
87
+ return `${name}${s("subagent_type") ? ` (${s("subagent_type")})` : ""}: ${oneLine(s("description") ?? "", ARG_MAX)}`;
88
+ case "Skill":
89
+ return `Skill ${s("skill") ?? s("name") ?? ""}`.trim();
90
+ case "ExitPlanMode":
91
+ return name; // the plan follows as text
92
+ case "apply_patch":
93
+ return `apply_patch ${patchFiles(s("input") ?? s("patch") ?? (typeof input === "string" ? input : ""))}`.trim();
94
+ }
95
+ // Anything else (MCP tools, task lists): the name and its arguments, compact.
96
+ const args = input === undefined ? "" : typeof input === "string" ? input : JSON.stringify(input);
97
+ return args && args !== "{}" ? `${name} ${oneLine(args, ARG_MAX)}` : name;
98
+ }
99
+ /** "Update a.ts, Add b.ts" from an apply_patch body. */
100
+ export function patchFiles(patch) {
101
+ const files = [...patch.matchAll(/^\*\*\* (Add|Update|Delete) File: (.+)$/gm)].map((m) => `${m[1]} ${m[2].trim()}`);
102
+ return files.join(", ");
103
+ }