conare 0.19.0 → 0.21.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,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
+ }
@@ -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,101 @@
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, utimesSync, 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
+ /** The holder touches the lock this often, so a run longer than STALE_LOCK_MS keeps it. */
42
+ const HEARTBEAT_MS = 5 * 60 * 1000;
43
+ /**
44
+ * Take the run lock, or return undefined when another run holds it. The holder touches the
45
+ * lock every 5 minutes; a lock held by a process that is gone, or not touched for an hour
46
+ * (its holder hung, or its pid now belongs to another program), is taken over.
47
+ */
48
+ export function acquireLock(path) {
49
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
50
+ for (let attempt = 0; attempt < 2; attempt++) {
51
+ try {
52
+ const fd = openSync(path, "wx", 0o600);
53
+ writeSync(fd, String(process.pid));
54
+ closeSync(fd);
55
+ const heartbeat = setInterval(() => {
56
+ try {
57
+ const now = new Date();
58
+ utimesSync(path, now, now);
59
+ }
60
+ catch {
61
+ // Removed under us; the release below tolerates that.
62
+ }
63
+ }, HEARTBEAT_MS);
64
+ heartbeat.unref();
65
+ return () => {
66
+ clearInterval(heartbeat);
67
+ try {
68
+ unlinkSync(path);
69
+ }
70
+ catch {
71
+ // Already gone.
72
+ }
73
+ };
74
+ }
75
+ catch (err) {
76
+ if (err.code !== "EEXIST" || !isStaleLock(path))
77
+ return undefined;
78
+ try {
79
+ unlinkSync(path);
80
+ }
81
+ catch {
82
+ return undefined;
83
+ }
84
+ }
85
+ }
86
+ return undefined;
87
+ }
88
+ function isStaleLock(path) {
89
+ try {
90
+ if (Date.now() - statSync(path).mtimeMs > STALE_LOCK_MS)
91
+ return true;
92
+ const pid = Number(readFileSync(path, "utf8"));
93
+ if (!Number.isInteger(pid) || pid <= 0)
94
+ return true;
95
+ process.kill(pid, 0);
96
+ return false;
97
+ }
98
+ catch (err) {
99
+ return err.code !== "EPERM"; // ESRCH: the holder is gone
100
+ }
101
+ }