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.
@@ -1,7 +1,7 @@
1
1
  // The record of sessions sync runs: one line per run appended to ~/.conare/sync.log, and the
2
2
  // last run, the last success and the newest uploaded session in ~/.conare/sync-status.json,
3
3
  // which `conare sync status` reads.
4
- import { appendFileSync, mkdirSync, readFileSync, statSync } from "node:fs";
4
+ import { appendFileSync, chmodSync, mkdirSync, readFileSync, statSync } from "node:fs";
5
5
  import { dirname } from "node:path";
6
6
  import { writePrivate } from "./config.js";
7
7
  import { displayTime } from "./render.js";
@@ -30,7 +30,8 @@ function counts(run) {
30
30
  export function recordRun(files, run, newest) {
31
31
  try {
32
32
  mkdirSync(dirname(files.logFile), { recursive: true, mode: 0o700 });
33
- appendFileSync(files.logFile, `${runLine(run)}\n`);
33
+ appendFileSync(files.logFile, `${runLine(run)}\n`, { mode: 0o600 });
34
+ chmodSync(files.logFile, 0o600); // one made by launchd or systemd, or an older version, is 0644
34
35
  }
35
36
  catch {
36
37
  // A full or read-only disk: the status file below may still be written.
@@ -50,17 +51,19 @@ export function recordRun(files, run, newest) {
50
51
  }
51
52
  /**
52
53
  * Transcripts last changed before `before` (the start of the last successful run) that the
53
- * sync state does not stamp as synced. A run stamps every file it read, uploaded or not (empty
54
- * sessions and duplicates included), so one of these was never read by that run: the
55
- * background sync scans another directory (CLAUDE_CONFIG_DIR or CODEX_HOME changed since
56
- * --install), the file cannot be read, or the server refused its documents.
54
+ * sync state does not stamp. A run stamps every file it read: uploaded, already held (empty
55
+ * sessions and duplicates included), or deliberately left out (an excluded project, or no
56
+ * message this version can read: `skipped`). So one of these was not read by that run: the
57
+ * background sync scans another directory (CLAUDE_CONFIG_DIR, CODEX_HOME or Pi's directory
58
+ * changed since --install), the file cannot be read, or the server refused its documents. A
59
+ * transcript listed with its own stamp (a Cursor chat, which is not a file) is judged by it.
57
60
  */
58
- export function unsyncedTranscripts(paths, stamps, before) {
61
+ export function unsyncedTranscripts(files, stamps, before) {
59
62
  const out = [];
60
- for (const path of paths) {
63
+ for (const { path, stamp } of files) {
61
64
  let stat;
62
65
  try {
63
- stat = statSync(path);
66
+ stat = stamp ?? statSync(path);
64
67
  }
65
68
  catch {
66
69
  continue; // removed since it was listed
@@ -72,11 +75,12 @@ export function unsyncedTranscripts(paths, stamps, before) {
72
75
  }
73
76
  return out;
74
77
  }
75
- /** The file stamps in a sync state file, whatever key wrote it; {} when there is none. */
78
+ /** The file stamps in a sync state file, synced or skipped, whatever key wrote it; {} when there is none. */
76
79
  export function readStamps(stateFile) {
77
80
  try {
78
- const files = JSON.parse(readFileSync(stateFile, "utf8")).files;
79
- return files && typeof files === "object" ? files : {};
81
+ const { files, skipped } = JSON.parse(readFileSync(stateFile, "utf8"));
82
+ const object = (v) => (v && typeof v === "object" ? v : {});
83
+ return { ...object(skipped), ...object(files) };
80
84
  }
81
85
  catch {
82
86
  return {};
@@ -95,13 +99,13 @@ export function describeStatus(status, now, schedule, unsynced = []) {
95
99
  lines.push(`Last success: ${status.lastSuccessAt ? when(status.lastSuccessAt, now) : "never"}`);
96
100
  const newest = status.newestSession;
97
101
  lines.push(`Newest upload: ${newest ? `${newest.id}, last activity ${when(newest.date, now)}` : "none recorded"}`);
98
- lines.push(`Background: ${schedule ?? "not installed (conare sync --install)"}`);
102
+ lines.push(`Background: ${schedule ?? "not installed (npx conare sync --install)"}`);
99
103
  const success = status.lastSuccessAt ? Date.parse(status.lastSuccessAt) : NaN;
100
104
  const recent = Number.isFinite(success) && now - success <= MAX_SUCCESS_AGE_MS;
101
105
  if (!recent)
102
106
  lines.push(status.lastSuccessAt ? "UNHEALTHY: the last successful sync is over 1 h old." : "UNHEALTHY: no successful sync recorded.");
103
107
  if (unsynced.length > 0) {
104
- lines.push(`UNHEALTHY: ${unsynced.length} transcripts changed before the last successful sync are not synced, e.g. ${unsynced[0]}.`, " The background sync may read another directory (CLAUDE_CONFIG_DIR or CODEX_HOME changed since --install: run it again), or could not read or upload them (see the log).");
108
+ lines.push(`UNHEALTHY: ${unsynced.length} transcripts changed before the last successful sync are not synced, e.g. ${unsynced[0]}.`, " The background sync may read another directory (CLAUDE_CONFIG_DIR, CODEX_HOME or PI_CODING_AGENT_DIR changed since --install: run it again), or could not read or upload them (see the log).");
105
109
  }
106
110
  return { text: `${lines.join("\n")}\n`, ok: recent && unsynced.length === 0 };
107
111
  }
package/dist/cli/sync.js CHANGED
@@ -5,28 +5,43 @@ import { NAMESPACE, baseId, toDocuments } from "./documents.js";
5
5
  import { projectName } from "./project.js";
6
6
  import { findClaudeFiles, readClaudeFile } from "./sources/claude.js";
7
7
  import { findCodexFiles, readCodexFile } from "./sources/codex.js";
8
+ import { findCursorFiles, readCursorComposer } from "./sources/cursor.js";
9
+ import { findPiFiles, readPiFile } from "./sources/pi.js";
8
10
  import { isStamped, loadState, saveState } from "./state.js";
9
11
  import { BATCH_BYTES, BATCH_DOCUMENTS, UPLOADS_IN_FLIGHT, heldAs, listLayouts, removeStaleParts, sendBatch, splitPart } from "./upload.js";
10
- export function findTranscripts(paths) {
12
+ /** `save` keeps Cursor's listing for the next run (not in a dry run or `sync status`); `log` hears why Cursor's database could not be read. */
13
+ export function findTranscripts(paths, opts = {}) {
11
14
  return [
12
15
  ...findClaudeFiles(paths.claudeDir).map((f) => ({ path: f.path, read: () => readClaudeFile(f) })),
13
16
  ...findCodexFiles(paths.codexDir).map((f) => ({ path: f.path, read: () => readCodexFile(f) })),
17
+ ...findPiFiles(paths.piDir).map((f) => ({ path: f.path, read: () => readPiFile(f) })),
18
+ ...findCursorFiles(paths.cursorDb, paths.cursorListFile, opts).map((f) => ({ path: f.path, stamp: f.stamp, read: () => readCursorComposer(paths.cursorDb, f.composerId) })),
14
19
  ];
15
20
  }
21
+ /**
22
+ * How often the state is checked against a listing of the namespace, which finds what the
23
+ * server no longer holds (a session deleted in the console, an erased namespace). The listing
24
+ * reads every document id (44 pages and about a minute for 4,400 sessions), so a 10-minute
25
+ * schedule does it once a day: what the server lost goes up again within a day.
26
+ */
27
+ export const CHECK_EVERY_MS = 24 * 60 * 60 * 1000;
16
28
  export async function runSync(opts) {
17
29
  const dryRun = !opts.client;
18
30
  const ns = opts.client?.namespace(NAMESPACE);
19
31
  const log = opts.log ?? (() => { });
20
32
  const state = loadState(opts.stateFile, opts.account);
33
+ const now = opts.now ?? Date.now();
21
34
  const report = { sessions: 0, documents: 0, bytes: 0, unchanged: 0, excluded: 0, unread: 0, unreadable: [], deleted: 0, rejected: [], planned: [] };
22
- // The layout the server holds for a session: what the state said this tool stored last;
23
- // on a fresh state (the first sync, after the migration of older history), or for a session
24
- // whose upload an earlier run cut short after some of its documents were accepted (0: any
25
- // of its parts, gaps included, may be there), one listing of the namespace, read once;
26
- // else unknown, and probed.
35
+ // The layout the server holds for a session: the listing of the namespace, when this run
36
+ // read one; else what the state said this tool stored last; on a fresh state (the first
37
+ // sync, after the migration of older history), or for a session whose upload an earlier run
38
+ // cut short after some of its documents were accepted (0: any of its parts, gaps included,
39
+ // may be there), one listing, read once; else unknown, and probed.
27
40
  const fresh = !Object.values(state.parts).some((n) => n > 0);
28
41
  let layouts;
29
42
  const held = async (entry) => {
43
+ if (layouts)
44
+ return (await layouts).get(entry.base) ?? { whole: false, parts: [] };
30
45
  if (entry.previous)
31
46
  return heldAs(entry.previous);
32
47
  if (!ns || (!fresh && entry.previous !== 0))
@@ -99,8 +114,16 @@ export async function runSync(opts) {
99
114
  try {
100
115
  // What the state says the server holds and it no longer does (a delete in the console,
101
116
  // an erased namespace, a restore) goes up again: only those, since the rest still match.
102
- if (ns && Object.keys(state.documents).length > 0)
103
- forgetGone(state, await (layouts ??= listLayouts(ns)));
117
+ // Once a day (CHECK_EVERY_MS); a state with no documents (just started, or for another
118
+ // key or server) holds nothing to check, and this run uploads everything.
119
+ if (ns) {
120
+ const empty = Object.keys(state.documents).length === 0;
121
+ const due = state.checkedAt === undefined || now - state.checkedAt >= CHECK_EVERY_MS || now < state.checkedAt;
122
+ if (!empty && due)
123
+ forgetGone(state, await (layouts ??= listLayouts(ns)));
124
+ if (empty || due)
125
+ state.checkedAt = now;
126
+ }
104
127
  const files = newestFirst(opts.files);
105
128
  for (const file of files)
106
129
  await visit(file);
@@ -110,6 +133,9 @@ export async function runSync(opts) {
110
133
  for (const path of Object.keys(state.files))
111
134
  if (!present.has(path))
112
135
  delete state.files[path];
136
+ for (const path of Object.keys(state.skipped))
137
+ if (!present.has(path))
138
+ delete state.skipped[path];
113
139
  }
114
140
  finally {
115
141
  // Accepted batches are already saved; this keeps the probes and stamps of a cut-short run.
@@ -122,22 +148,40 @@ export async function runSync(opts) {
122
148
  report.unchanged++;
123
149
  return;
124
150
  }
151
+ // Left out by an earlier run and unchanged since: not read again while it would be left
152
+ // out again (its project still excluded; unread by this version).
153
+ const skip = state.skipped[file.path];
154
+ if (skip && isStamped(state.skipped, file.path, file.stamp)) {
155
+ if (skip.unread) {
156
+ report.unread++;
157
+ return;
158
+ }
159
+ if (excluded(skip.project)) {
160
+ report.excluded++;
161
+ return;
162
+ }
163
+ }
125
164
  let docs;
126
165
  let base;
127
166
  try {
128
167
  const transcript = file.read();
129
168
  const project = projectName(transcript.cwd);
130
- // Not stamped: taken off the list, the project's sessions upload on the next run.
131
- // With a list, a session of no known project may be on it: held back too.
132
- if (project === undefined ? opts.exclude?.size : opts.exclude?.has(project)) {
169
+ // Recorded apart from the synced files: taken off the list, the project's sessions upload
170
+ // on the next run. With a list, a session of no known project may be on it: held back too.
171
+ if (excluded(project)) {
133
172
  report.excluded++;
173
+ if (!dryRun)
174
+ state.skipped[file.path] = { ...file.stamp, ...(project !== undefined ? { project } : {}) };
134
175
  return;
135
176
  }
136
- // A new record format reads as no messages, and a stamp would keep the file from the CLI that can read it.
177
+ // A new record format reads as no messages; another version (or a change to the file) reads it again.
137
178
  if (transcript.messages.length === 0) {
138
179
  report.unread++;
180
+ if (!dryRun)
181
+ state.skipped[file.path] = { ...file.stamp, unread: true };
139
182
  return;
140
183
  }
184
+ delete state.skipped[file.path];
141
185
  base = baseId(transcript);
142
186
  docs = toDocuments(transcript, project);
143
187
  }
@@ -197,6 +241,9 @@ export async function runSync(opts) {
197
241
  queuedBytes += size;
198
242
  }
199
243
  }
244
+ function excluded(project) {
245
+ return Boolean(project === undefined ? opts.exclude?.size : opts.exclude?.has(project));
246
+ }
200
247
  }
201
248
  /**
202
249
  * Every document of the file is on the server: when the session's document count is new
@@ -228,12 +275,12 @@ function forgetGone(state, listed) {
228
275
  if (gone)
229
276
  state.files = {};
230
277
  }
231
- /** Stat every file (skipping ones that vanished) and order newest first, so a cut-short run keeps the recent work. */
278
+ /** Stat every file without a stamp (skipping ones that vanished) and order newest first, so a cut-short run keeps the recent work. */
232
279
  function newestFirst(files) {
233
280
  const out = [];
234
281
  for (const f of files) {
235
282
  try {
236
- const s = statSync(f.path);
283
+ const s = f.stamp ?? statSync(f.path);
237
284
  out.push({ ...f, stamp: { size: s.size, mtimeMs: s.mtimeMs } });
238
285
  }
239
286
  catch {
@@ -1,4 +1,7 @@
1
1
  // The parsed form of one agent session, shared by the sources and the renderer.
2
+ import { closeSync, openSync, readSync } from "node:fs";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import { scrub } from "./scrub.js";
2
5
  /** RFC 3339 UTC for a timestamp string or epoch number, or undefined. */
3
6
  export function toIso(value) {
4
7
  if (typeof value !== "string" && typeof value !== "number")
@@ -6,6 +9,49 @@ export function toIso(value) {
6
9
  const ms = typeof value === "number" ? (value < 1e11 ? value * 1000 : value) : Date.parse(value);
7
10
  return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
8
11
  }
12
+ const READ_CHUNK = 1 << 20;
13
+ /** A longer line is skipped as unparseable: no record of ours is anywhere near it. */
14
+ export const LINE_MAX = 64 * 1024 * 1024;
15
+ /**
16
+ * The lines of a file, read in fixed chunks. A whole transcript read as one string costs
17
+ * several times its size in memory, and over 512 MiB it is past Node's string limit and
18
+ * would fail on every run. Synchronous, as the sources are. A trailing "\r" is removed; a
19
+ * line over maxLine characters is skipped.
20
+ */
21
+ export function* readLines(path, maxLine = LINE_MAX) {
22
+ const fd = openSync(path, "r");
23
+ try {
24
+ const buf = Buffer.allocUnsafe(READ_CHUNK);
25
+ const decoder = new StringDecoder("utf8"); // keeps a character split across two chunks whole
26
+ let line = "";
27
+ let skipping = false; // inside a line already over maxLine
28
+ const done = (s) => (s.endsWith("\r") ? s.slice(0, -1) : s);
29
+ for (let n = readSync(fd, buf, 0, READ_CHUNK, null); n > 0; n = readSync(fd, buf, 0, READ_CHUNK, null)) {
30
+ const text = decoder.write(buf.subarray(0, n));
31
+ let start = 0;
32
+ for (let nl = text.indexOf("\n"); nl !== -1; nl = text.indexOf("\n", start)) {
33
+ if (!skipping && line.length + nl - start <= maxLine)
34
+ yield done(line + text.slice(start, nl));
35
+ line = "";
36
+ skipping = false;
37
+ start = nl + 1;
38
+ }
39
+ if (skipping)
40
+ continue;
41
+ line += text.slice(start);
42
+ if (line.length > maxLine) {
43
+ line = "";
44
+ skipping = true;
45
+ }
46
+ }
47
+ line += decoder.end();
48
+ if (!skipping && line && line.length <= maxLine)
49
+ yield done(line);
50
+ }
51
+ finally {
52
+ closeSync(fd);
53
+ }
54
+ }
9
55
  /**
10
56
  * An index at or below i that does not fall between the two halves of a surrogate pair (an
11
57
  * emoji is two UTF-16 units): a cut there would leave a lone half, which the API refuses.
@@ -16,7 +62,13 @@ function charBoundary(t, i) {
16
62
  }
17
63
  /** Keeps the head and the tail of a long text (errors carry their cause at either end). */
18
64
  export function clip(text, max) {
19
- const t = text.trim();
65
+ let t = text.trim();
66
+ if (t.length <= max)
67
+ return t;
68
+ // Scrubbed before the cut: a cut through a secret leaves halves no rule matches (a PEM
69
+ // key's base64 tail and END line, a token cut in two), and the document text is scrubbed
70
+ // only after clipping.
71
+ t = scrub(t);
20
72
  if (t.length <= max)
21
73
  return t;
22
74
  const head = charBoundary(t, Math.floor(max * 0.6));
@@ -25,7 +77,11 @@ export function clip(text, max) {
25
77
  }
26
78
  /** One line of at most max characters. */
27
79
  export function oneLine(text, max) {
28
- const t = text.replace(/\s+/g, " ").trim();
80
+ const flat = (s) => s.replace(/\s+/g, " ").trim();
81
+ let t = flat(text);
82
+ if (t.length <= max)
83
+ return t;
84
+ t = flat(scrub(text)); // before the cut, as in clip(); on the lines a PEM rule reads
29
85
  return t.length <= max ? t : `${t.slice(0, charBoundary(t, max - 1))}…`;
30
86
  }
31
87
  /** The text with any lone surrogate as U+FFFD (String.prototype.toWellFormed, which Node 18 lacks). */
@@ -68,6 +124,8 @@ export function summarizeTool(name, input) {
68
124
  const cmd = shellCommand(i.command) ?? shellCommand(i.cmd);
69
125
  switch (name) {
70
126
  case "Bash":
127
+ case "bash": // Pi
128
+ case "run_terminal_cmd": // Cursor
71
129
  case "shell":
72
130
  case "shell_command":
73
131
  case "exec_command":
@@ -80,7 +138,14 @@ export function summarizeTool(name, input) {
80
138
  case "MultiEdit":
81
139
  case "NotebookEdit":
82
140
  case "view_image":
83
- return `${name} ${s("file_path") ?? s("notebook_path") ?? s("path") ?? ""}`.trim();
141
+ case "read": // Pi
142
+ case "write":
143
+ case "edit":
144
+ case "read_file": // Cursor
145
+ case "edit_file":
146
+ case "search_replace":
147
+ case "delete_file":
148
+ return `${name} ${s("file_path") ?? s("notebook_path") ?? s("path") ?? s("target_file") ?? ""}`.trim();
84
149
  case "Grep":
85
150
  return `Grep "${oneLine(s("pattern") ?? "", ARG_MAX)}"${s("path") ? ` in ${s("path")}` : ""}${s("glob") ? ` (${s("glob")})` : ""}`;
86
151
  case "Glob":
@@ -1,7 +1,7 @@
1
1
  // Sending documents through the SDK client. The client retries 429, 5xx and network errors
2
2
  // with backoff, honouring Retry-After (bounded by its maxRetries); what still fails here is
3
- // either one bad document (sent again alone, then left for the next run) or a server or
4
- // auth problem that stops the run.
3
+ // either one bad document (sent again alone, then left for the next run) or a server, key or
4
+ // request problem that stops the run.
5
5
  import { ConareError } from "../index.js";
6
6
  import { partId } from "./documents.js";
7
7
  /** The API takes 1-100 documents per write; a byte budget keeps each request's embedding work small. */
@@ -28,10 +28,14 @@ export function batches(docs, maxDocs = BATCH_DOCUMENTS, maxBytes = BATCH_BYTES)
28
28
  out.push(current);
29
29
  return out;
30
30
  }
31
- /** A request the API refused because of what one of its documents holds; a bad namespace is
32
- * every document's, so sending each alone would only repeat it. */
31
+ /**
32
+ * A request the API refused because of what one of its documents holds: too large (413), or a
33
+ * 400/422 naming the document ("documents[3].text is required"). Any other 400 is every
34
+ * document's (a bad namespace, a key of several organizations without X-Conare-Org): sending
35
+ * each alone would only repeat it, so it stops the run.
36
+ */
33
37
  function isDocumentError(err) {
34
- return err instanceof ConareError && (err.status === 400 || err.status === 413 || err.status === 422) && err.code !== "invalid_namespace";
38
+ return err instanceof ConareError && (err.status === 413 || ((err.status === 400 || err.status === 422) && /\bdocuments\[\d+\]/.test(err.message)));
35
39
  }
36
40
  /**
37
41
  * Write one batch. When the API refuses the batch for its content, each document is sent
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.33.0";
1
+ export declare const VERSION = "0.34.0";
2
2
  /** A metadata value: string, number, boolean or an array of strings. */
3
3
  export type MetadataValue = string | number | boolean | string[];
4
4
  export type Metadata = Record<string, MetadataValue>;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
2
- export const VERSION = "0.33.0";
2
+ export const VERSION = "0.34.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  /** Above the API's 110 s deadline for a write: a call given up sooner is retried while the first still runs. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",