conare 0.33.0 → 0.34.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 +68 -18
- package/dist/cli/args.js +39 -9
- package/dist/cli/config.js +21 -1
- package/dist/cli/documents.js +3 -2
- package/dist/cli/legacy.js +111 -0
- package/dist/cli/main.js +147 -57
- package/dist/cli/others.js +46 -0
- package/dist/cli/schedule.js +74 -10
- package/dist/cli/scrub.js +28 -9
- package/dist/cli/sources/claude.js +19 -6
- package/dist/cli/sources/codex.js +5 -5
- package/dist/cli/sources/cursor.js +250 -0
- package/dist/cli/sources/pi.js +180 -0
- package/dist/cli/state.js +34 -10
- package/dist/cli/status.js +18 -14
- package/dist/cli/sync.js +61 -14
- package/dist/cli/transcript.js +68 -3
- package/dist/cli/upload.js +9 -5
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
|
@@ -32,13 +32,17 @@
|
|
|
32
32
|
// - Subagent transcripts agent-acompact-* and agent-aprompt_* (compaction and prompt
|
|
33
33
|
// suggestion), which Claude Code writes beside a session's own subagents, restate the
|
|
34
34
|
// parent conversation: skipped.
|
|
35
|
+
// - user, assistant, attachment and system records carry "entrypoint" (what started the
|
|
36
|
+
// session). An app built on the Claude Agent SDK writes "sdk-go" or another "sdk-" value:
|
|
37
|
+
// such a transcript is titled "Agent SDK run", not a Claude Code session, since its
|
|
38
|
+
// prompts come from the app.
|
|
35
39
|
// Dropped from the retired CLI: the 50-character minimum turn length, the "narration"
|
|
36
40
|
// filter ("Let me ..."), folding short prompts into the previous round, and the owner's
|
|
37
41
|
// custom tag list (vibe-rules, good-behaviour, ...). They were content heuristics that lost
|
|
38
42
|
// short answers and decisions such as "yes, use Postgres".
|
|
39
43
|
import { readdirSync, readFileSync } from "node:fs";
|
|
40
44
|
import { join, relative, sep } from "node:path";
|
|
41
|
-
import { clip, dropBinary, oneLine, stripReminders, summarizeTool, toIso, } from "../transcript.js";
|
|
45
|
+
import { clip, dropBinary, oneLine, readLines, stripReminders, summarizeTool, toIso, } from "../transcript.js";
|
|
42
46
|
const SKIPPED_AGENT = /^(acompact|aprompt_)/;
|
|
43
47
|
const ERROR_MAX = 1_000;
|
|
44
48
|
const ANSWER_MAX = 2_000;
|
|
@@ -100,14 +104,14 @@ export function readClaudeFile(file) {
|
|
|
100
104
|
// No meta file: the header names the agent generically.
|
|
101
105
|
}
|
|
102
106
|
}
|
|
103
|
-
return parseClaude(
|
|
107
|
+
return parseClaude(readLines(file.path), {
|
|
104
108
|
sessionId: file.sessionId,
|
|
105
109
|
agentId: file.agentId,
|
|
106
110
|
agentType: typeof meta.agentType === "string" ? meta.agentType : undefined,
|
|
107
111
|
description: typeof meta.description === "string" ? meta.description : undefined,
|
|
108
112
|
});
|
|
109
113
|
}
|
|
110
|
-
/** Parse a transcript's JSONL text. Pure: no file access. */
|
|
114
|
+
/** Parse a transcript's JSONL text, or its lines. Pure: no file access. */
|
|
111
115
|
export function parseClaude(jsonl, ctx) {
|
|
112
116
|
const isSubagent = ctx.agentId !== undefined;
|
|
113
117
|
const messages = [];
|
|
@@ -119,6 +123,7 @@ export function parseClaude(jsonl, ctx) {
|
|
|
119
123
|
let aiTitle;
|
|
120
124
|
let cwd;
|
|
121
125
|
let branch;
|
|
126
|
+
let entrypoint;
|
|
122
127
|
let startedAt;
|
|
123
128
|
let endedAt;
|
|
124
129
|
// Agent output merges under one heading; each user prompt opens its own (it carries a time).
|
|
@@ -143,7 +148,7 @@ export function parseClaude(jsonl, ctx) {
|
|
|
143
148
|
const summary = /<summary>([\s\S]*?)<\/summary>/.exec(text)?.[1]?.trim();
|
|
144
149
|
push(side ? "Subagent" : "Assistant", { type: "event", text: oneLine(`task ${status ?? "update"}: ${summary ?? ""}`, NOTE_MAX) });
|
|
145
150
|
};
|
|
146
|
-
for (const line of jsonl.split("\n")) {
|
|
151
|
+
for (const line of typeof jsonl === "string" ? jsonl.split("\n") : jsonl) {
|
|
147
152
|
if (!line.trim())
|
|
148
153
|
continue;
|
|
149
154
|
let r;
|
|
@@ -157,6 +162,8 @@ export function parseClaude(jsonl, ctx) {
|
|
|
157
162
|
continue;
|
|
158
163
|
if (r.uuid)
|
|
159
164
|
uuids.add(r.uuid);
|
|
165
|
+
if (typeof r.entrypoint === "string" && r.entrypoint)
|
|
166
|
+
entrypoint ??= r.entrypoint;
|
|
160
167
|
if (r.type === "custom-title" && r.customTitle)
|
|
161
168
|
customTitle = r.customTitle;
|
|
162
169
|
if (r.type === "ai-title" && r.aiTitle)
|
|
@@ -256,14 +263,20 @@ export function parseClaude(jsonl, ctx) {
|
|
|
256
263
|
}
|
|
257
264
|
// A summary line titles the conversation that ends at leafUuid, which may live in another file.
|
|
258
265
|
const summary = summaries.filter((s) => !s.leafUuid || uuids.has(s.leafUuid)).pop()?.summary;
|
|
266
|
+
// An app built on the Agent SDK writes the same transcripts (entrypoint "sdk-go" and the
|
|
267
|
+
// other "sdk-" values): its prompts are the app's, not the person's, so the heading says so.
|
|
268
|
+
const sdk = entrypoint?.startsWith("sdk-") ?? false;
|
|
259
269
|
const agent = isSubagent
|
|
260
|
-
?
|
|
261
|
-
:
|
|
270
|
+
? `${sdk ? "Agent SDK" : "Claude Code"} subagent${ctx.agentType ? ` (${ctx.agentType})` : ""}${ctx.description ? `: ${oneLine(ctx.description, 200)}` : ""}`
|
|
271
|
+
: sdk
|
|
272
|
+
? "Agent SDK run"
|
|
273
|
+
: "Claude Code session";
|
|
262
274
|
return {
|
|
263
275
|
source: "claude-code",
|
|
264
276
|
sessionId: ctx.sessionId,
|
|
265
277
|
agentId: ctx.agentId,
|
|
266
278
|
agent,
|
|
279
|
+
entrypoint,
|
|
267
280
|
title: customTitle ?? aiTitle ?? summary,
|
|
268
281
|
cwd,
|
|
269
282
|
branch,
|
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
// 0), clipped. Images and base64 become markers.
|
|
23
23
|
// Dropped from the retired CLI: the "narration" filter, short-prompt folding and skipping
|
|
24
24
|
// <user_action> messages (they carry review results, which a reader wants).
|
|
25
|
-
import { readdirSync
|
|
25
|
+
import { readdirSync } from "node:fs";
|
|
26
26
|
import { join } from "node:path";
|
|
27
|
-
import { clip, dropBinary, oneLine, summarizeTool, toIso } from "../transcript.js";
|
|
27
|
+
import { clip, dropBinary, oneLine, readLines, summarizeTool, toIso } from "../transcript.js";
|
|
28
28
|
const ERROR_MAX = 1_000;
|
|
29
29
|
/** Every rollout under <home>/sessions. The id is the file name, as the retired CLI keyed it. */
|
|
30
30
|
export function findCodexFiles(codexHome) {
|
|
@@ -49,7 +49,7 @@ export function findCodexFiles(codexHome) {
|
|
|
49
49
|
return files.sort((a, b) => a.path.localeCompare(b.path));
|
|
50
50
|
}
|
|
51
51
|
export function readCodexFile(file) {
|
|
52
|
-
return parseCodex(
|
|
52
|
+
return parseCodex(readLines(file.path), file.sessionId);
|
|
53
53
|
}
|
|
54
54
|
const ITEM_TYPES = new Set([
|
|
55
55
|
"message",
|
|
@@ -62,7 +62,7 @@ const ITEM_TYPES = new Set([
|
|
|
62
62
|
"web_search_call",
|
|
63
63
|
"agent_message",
|
|
64
64
|
]);
|
|
65
|
-
/** Parse a rollout's JSONL text. Pure: no file access. */
|
|
65
|
+
/** Parse a rollout's JSONL text, or its lines. Pure: no file access. */
|
|
66
66
|
export function parseCodex(jsonl, sessionId) {
|
|
67
67
|
const messages = [];
|
|
68
68
|
let meta = {};
|
|
@@ -76,7 +76,7 @@ export function parseCodex(jsonl, sessionId) {
|
|
|
76
76
|
else
|
|
77
77
|
messages.push({ role, time, parts: [part] });
|
|
78
78
|
};
|
|
79
|
-
for (const line of jsonl.split("\n")) {
|
|
79
|
+
for (const line of typeof jsonl === "string" ? jsonl.split("\n") : jsonl) {
|
|
80
80
|
if (!line.trim())
|
|
81
81
|
continue;
|
|
82
82
|
let rec;
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// Cursor chats (the composer: Ask, Agent and Edit modes).
|
|
2
|
+
//
|
|
3
|
+
// Layout: one SQLite database, <Cursor>/User/globalStorage/state.vscdb (macOS: ~/Library/
|
|
4
|
+
// Application Support/Cursor, Linux: ~/.config/Cursor), table cursorDiskKV(key, value). A
|
|
5
|
+
// chat is the row composerData:<composerId>, JSON {composerId, name, createdAt,
|
|
6
|
+
// lastUpdatedAt (epoch ms), ...} holding its messages ("bubbles") either inline, older
|
|
7
|
+
// versions: conversation [{bubbleId, type, text, ...}], or, newer ones, as headers
|
|
8
|
+
// fullConversationHeadersOnly [{bubbleId, type}] with each bubble in its own row
|
|
9
|
+
// bubbleId:<composerId>:<bubbleId>. A bubble's type is 1 for the user, 2 for the model; an
|
|
10
|
+
// agent's tool call is a type 2 bubble with toolFormerData {name, rawArgs or params (JSON
|
|
11
|
+
// text), status, result}. No Cursor store was on the machine this was written on: the format
|
|
12
|
+
// comes from the retired CLI's reader (mid-2026; composerData, the headers and the bubble
|
|
13
|
+
// rows' text) and from open-source exporters (the inline conversation, toolFormerData); it
|
|
14
|
+
// was not checked against a current install. A composer or bubble that does not parse reads
|
|
15
|
+
// as no message (unread), never as an error.
|
|
16
|
+
//
|
|
17
|
+
// Mapping: one composer is one session document (cursor:<composerId>, "Cursor session",
|
|
18
|
+
// titled with its name). The composer row records no workspace, so a Cursor session has no
|
|
19
|
+
// cwd and no project (an exclude list holds back sessions of no known project).
|
|
20
|
+
//
|
|
21
|
+
// Change detection: every chat lives in one file, so the file stamp of the other sources says
|
|
22
|
+
// nothing about one chat. Each composer is listed as its own transcript with the pseudo-path
|
|
23
|
+
// <db>#<composerId> and a stamp of its own: size = the composer row's length (it grows with
|
|
24
|
+
// every message, and changes with the name or status), mtimeMs = its lastUpdatedAt (else
|
|
25
|
+
// createdAt), which also orders it among the other sessions. One query lists them all, by a
|
|
26
|
+
// range of the key index with json_extract for the date: no row is parsed in JavaScript, and
|
|
27
|
+
// bubble rows are not read. An unchanged composer is then neither read nor uploaded. A bubble
|
|
28
|
+
// Cursor rewrites without touching its composer is read at the composer's next change.
|
|
29
|
+
// The listing is kept in ~/.conare/cursor-composers.json with the database's stamp (the file
|
|
30
|
+
// and its -wal, where Cursor's writes land until a checkpoint): while both are unchanged the
|
|
31
|
+
// database is not opened at all. When it cannot be read (busy, corrupt), the last listing
|
|
32
|
+
// stands, so the chats already synced stay stamped, and it is tried again next run.
|
|
33
|
+
//
|
|
34
|
+
// Rules kept: the user's text and the model's; tool calls as one summary line; tool output
|
|
35
|
+
// only for a failed call (status "error"), clipped; thinking dropped. Dropped from the retired
|
|
36
|
+
// CLI: the 50-character minimum turn and pairing each answer with one prompt.
|
|
37
|
+
//
|
|
38
|
+
// The database is opened read-only through node:sqlite (Node 22.13 or newer, Bun): never a
|
|
39
|
+
// write, never a checkpoint. Where the runtime has none, Cursor is not synced and the sync says
|
|
40
|
+
// why (others.ts).
|
|
41
|
+
import { readFileSync, statSync } from "node:fs";
|
|
42
|
+
import { createRequire } from "node:module";
|
|
43
|
+
import { writePrivate } from "../config.js";
|
|
44
|
+
import { clip, dropBinary, summarizeTool, toIso } from "../transcript.js";
|
|
45
|
+
const ERROR_MAX = 1_000;
|
|
46
|
+
const BUSY_MS = 2_000;
|
|
47
|
+
let sqlite;
|
|
48
|
+
/**
|
|
49
|
+
* node:sqlite, or undefined where the runtime has none (Node before 22.13, a Bun without it).
|
|
50
|
+
* Loaded synchronously so the listing stays synchronous like the other sources'.
|
|
51
|
+
*/
|
|
52
|
+
export function loadSqlite() {
|
|
53
|
+
if (sqlite === undefined) {
|
|
54
|
+
// Node 22.13 to 24 warn on stderr that SQLite is experimental: a --quiet run prints nothing.
|
|
55
|
+
const emit = process.emitWarning;
|
|
56
|
+
process.emitWarning = ((warning, ...rest) => {
|
|
57
|
+
if (/sqlite/i.test(typeof warning === "string" ? warning : String(warning?.message)))
|
|
58
|
+
return;
|
|
59
|
+
emit.call(process, warning, ...rest);
|
|
60
|
+
});
|
|
61
|
+
try {
|
|
62
|
+
const mod = createRequire(import.meta.url)("node:sqlite");
|
|
63
|
+
sqlite = typeof mod.DatabaseSync === "function" ? mod : null;
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
sqlite = null;
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
process.emitWarning = emit;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return sqlite ?? undefined;
|
|
73
|
+
}
|
|
74
|
+
function open(db) {
|
|
75
|
+
const { DatabaseSync } = loadSqlite();
|
|
76
|
+
const d = new DatabaseSync(db, { readOnly: true });
|
|
77
|
+
try {
|
|
78
|
+
d.exec(`PRAGMA busy_timeout = ${BUSY_MS}`);
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
d.close();
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
return d;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Every composer in Cursor's database, with its stamp. `save` keeps the listing for the next
|
|
88
|
+
* run (not in a dry run or `sync status`); `log` hears why the database could not be read.
|
|
89
|
+
*/
|
|
90
|
+
export function findCursorFiles(db, listFile, opts = {}) {
|
|
91
|
+
if (!loadSqlite())
|
|
92
|
+
return [];
|
|
93
|
+
let stamp;
|
|
94
|
+
try {
|
|
95
|
+
const s = statSync(db);
|
|
96
|
+
let wal = "-";
|
|
97
|
+
try {
|
|
98
|
+
const w = statSync(`${db}-wal`);
|
|
99
|
+
wal = `${w.size}:${w.mtimeMs}`;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// No write-ahead log: Cursor is closed, or checkpointed and removed it.
|
|
103
|
+
}
|
|
104
|
+
stamp = `${s.size}:${s.mtimeMs}:${wal}`;
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return []; // No Cursor here.
|
|
108
|
+
}
|
|
109
|
+
const saved = readListing(listFile, db);
|
|
110
|
+
let composers;
|
|
111
|
+
if (saved && saved.stamp === stamp) {
|
|
112
|
+
composers = saved.composers;
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
try {
|
|
116
|
+
composers = listComposers(db);
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
opts.log?.(`Could not read Cursor's chats (${err instanceof Error ? err.message : String(err)}); tried again next run.`);
|
|
120
|
+
composers = saved?.composers ?? [];
|
|
121
|
+
stamp = ""; // whatever is saved stays as it is
|
|
122
|
+
}
|
|
123
|
+
if (opts.save && stamp)
|
|
124
|
+
writePrivate(listFile, JSON.stringify({ db, stamp, composers }));
|
|
125
|
+
}
|
|
126
|
+
return composers.map(([composerId, size, mtimeMs]) => ({ path: `${db}#${composerId}`, composerId, stamp: { size, mtimeMs } }));
|
|
127
|
+
}
|
|
128
|
+
function readListing(file, db) {
|
|
129
|
+
try {
|
|
130
|
+
const l = JSON.parse(readFileSync(file, "utf8"));
|
|
131
|
+
return l.db === db && typeof l.stamp === "string" && Array.isArray(l.composers) ? l : undefined;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// ";" follows ":": the range is every key starting "composerData:", read through the key's
|
|
138
|
+
// index. json_valid first: json_extract fails the whole query on one malformed row.
|
|
139
|
+
const LIST = `SELECT substr(key, 14) AS id, length(value) AS size,
|
|
140
|
+
CASE WHEN json_valid(CAST(value AS TEXT)) THEN coalesce(json_extract(CAST(value AS TEXT), '$.lastUpdatedAt'), json_extract(CAST(value AS TEXT), '$.createdAt')) END AS at
|
|
141
|
+
FROM cursorDiskKV WHERE key >= 'composerData:' AND key < 'composerData;'`;
|
|
142
|
+
function listComposers(db) {
|
|
143
|
+
const d = open(db);
|
|
144
|
+
try {
|
|
145
|
+
return d.prepare(LIST).all()
|
|
146
|
+
.filter((r) => typeof r.id === "string" && r.id)
|
|
147
|
+
.map((r) => {
|
|
148
|
+
const at = typeof r.at === "number" ? r.at : typeof r.at === "string" ? Date.parse(r.at) : NaN;
|
|
149
|
+
return [r.id, Number(r.size) || 0, Number.isFinite(at) ? at : 0];
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
d.close();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
export function readCursorComposer(db, composerId) {
|
|
157
|
+
const d = open(db);
|
|
158
|
+
try {
|
|
159
|
+
const get = d.prepare("SELECT value FROM cursorDiskKV WHERE key = ?");
|
|
160
|
+
const value = (key) => text(get.get(key)?.value);
|
|
161
|
+
return parseCursor(composerId, value(`composerData:${composerId}`), (bubbleId) => value(`bubbleId:${composerId}:${bubbleId}`));
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
d.close();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** A value column as text: Cursor writes JSON text, which may come back as a BLOB. */
|
|
168
|
+
function text(v) {
|
|
169
|
+
if (typeof v === "string")
|
|
170
|
+
return v;
|
|
171
|
+
if (v instanceof Uint8Array)
|
|
172
|
+
return Buffer.from(v).toString("utf8");
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
function parseJson(text) {
|
|
176
|
+
if (text === undefined)
|
|
177
|
+
return undefined;
|
|
178
|
+
try {
|
|
179
|
+
return JSON.parse(text);
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/** One composer from its row's JSON and a lookup of its bubble rows. Pure: no database access. */
|
|
186
|
+
export function parseCursor(composerId, composerJson, bubbleRow) {
|
|
187
|
+
const parsed = parseJson(composerJson);
|
|
188
|
+
const c = parsed && typeof parsed === "object" ? parsed : {};
|
|
189
|
+
const inline = Array.isArray(c.conversation) && c.conversation.length > 0;
|
|
190
|
+
const list = (inline ? c.conversation : c.fullConversationHeadersOnly);
|
|
191
|
+
const messages = [];
|
|
192
|
+
let first;
|
|
193
|
+
let last;
|
|
194
|
+
const push = (role, part, time) => {
|
|
195
|
+
const m = messages.at(-1);
|
|
196
|
+
if (m && m.role === role && (role === "Assistant" || time === undefined))
|
|
197
|
+
m.parts.push(part);
|
|
198
|
+
else
|
|
199
|
+
messages.push({ role, time, parts: [part] });
|
|
200
|
+
};
|
|
201
|
+
for (const header of Array.isArray(list) ? list : []) {
|
|
202
|
+
if (!header || typeof header !== "object")
|
|
203
|
+
continue;
|
|
204
|
+
const h = header;
|
|
205
|
+
const b = (inline ? h : typeof h.bubbleId === "string" ? parseJson(bubbleRow(h.bubbleId)) : undefined);
|
|
206
|
+
if (!b || typeof b !== "object")
|
|
207
|
+
continue;
|
|
208
|
+
const type = b.type ?? h.type;
|
|
209
|
+
const time = toIso(b.createdAt);
|
|
210
|
+
const said = typeof b.text === "string" ? dropBinary(b.text).trim() : "";
|
|
211
|
+
let spoke = false;
|
|
212
|
+
if (type === 1 && said) {
|
|
213
|
+
push("User", { type: "text", text: said }, time);
|
|
214
|
+
spoke = true;
|
|
215
|
+
}
|
|
216
|
+
else if (type === 2) {
|
|
217
|
+
if (said)
|
|
218
|
+
push("Assistant", { type: "text", text: said });
|
|
219
|
+
const tool = b.toolFormerData;
|
|
220
|
+
if (tool && typeof tool === "object" && typeof tool.name === "string" && tool.name) {
|
|
221
|
+
push("Assistant", { type: "tool", text: summarizeTool(tool.name, args(tool.rawArgs ?? tool.params)) });
|
|
222
|
+
if (tool.status === "error" && typeof tool.result === "string" && tool.result.trim())
|
|
223
|
+
push("Assistant", { type: "output", text: clip(tool.result, ERROR_MAX), error: true });
|
|
224
|
+
spoke = true;
|
|
225
|
+
}
|
|
226
|
+
spoke ||= Boolean(said);
|
|
227
|
+
}
|
|
228
|
+
if (spoke && time) {
|
|
229
|
+
first ??= time;
|
|
230
|
+
last = time;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const startedAt = toIso(c.createdAt) ?? first;
|
|
234
|
+
return {
|
|
235
|
+
source: "cursor",
|
|
236
|
+
sessionId: composerId,
|
|
237
|
+
agent: "Cursor session",
|
|
238
|
+
title: typeof c.name === "string" && c.name.trim() ? c.name : undefined,
|
|
239
|
+
startedAt,
|
|
240
|
+
endedAt: toIso(c.lastUpdatedAt) ?? last ?? startedAt,
|
|
241
|
+
messages,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
/** A tool call's arguments: Cursor keeps them as JSON text. */
|
|
245
|
+
function args(raw) {
|
|
246
|
+
if (typeof raw !== "string")
|
|
247
|
+
return raw;
|
|
248
|
+
const parsed = parseJson(raw);
|
|
249
|
+
return parsed && typeof parsed === "object" ? parsed : raw;
|
|
250
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Pi coding agent sessions (pi-mono's coding-agent, `pi`).
|
|
2
|
+
//
|
|
3
|
+
// Layout: <sessions>/--<cwd with / \ : as ->--/<time>_<session id>.jsonl, <sessions> being
|
|
4
|
+
// $PI_CODING_AGENT_SESSION_DIR, else $PI_CODING_AGENT_DIR/sessions, else ~/.pi/agent/sessions.
|
|
5
|
+
// The first line is a header {type: "session", version, id, timestamp, cwd, parentSession};
|
|
6
|
+
// every other line an entry {type, id, parentId, timestamp, ...}: message, model_change,
|
|
7
|
+
// thinking_level_change, compaction, branch_summary, label, session_info, custom, ...
|
|
8
|
+
// A message entry's `message` is {role, content, timestamp (ms)}: user (content a string or
|
|
9
|
+
// text/image blocks), assistant (text, thinking and toolCall {id, name, arguments} blocks,
|
|
10
|
+
// stopReason, errorMessage), toolResult {toolCallId, toolName, content, isError}, and
|
|
11
|
+
// bashExecution {command, output, exitCode} for a `!` command the user ran.
|
|
12
|
+
// No Pi store was on the machine this was written on: the format comes from the retired CLI's
|
|
13
|
+
// reader (mid-2026) and pi-mono's docs/session-format.md and packages/ai types as of
|
|
14
|
+
// 2026-11; it was not checked against a current install. Unknown entry types and roles are
|
|
15
|
+
// ignored.
|
|
16
|
+
//
|
|
17
|
+
// Rules kept, each justified by the format:
|
|
18
|
+
// - A file is a tree (version 2 and later): /tree and /fork leave abandoned branches in it.
|
|
19
|
+
// The conversation is the path from the last entry written (Pi's current leaf) back to the
|
|
20
|
+
// root, every entry type included, since a model_change or compaction entry is a link of
|
|
21
|
+
// that chain. A file with no ids (version 1, linear) is read in order.
|
|
22
|
+
// - compaction and branch_summary entries restate earlier turns: skipped (the turns they
|
|
23
|
+
// summarize are still on the path).
|
|
24
|
+
// - thinking blocks: skipped (model-internal).
|
|
25
|
+
// - Tool calls become one summary line; output is kept only for failures (isError), clipped.
|
|
26
|
+
// - An assistant message's errorMessage (a failed or aborted request) is a harness message:
|
|
27
|
+
// not rendered, as Claude Code's API error records are not.
|
|
28
|
+
// - A `!` command the user ran renders as "! command"; its output is dropped, as for Claude Code.
|
|
29
|
+
// - session_info's name is the title.
|
|
30
|
+
// - custom messages come from extensions, not the user or the model: skipped.
|
|
31
|
+
// Dropped from the retired CLI: the 50-character minimum user turn and the narration filter.
|
|
32
|
+
import { readdirSync } from "node:fs";
|
|
33
|
+
import { join } from "node:path";
|
|
34
|
+
import { clip, dropBinary, readLines, summarizeTool, toIso } from "../transcript.js";
|
|
35
|
+
const ERROR_MAX = 1_000;
|
|
36
|
+
/** Every session under the sessions directory. The id is the file name, as the retired CLI keyed it. */
|
|
37
|
+
export function findPiFiles(sessionsDir) {
|
|
38
|
+
const files = [];
|
|
39
|
+
const walk = (dir) => {
|
|
40
|
+
let entries;
|
|
41
|
+
try {
|
|
42
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
const path = join(dir, entry.name);
|
|
49
|
+
if (entry.isDirectory())
|
|
50
|
+
walk(path);
|
|
51
|
+
else if (entry.isFile() && entry.name.endsWith(".jsonl"))
|
|
52
|
+
files.push({ path, sessionId: entry.name.slice(0, -".jsonl".length) });
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
walk(sessionsDir);
|
|
56
|
+
return files.sort((a, b) => a.path.localeCompare(b.path));
|
|
57
|
+
}
|
|
58
|
+
export function readPiFile(file) {
|
|
59
|
+
return parsePi(readLines(file.path), file.sessionId);
|
|
60
|
+
}
|
|
61
|
+
/** Parse a session's JSONL text, or its lines. Pure: no file access. */
|
|
62
|
+
export function parsePi(jsonl, sessionId) {
|
|
63
|
+
const entries = [];
|
|
64
|
+
let cwd;
|
|
65
|
+
let title;
|
|
66
|
+
let startedAt;
|
|
67
|
+
for (const line of typeof jsonl === "string" ? jsonl.split("\n") : jsonl) {
|
|
68
|
+
if (!line.trim())
|
|
69
|
+
continue;
|
|
70
|
+
let rec;
|
|
71
|
+
try {
|
|
72
|
+
rec = JSON.parse(line);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
continue; // A line cut off mid-write by a running session.
|
|
76
|
+
}
|
|
77
|
+
if (!rec || typeof rec !== "object")
|
|
78
|
+
continue;
|
|
79
|
+
if (rec.type === "session") {
|
|
80
|
+
if (typeof rec.cwd === "string")
|
|
81
|
+
cwd ??= rec.cwd;
|
|
82
|
+
startedAt ??= toIso(rec.timestamp);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (rec.type === "session_info" && typeof rec.name === "string")
|
|
86
|
+
title = rec.name;
|
|
87
|
+
entries.push(rec);
|
|
88
|
+
}
|
|
89
|
+
const messages = [];
|
|
90
|
+
let endedAt;
|
|
91
|
+
const push = (role, part, time) => {
|
|
92
|
+
const last = messages.at(-1);
|
|
93
|
+
if (last && last.role === role && (role === "Assistant" || time === undefined))
|
|
94
|
+
last.parts.push(part);
|
|
95
|
+
else
|
|
96
|
+
messages.push({ role, time, parts: [part] });
|
|
97
|
+
};
|
|
98
|
+
for (const entry of activePath(entries)) {
|
|
99
|
+
const m = entry.message;
|
|
100
|
+
if (entry.type !== "message" || !m || typeof m !== "object")
|
|
101
|
+
continue;
|
|
102
|
+
const time = toIso(entry.timestamp) ?? toIso(m.timestamp);
|
|
103
|
+
let spoke = true;
|
|
104
|
+
switch (m.role) {
|
|
105
|
+
case "user": {
|
|
106
|
+
const text = blocksText(m.content);
|
|
107
|
+
if (text)
|
|
108
|
+
push("User", { type: "text", text }, time);
|
|
109
|
+
else
|
|
110
|
+
spoke = false;
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
case "bashExecution":
|
|
114
|
+
if (typeof m.command === "string" && m.command.trim())
|
|
115
|
+
push("User", { type: "text", text: `! ${m.command.trim()}` }, time);
|
|
116
|
+
else
|
|
117
|
+
spoke = false;
|
|
118
|
+
break;
|
|
119
|
+
case "assistant":
|
|
120
|
+
spoke = false;
|
|
121
|
+
for (const b of Array.isArray(m.content) ? m.content : []) {
|
|
122
|
+
const text = b?.type === "text" && typeof b.text === "string" ? dropBinary(b.text).trim() : "";
|
|
123
|
+
if (text)
|
|
124
|
+
push("Assistant", { type: "text", text });
|
|
125
|
+
else if (b?.type === "toolCall")
|
|
126
|
+
push("Assistant", { type: "tool", text: summarizeTool(typeof b.name === "string" ? b.name : "tool", b.arguments) });
|
|
127
|
+
else
|
|
128
|
+
continue;
|
|
129
|
+
spoke = true;
|
|
130
|
+
}
|
|
131
|
+
break;
|
|
132
|
+
case "toolResult": {
|
|
133
|
+
const text = m.isError === true ? blocksText(m.content) : "";
|
|
134
|
+
if (text)
|
|
135
|
+
push("Assistant", { type: "output", text: clip(text, ERROR_MAX), error: true });
|
|
136
|
+
else
|
|
137
|
+
spoke = false;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
default:
|
|
141
|
+
spoke = false; // custom messages and anything newer
|
|
142
|
+
}
|
|
143
|
+
if (spoke && time) {
|
|
144
|
+
startedAt ??= time;
|
|
145
|
+
endedAt = time;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return { source: "pi", sessionId, agent: "Pi session", title, cwd, startedAt, endedAt: endedAt ?? startedAt, messages };
|
|
149
|
+
}
|
|
150
|
+
/** The entries from the root to the last one written, by parentId; every entry in order when the file has no ids. */
|
|
151
|
+
function activePath(entries) {
|
|
152
|
+
const byId = new Map();
|
|
153
|
+
for (const e of entries)
|
|
154
|
+
if (typeof e.id === "string")
|
|
155
|
+
byId.set(e.id, e);
|
|
156
|
+
if (byId.size === 0)
|
|
157
|
+
return entries;
|
|
158
|
+
let leaf;
|
|
159
|
+
for (let i = entries.length - 1; i >= 0 && !leaf; i--)
|
|
160
|
+
if (typeof entries[i].id === "string")
|
|
161
|
+
leaf = entries[i];
|
|
162
|
+
const path = [];
|
|
163
|
+
const seen = new Set();
|
|
164
|
+
for (let e = leaf; e && typeof e.id === "string" && !seen.has(e.id); e = typeof e.parentId === "string" ? byId.get(e.parentId) : undefined) {
|
|
165
|
+
seen.add(e.id);
|
|
166
|
+
path.push(e);
|
|
167
|
+
}
|
|
168
|
+
return path.reverse();
|
|
169
|
+
}
|
|
170
|
+
/** The text of a string or of text and image blocks; an image becomes a marker. */
|
|
171
|
+
function blocksText(content) {
|
|
172
|
+
if (typeof content === "string")
|
|
173
|
+
return dropBinary(content).trim();
|
|
174
|
+
if (!Array.isArray(content))
|
|
175
|
+
return "";
|
|
176
|
+
return content
|
|
177
|
+
.map((b) => (b?.type === "text" && typeof b.text === "string" ? dropBinary(b.text).trim() : b?.type === "image" ? "[image]" : ""))
|
|
178
|
+
.filter(Boolean)
|
|
179
|
+
.join("\n\n");
|
|
180
|
+
}
|
package/dist/cli/state.js
CHANGED
|
@@ -2,16 +2,19 @@
|
|
|
2
2
|
// content_hash the server accepted. It is written only after the server accepts a batch,
|
|
3
3
|
// so a failed batch leaves its ids unsynced for the next run.
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
|
-
import { closeSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, utimesSync, writeSync } from "node:fs";
|
|
5
|
+
import { closeSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, utimesSync, writeSync } from "node:fs";
|
|
6
6
|
import { dirname } from "node:path";
|
|
7
|
+
import { VERSION } from "../index.js";
|
|
7
8
|
import { writePrivate } from "./config.js";
|
|
8
9
|
/** Bump when rendering changes, so files skipped by their stamp are read again. */
|
|
9
10
|
export const RENDERER = 1;
|
|
10
|
-
|
|
11
|
-
|
|
11
|
+
/** One key writes another organization's namespaces with --org: its own state. */
|
|
12
|
+
export function accountOf(baseURL, apiKey, org) {
|
|
13
|
+
return createHash("sha256").update(`${baseURL}\n${apiKey}${org ? `\n${org}` : ""}`).digest("hex").slice(0, 16);
|
|
12
14
|
}
|
|
15
|
+
/** The saved state, or an empty one when it was written for another account; `account` undefined (no key) takes whatever is saved. */
|
|
13
16
|
export function loadState(path, account) {
|
|
14
|
-
const empty = { account, renderer: RENDERER, documents: {}, parts: {}, files: {} };
|
|
17
|
+
const empty = { account: account ?? "", renderer: RENDERER, documents: {}, parts: {}, files: {}, skipped: {}, version: VERSION };
|
|
15
18
|
let saved;
|
|
16
19
|
try {
|
|
17
20
|
saved = JSON.parse(readFileSync(path, "utf8"));
|
|
@@ -19,20 +22,24 @@ export function loadState(path, account) {
|
|
|
19
22
|
catch {
|
|
20
23
|
return empty; // Missing or corrupt: everything uploads again, which is safe (same ids).
|
|
21
24
|
}
|
|
22
|
-
if (saved.account !== account || typeof saved.documents !== "object" || !saved.documents)
|
|
25
|
+
if ((account !== undefined && saved.account !== account) || typeof saved.documents !== "object" || !saved.documents)
|
|
23
26
|
return empty;
|
|
27
|
+
const sameRenderer = saved.renderer === RENDERER;
|
|
24
28
|
return {
|
|
25
|
-
account,
|
|
29
|
+
account: account ?? saved.account ?? "",
|
|
26
30
|
renderer: RENDERER,
|
|
27
31
|
documents: saved.documents,
|
|
28
32
|
parts: saved.parts && typeof saved.parts === "object" ? saved.parts : {},
|
|
29
|
-
files:
|
|
33
|
+
files: sameRenderer && saved.files && typeof saved.files === "object" ? saved.files : {},
|
|
34
|
+
skipped: sameRenderer && saved.version === VERSION && saved.skipped && typeof saved.skipped === "object" ? saved.skipped : {},
|
|
35
|
+
version: VERSION,
|
|
36
|
+
...(typeof saved.checkedAt === "number" ? { checkedAt: saved.checkedAt } : {}),
|
|
30
37
|
};
|
|
31
38
|
}
|
|
32
39
|
export function saveState(path, state) {
|
|
33
40
|
writePrivate(path, JSON.stringify(state));
|
|
34
41
|
}
|
|
35
|
-
/** True when the file is unchanged since all of its documents reached the server. */
|
|
42
|
+
/** True when the file is unchanged since all of its documents reached the server (or since it was skipped, for `skipped`). */
|
|
36
43
|
export function isStamped(files, path, stat) {
|
|
37
44
|
const s = files[path];
|
|
38
45
|
return !!s && s.size === stat.size && s.mtimeMs === stat.mtimeMs;
|
|
@@ -65,7 +72,9 @@ export function acquireLock(path) {
|
|
|
65
72
|
return () => {
|
|
66
73
|
clearInterval(heartbeat);
|
|
67
74
|
try {
|
|
68
|
-
|
|
75
|
+
// Only our own: a run that judged us stale (a hung disk) may hold it now.
|
|
76
|
+
if (readFileSync(path, "utf8") === String(process.pid))
|
|
77
|
+
unlinkSync(path);
|
|
69
78
|
}
|
|
70
79
|
catch {
|
|
71
80
|
// Already gone.
|
|
@@ -75,12 +84,27 @@ export function acquireLock(path) {
|
|
|
75
84
|
catch (err) {
|
|
76
85
|
if (err.code !== "EEXIST" || !isStaleLock(path))
|
|
77
86
|
return undefined;
|
|
87
|
+
// Two runs may both judge it stale: a rename has one winner, where two unlinks would each
|
|
88
|
+
// remove what the other just created.
|
|
89
|
+
const aside = `${path}.stale.${process.pid}`;
|
|
78
90
|
try {
|
|
79
|
-
|
|
91
|
+
renameSync(path, aside);
|
|
80
92
|
}
|
|
81
93
|
catch {
|
|
94
|
+
return undefined; // another run took it over first
|
|
95
|
+
}
|
|
96
|
+
if (!isStaleLock(aside)) {
|
|
97
|
+
// What was renamed is the lock that run had just made: give it back unless a third has one.
|
|
98
|
+
try {
|
|
99
|
+
linkSync(aside, path);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// Leave the newer one.
|
|
103
|
+
}
|
|
104
|
+
rmSync(aside, { force: true });
|
|
82
105
|
return undefined;
|
|
83
106
|
}
|
|
107
|
+
rmSync(aside, { force: true });
|
|
84
108
|
}
|
|
85
109
|
}
|
|
86
110
|
return undefined;
|