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.
- package/README.md +101 -28
- package/dist/cli/args.js +137 -0
- package/dist/cli/config.js +39 -0
- package/dist/cli/documents.js +82 -0
- package/dist/cli/github/api.js +139 -0
- package/dist/cli/github/documents.js +118 -0
- package/dist/cli/github/sync.js +244 -0
- package/dist/cli/main.js +273 -0
- package/dist/cli/project.js +61 -0
- package/dist/cli/render.js +69 -0
- package/dist/cli/schedule.js +289 -0
- package/dist/cli/scrub.js +115 -0
- package/dist/cli/sources/claude.js +313 -0
- package/dist/cli/sources/codex.js +266 -0
- package/dist/cli/state.js +101 -0
- package/dist/cli/status.js +125 -0
- package/dist/cli/sync.js +219 -0
- package/dist/cli/transcript.js +103 -0
- package/dist/cli/upload.js +139 -0
- package/dist/index.d.ts +453 -45
- package/dist/index.js +565 -52
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# conare
|
|
2
2
|
|
|
3
|
-
TypeScript client for [Conare](https://conare.ai): add documents, query them, connect apps.
|
|
3
|
+
TypeScript client for [Conare](https://conare.ai): add documents, query them, connect apps, sync your own.
|
|
4
4
|
No dependencies. Works on Node 18+, Bun, Deno and edge runtimes.
|
|
5
5
|
|
|
6
6
|
## Quickstart
|
|
@@ -31,10 +31,16 @@ A namespace is created by its first write. Writing the same id again replaces th
|
|
|
31
31
|
```ts
|
|
32
32
|
new Conare() // CONARE_API_KEY from the environment
|
|
33
33
|
new Conare({ apiKey, baseURL, timeout: 60_000, maxRetries: 2 })
|
|
34
|
+
await conare.organizations() // [{ id, name, role }]: the organizations the key acts for
|
|
35
|
+
new Conare({ organization: "org_…" }) // acts for that one (X-Conare-Org)
|
|
34
36
|
```
|
|
35
37
|
|
|
36
38
|
Every method also takes `{ signal, timeout }` as its last option.
|
|
37
39
|
|
|
40
|
+
A key acts for its own organization. A multi-organization key (made in the console by an admin of
|
|
41
|
+
each organization it names) acts for any of them: make one client per organization with
|
|
42
|
+
`organization`. Without it, such a key answers 400 on every call but `organizations()`.
|
|
43
|
+
|
|
38
44
|
### Namespaces and documents
|
|
39
45
|
|
|
40
46
|
```ts
|
|
@@ -58,8 +64,8 @@ await docs.uploadFile(bytes, "report.pdf"); // a PDF (one document per page)
|
|
|
58
64
|
// up to 20 MiB. The same name (or { id }) again replaces it.
|
|
59
65
|
// Returns { fileId, type, ids, pages, sheets, pagesOcr, pagesWithoutText, ocrPending }:
|
|
60
66
|
// scanned pages are OCR'd after the answer (ocrPending; { wait: true } reads them first)
|
|
67
|
+
await docs.getFile("report.pdf"); // that upload's outcome, OCR after the answer included (kept 7 days)
|
|
61
68
|
await docs.drop(); // delete the namespace and its documents (succeeds if already emptied; 404 namespace_not_found if never written)
|
|
62
|
-
await docs.create({ sparse: true }); // create it with a sparse (SPLADE) index, before its first write
|
|
63
69
|
|
|
64
70
|
await conare.namespaces(); // [{ name, documents }]
|
|
65
71
|
await conare.namespaces({ prefix: "u7f3a9c-" }); // one user's namespaces
|
|
@@ -75,13 +81,12 @@ await docs.query("how do refunds work?", {
|
|
|
75
81
|
topK: 10, // 1-100, default 10
|
|
76
82
|
filter: { team: "support" }, // optional metadata filter
|
|
77
83
|
rerank: true, // default true
|
|
78
|
-
retrievers: ["vector", "keyword"], // default;
|
|
84
|
+
retrievers: ["vector", "keyword"], // default; one of them alone searches with it alone
|
|
79
85
|
});
|
|
80
86
|
```
|
|
81
87
|
|
|
82
88
|
Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what it
|
|
83
|
-
fuses: `"vector"` (the embedding model)
|
|
84
|
-
learned-sparse SPLADE model, in a namespace created with `create({ sparse: true })`).
|
|
89
|
+
fuses: `"vector"` (the embedding model) and `"keyword"` (BM25; alone, BM25 alone).
|
|
85
90
|
`score` is the reranker's when `reranked` is true, else the fused rank score of a result past the
|
|
86
91
|
rerank window (or of a query not reranked); the two scales do not compare.
|
|
87
92
|
|
|
@@ -107,14 +112,19 @@ There is no `$ne` or `$nin`: the API answers 400 `invalid_filter`.
|
|
|
107
112
|
|
|
108
113
|
```ts
|
|
109
114
|
await conare.embed(["some text"], { type: "query" }); // number[][]; type defaults to "document"
|
|
115
|
+
await conare.embed(["some text"], { outputDtype: "int8" }); // { values: Int8Array[], scales }; dequantize() gives floats
|
|
110
116
|
await conare.rerank("refund window", ["a", "b"], { topK: 1 }); // [{ index, score, document }], plus .unscored
|
|
111
117
|
```
|
|
112
118
|
|
|
119
|
+
`outputDtype: "int8"` returns each vector as int8 values plus one scale (vector ≈ values × scale, scale = max|x| / 127):
|
|
120
|
+
a quarter of the bytes. Cosine on the values alone equals cosine on the floats, so they can be stored and searched as
|
|
121
|
+
they are. On our embedder's real vectors this cost no measurable retrieval quality (nDCG@10 -0.00 [-0.10, +0.10] on 1M
|
|
122
|
+
chunks). There is no binary output: 1-bit vectors lost 4 to 7.5 nDCG@10 points there.
|
|
123
|
+
|
|
113
124
|
`rerank` takes 1-100 documents of 1-24,000 characters each (the query at most 8,192 characters, all
|
|
114
|
-
together at most 256,000); more than 100 is a 400 `invalid_request`.
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
index in `.unscored` and is not in the results; its score from another call would not compare.
|
|
125
|
+
together at most 256,000); more than 100 is a 400 `invalid_request`. A document not read before the
|
|
126
|
+
one-second budget ended, or whose read failed, is listed by index in `.unscored` and is not in the
|
|
127
|
+
results; its score from another call would not compare.
|
|
118
128
|
|
|
119
129
|
### Sources
|
|
120
130
|
|
|
@@ -133,10 +143,51 @@ await conare.sources.types(); // [{ type, name, logoUrl }]
|
|
|
133
143
|
await conare.sources.list(); // [Source]
|
|
134
144
|
await conare.sources.get(source.id); // { id, type, name, namespace, status, error, documents, lastSyncedAt, createdAt }
|
|
135
145
|
await conare.sources.sync(source.id); // sync now
|
|
146
|
+
await conare.sources.sync(source.id, { full: true }); // re-read everything (Gmail and apps Conare reads itself); Gmail's rows are billed again
|
|
147
|
+
await conare.sources.update(source.id, { syncIntervalSeconds: 3600 }); // every hour; null is automatic
|
|
136
148
|
await conare.sources.delete(source.id, { deleteDocuments: true });
|
|
137
149
|
```
|
|
138
150
|
|
|
139
|
-
`status` is `connecting`, `syncing`, `ready` or `error`.
|
|
151
|
+
`status` is `connecting`, `syncing`, `ready` or `error`. A source syncs on an automatic interval
|
|
152
|
+
picked from what each sync reads, or on one you set from 5 minutes to 30 days. `source.cost` holds
|
|
153
|
+
what an estimate of a month at any interval needs: the rows the last sync read, whether syncs read
|
|
154
|
+
only changes, and the prices.
|
|
155
|
+
|
|
156
|
+
### Custom sources
|
|
157
|
+
|
|
158
|
+
A custom source is a set of documents you push from your own system, keyed by your own ids.
|
|
159
|
+
Conare answers per document what each write did, keeps a deleted one out, and can mirror a whole
|
|
160
|
+
set: what a snapshot run never saw is deleted.
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
const src = await conare.sources.create({ type: "custom", namespace: "kb", name: "Help center" });
|
|
164
|
+
|
|
165
|
+
await conare.sources.documents.put(src.id, [
|
|
166
|
+
{ externalId: "article-12", text: "Refunds take 5 days.", seq: 1759698843000, tag: "etag-9" },
|
|
167
|
+
]); // [{ externalId, key, result, storedSeq?, code? }], 100 a call:
|
|
168
|
+
// created, updated, unchanged, stale (a lower seq), deleted, rejected
|
|
169
|
+
await conare.sources.documents.check(src.id, [{ externalId: "article-12", tag: "etag-9" }]); // { need, excluded }
|
|
170
|
+
for await (const d of conare.sources.documents.list(src.id)) {} // { externalId, key, tag, seq, user, version }
|
|
171
|
+
await conare.sources.documents.get(src.id, "article-12"); // with text and metadata, or null
|
|
172
|
+
await conare.sources.documents.delete(src.id, ["article-12"], { exclude: true }); // kept out until restored
|
|
173
|
+
await conare.sources.documents.restore(src.id, ["article-12"]);
|
|
174
|
+
|
|
175
|
+
// Mirror the whole set: push (or check, when unchanged) every document through a run, then complete it.
|
|
176
|
+
const run = await conare.runs.open(src.id, { expected: 2 });
|
|
177
|
+
await run.put([{ externalId: "a", text: "..." }]);
|
|
178
|
+
await run.check([{ externalId: "b", tag: "etag-1" }]);
|
|
179
|
+
const done = await run.complete(); // { state, sweep, counts: { seen, live, planned, deleted } }
|
|
180
|
+
// sweep "held": over 10% (and over 1,000) would go at once; a run 24 h later that agrees applies it.
|
|
181
|
+
|
|
182
|
+
await conare.imports.create(src.id, jsonl, { mode: "snapshot" }); // a JSON-lines file, up to 1 GiB: a Run
|
|
183
|
+
await conare.runs.get(runId); // follow any run
|
|
184
|
+
await conare.users.delete("tenant-7:u_42"); // everything of a user, in every namespace: a purge Run
|
|
185
|
+
await conare.users.deletePrefix("tenant-7:");
|
|
186
|
+
await conare.events.list({ cursor: "0", types: ["run.*"] }); // { data: [{ seq, type, runId, data }], nextCursor }
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`sources.list()` and `sources.get()` answer custom sources too, with `kind: "custom"`. These
|
|
190
|
+
calls send an `Idempotency-Key` when they create or delete something, so their retries are safe.
|
|
140
191
|
|
|
141
192
|
### Errors
|
|
142
193
|
|
|
@@ -179,32 +230,54 @@ const context = await user.query("how should we contact them?");
|
|
|
179
230
|
|
|
180
231
|
Keep the API key on your server. It can read and write every namespace in your organization.
|
|
181
232
|
|
|
182
|
-
##
|
|
183
|
-
|
|
184
|
-
Conare is also an MCP server at `https://api.conare.ai/mcp`, with tools to search, fetch, save
|
|
185
|
-
and delete documents and list namespaces. Clients that sign in over OAuth (claude.ai connectors,
|
|
186
|
-
ChatGPT) need only the URL; the rest take a key:
|
|
233
|
+
## The `conare` command: sync sessions and GitHub
|
|
187
234
|
|
|
188
|
-
|
|
235
|
+
The package also ships a command (the library never loads it). It runs under Node and Bun:
|
|
189
236
|
|
|
190
237
|
```bash
|
|
191
|
-
|
|
192
|
-
|
|
238
|
+
npx conare sync --key sk-conare-... # save the key to ~/.conare/sync.json, then sync
|
|
239
|
+
bunx conare sync # sync again: only new or changed sessions are sent
|
|
240
|
+
npx conare sync --dry-run # count what would upload
|
|
241
|
+
npx conare sync --install # sync now, then every 10 minutes in the background
|
|
242
|
+
npx conare sync status # the last background run; exits 1 if no success in 1 h or a transcript was missed
|
|
243
|
+
npx conare sync --uninstall # stop the background sync
|
|
244
|
+
npx conare sync github owner/repo # issues, PRs and markdown docs (GITHUB_TOKEN or gh auth)
|
|
193
245
|
```
|
|
194
246
|
|
|
195
|
-
|
|
247
|
+
**Sessions.** Each Claude Code or Codex session becomes one document in the namespace `sessions`:
|
|
248
|
+
a readable transcript with the prompts, the answers, one line per tool call, and the errors. Tool
|
|
249
|
+
output that succeeded, images and thinking are left out, and secrets (API keys, tokens, private
|
|
250
|
+
keys, passwords) are replaced with `[REDACTED:<kind>]` before anything is sent. Ids are
|
|
251
|
+
`claude:<session>`, `claude:<session>:agent:<agent>` for a subagent, and `codex:<rollout file
|
|
252
|
+
name>`; a session over 250 KB is split into `<id>:part:000001`, `:part:000002`, and so on (one
|
|
253
|
+
layout per session, never both). Metadata: `source` (`claude-code` or `codex`), `session_id`,
|
|
254
|
+
`agent_id`, `project`, `cwd`, `git_branch`, `started_at`, `date` (the last activity) and
|
|
255
|
+
`content_hash`.
|
|
196
256
|
|
|
197
|
-
```
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
"conare": {
|
|
201
|
-
"url": "https://api.conare.ai/mcp",
|
|
202
|
-
"headers": { "Authorization": "Bearer sk-conare-..." }
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
}
|
|
257
|
+
```ts
|
|
258
|
+
const sessions = conare.namespace("sessions");
|
|
259
|
+
await sessions.query("why did we drop the Redis cache?", { filter: { project: "shop" } });
|
|
206
260
|
```
|
|
207
261
|
|
|
262
|
+
It reads `~/.claude/projects` (or `$CLAUDE_CONFIG_DIR`) and `~/.codex/sessions` (or `$CODEX_HOME`).
|
|
263
|
+
The key comes from `--key`, else `CONARE_API_KEY`, else `~/.conare/sync.json`. What the server
|
|
264
|
+
already has is kept in `~/.conare/sync-state.json`, and one run at a time holds `~/.conare/sync.lock`.
|
|
265
|
+
`--install` copies the command to `~/.conare/sync/<version>/`, checks the copy file by file, runs
|
|
266
|
+
it once, and only then adds a launchd agent (`ai.conare.sync`) on macOS or a systemd user timer on
|
|
267
|
+
Linux. Every run adds a line to `~/.conare/sync.log` (uploaded, skipped and failed counts, duration).
|
|
268
|
+
With `--install --via <command>` the schedule runs the sync through that command, which supplies
|
|
269
|
+
`CONARE_API_KEY` (for example a secrets manager's wrapper such as `ops`), and no key is saved to disk.
|
|
270
|
+
Up to four batches upload at once.
|
|
271
|
+
|
|
272
|
+
**GitHub.** `conare sync github owner/repo` writes every issue and PR thread (body, comments and
|
|
273
|
+
review comments; bots other than `greptile-apps[bot]` and `claude[bot]` are left out) into
|
|
274
|
+
`<repo>-github` as `pr-<n>` / `issue-<n>`, with metadata `kind`, `repo`, `number`, `title`,
|
|
275
|
+
`state`, `author`, `date`, `updated_at`, `merged_at`, `labels` and `url`; and every markdown file on
|
|
276
|
+
the default branch into `<repo>-docs` (id: the path with `/` as `:`; metadata `kind: "doc"`,
|
|
277
|
+
`path`, `title`, `author`, `date`, `url`). Later runs read only threads updated since the last one
|
|
278
|
+
and files whose content changed; docs whose file was deleted are deleted. `--state <file>` sets
|
|
279
|
+
where that is kept (default `~/.conare/github-state.json`).
|
|
280
|
+
|
|
208
281
|
## Development
|
|
209
282
|
|
|
210
283
|
```bash
|
package/dist/cli/args.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Command line: `conare sync [sessions]`, `conare sync status`, `conare sync github <owner/repo>...`.
|
|
2
|
+
export const HELP = `Usage:
|
|
3
|
+
conare sync [options] Claude Code and Codex sessions -> namespace "sessions"
|
|
4
|
+
conare sync status the last sessions sync; exits 1 when its last success is over 1 h old or it missed transcripts
|
|
5
|
+
conare sync github <owner/repo>... [opts] issues, PRs and markdown docs -> "<repo>-github", "<repo>-docs"
|
|
6
|
+
|
|
7
|
+
Run it as npx conare … or bunx conare …. Only new or changed sessions, threads and docs are
|
|
8
|
+
sent; secrets in sessions are redacted first.
|
|
9
|
+
|
|
10
|
+
Options:
|
|
11
|
+
--dry-run count what would upload; upload nothing
|
|
12
|
+
--quiet print nothing on success
|
|
13
|
+
--install sessions: sync now, then every 10 minutes in the background
|
|
14
|
+
--uninstall sessions: stop the background sync
|
|
15
|
+
--via <command> with --install: the schedule runs \`<command> node … sync\`, which
|
|
16
|
+
supplies CONARE_API_KEY (e.g. --via ops); no key is saved to disk
|
|
17
|
+
--state <file> github: what was synced (default ~/.conare/github-state.json)
|
|
18
|
+
--key <key> save an API key (sk-conare-…) to ~/.conare/sync.json, then sync
|
|
19
|
+
-v, --version print the version
|
|
20
|
+
-h, --help show this help
|
|
21
|
+
|
|
22
|
+
Exit codes: 0 done; 1 error; 2 bad arguments; 3 API key refused; 4 incomplete (documents
|
|
23
|
+
refused, the API unreachable, or another sync running), tried again next run.
|
|
24
|
+
|
|
25
|
+
The key comes from --key, else CONARE_API_KEY, else ~/.conare/sync.json.
|
|
26
|
+
Create one at https://conare.ai/console/keys. GitHub: GITHUB_TOKEN, else \`gh auth token\`.
|
|
27
|
+
`;
|
|
28
|
+
const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
29
|
+
export function parseArgs(argv) {
|
|
30
|
+
const args = { help: false, version: false, command: "sessions", dryRun: false, quiet: false, install: false, uninstall: false, repos: [] };
|
|
31
|
+
const rest = [...argv];
|
|
32
|
+
const words = [];
|
|
33
|
+
while (rest.length > 0) {
|
|
34
|
+
const arg = rest.shift();
|
|
35
|
+
const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, undefined];
|
|
36
|
+
const value = () => {
|
|
37
|
+
const v = inline ?? rest.shift();
|
|
38
|
+
return v && !v.startsWith("-") ? v : undefined;
|
|
39
|
+
};
|
|
40
|
+
switch (flag) {
|
|
41
|
+
case "-h":
|
|
42
|
+
case "--help":
|
|
43
|
+
case "help":
|
|
44
|
+
args.help = true;
|
|
45
|
+
break;
|
|
46
|
+
case "-v":
|
|
47
|
+
case "--version":
|
|
48
|
+
args.version = true;
|
|
49
|
+
break;
|
|
50
|
+
case "--dry-run":
|
|
51
|
+
args.dryRun = true;
|
|
52
|
+
break;
|
|
53
|
+
case "--quiet":
|
|
54
|
+
args.quiet = true;
|
|
55
|
+
break;
|
|
56
|
+
case "--install":
|
|
57
|
+
args.install = true;
|
|
58
|
+
break;
|
|
59
|
+
case "--uninstall":
|
|
60
|
+
args.uninstall = true;
|
|
61
|
+
break;
|
|
62
|
+
case "--key": {
|
|
63
|
+
const key = value();
|
|
64
|
+
if (!key)
|
|
65
|
+
return { error: "--key needs a value: --key sk-conare-…" };
|
|
66
|
+
if (!key.startsWith("sk-conare-"))
|
|
67
|
+
return { error: "The key should start with sk-conare-." };
|
|
68
|
+
args.key = key;
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
case "--via": {
|
|
72
|
+
const via = value();
|
|
73
|
+
if (!via)
|
|
74
|
+
return { error: "--via needs a command: --via ops" };
|
|
75
|
+
args.via = via;
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
case "--state": {
|
|
79
|
+
const state = value();
|
|
80
|
+
if (!state)
|
|
81
|
+
return { error: "--state needs a file" };
|
|
82
|
+
args.state = state;
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
default:
|
|
86
|
+
if (flag.startsWith("-"))
|
|
87
|
+
return { error: `Unknown argument: ${arg}` };
|
|
88
|
+
words.push(arg);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (args.help || args.version)
|
|
92
|
+
return args;
|
|
93
|
+
const [command, sub, ...more] = words;
|
|
94
|
+
if (command === undefined)
|
|
95
|
+
return { ...args, help: true };
|
|
96
|
+
if (command !== "sync")
|
|
97
|
+
return { error: `Unknown command: ${command}` };
|
|
98
|
+
if (sub === undefined || sub === "sessions" || sub === "status") {
|
|
99
|
+
if (more.length > 0)
|
|
100
|
+
return { error: `Unknown argument: ${more[0]}` };
|
|
101
|
+
args.command = sub === "status" ? "status" : "sessions";
|
|
102
|
+
}
|
|
103
|
+
else if (sub === "github") {
|
|
104
|
+
if (more.length === 0)
|
|
105
|
+
return { error: "sync github needs a repository: conare sync github owner/repo" };
|
|
106
|
+
for (const repo of more)
|
|
107
|
+
if (!REPO.test(repo))
|
|
108
|
+
return { error: `Not a repository (owner/repo): ${repo}` };
|
|
109
|
+
// Namespaces are named after the repository alone (<name>-github, <name>-docs).
|
|
110
|
+
const byName = new Map();
|
|
111
|
+
for (const repo of more) {
|
|
112
|
+
const name = repo.slice(repo.indexOf("/") + 1).toLowerCase();
|
|
113
|
+
const other = byName.get(name);
|
|
114
|
+
if (other && other.toLowerCase() !== repo.toLowerCase())
|
|
115
|
+
return { error: `${other} and ${repo} would both write to ${name}-github and ${name}-docs; sync one of them.` };
|
|
116
|
+
byName.set(name, repo);
|
|
117
|
+
}
|
|
118
|
+
args.command = "github";
|
|
119
|
+
args.repos = more;
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
return { error: `Unknown argument: ${sub}` };
|
|
123
|
+
}
|
|
124
|
+
if (args.install && args.uninstall)
|
|
125
|
+
return { error: "Use --install or --uninstall, not both." };
|
|
126
|
+
if (args.via && !args.install)
|
|
127
|
+
return { error: "--via goes with --install." };
|
|
128
|
+
if ((args.install || args.uninstall) && args.command !== "sessions")
|
|
129
|
+
return { error: "--install and --uninstall schedule the sessions sync only." };
|
|
130
|
+
if (args.dryRun && (args.install || args.uninstall))
|
|
131
|
+
return { error: "--dry-run cannot be combined with --install or --uninstall." };
|
|
132
|
+
if (args.state !== undefined && args.command !== "github")
|
|
133
|
+
return { error: "--state is for sync github." };
|
|
134
|
+
if (args.command === "status" && (args.dryRun || args.key))
|
|
135
|
+
return { error: "sync status takes no options." };
|
|
136
|
+
return args;
|
|
137
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Where sync reads transcripts and keeps its own files, and the saved API key.
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
export function resolvePaths(env = process.env, home = homedir()) {
|
|
6
|
+
const dir = join(home, ".conare");
|
|
7
|
+
return {
|
|
8
|
+
dir,
|
|
9
|
+
keyFile: join(dir, "sync.json"),
|
|
10
|
+
stateFile: join(dir, "sync-state.json"),
|
|
11
|
+
lockFile: join(dir, "sync.lock"),
|
|
12
|
+
logFile: join(dir, "sync.log"),
|
|
13
|
+
statusFile: join(dir, "sync-status.json"),
|
|
14
|
+
githubStateFile: join(dir, "github-state.json"),
|
|
15
|
+
installRoot: join(dir, "sync"),
|
|
16
|
+
claudeDir: env.CLAUDE_CONFIG_DIR || join(home, ".claude"),
|
|
17
|
+
codexDir: env.CODEX_HOME || join(home, ".codex"),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function readSavedKey(keyFile) {
|
|
21
|
+
try {
|
|
22
|
+
const key = JSON.parse(readFileSync(keyFile, "utf8")).api_key;
|
|
23
|
+
return typeof key === "string" && key ? key : undefined;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function saveKey(keyFile, key) {
|
|
30
|
+
writePrivate(keyFile, `${JSON.stringify({ api_key: key }, null, 2)}\n`);
|
|
31
|
+
}
|
|
32
|
+
/** Atomic write readable only by the user (the directory too). */
|
|
33
|
+
export function writePrivate(path, content) {
|
|
34
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
35
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
36
|
+
writeFileSync(tmp, content, { mode: 0o600 });
|
|
37
|
+
chmodSync(tmp, 0o600); // mode applies only on create; a leftover tmp keeps its old one
|
|
38
|
+
renameSync(tmp, path);
|
|
39
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Transcript → the documents sent to the namespace "sessions". Ids, parts and metadata are
|
|
2
|
+
// the contract with the server (and with the migration of older history, which uses the
|
|
3
|
+
// same ids).
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { render } from "./render.js";
|
|
6
|
+
import { scrub } from "./scrub.js";
|
|
7
|
+
export const NAMESPACE = "sessions";
|
|
8
|
+
/** The API caps text at 256 KB; a part stays under this many UTF-8 bytes. */
|
|
9
|
+
export const PART_BYTES = 250_000;
|
|
10
|
+
const METADATA_VALUE_BYTES = 4096;
|
|
11
|
+
/** claude:<session>, claude:<session>:agent:<agent>, codex:<session>. */
|
|
12
|
+
export function baseId(t) {
|
|
13
|
+
const prefix = t.source === "codex" ? "codex" : "claude";
|
|
14
|
+
return `${prefix}:${idSegment(t.sessionId)}${t.agentId ? `:agent:${idSegment(t.agentId)}` : ""}`;
|
|
15
|
+
}
|
|
16
|
+
/** <base>:part:000001 for n = 1. */
|
|
17
|
+
export function partId(base, n) {
|
|
18
|
+
return `${base}:part:${String(n).padStart(6, "0")}`;
|
|
19
|
+
}
|
|
20
|
+
/** Ids allow [A-Za-z0-9._:-]; anything else in a file name becomes "-". */
|
|
21
|
+
function idSegment(value) {
|
|
22
|
+
return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 160);
|
|
23
|
+
}
|
|
24
|
+
/** The documents for one transcript: one, or numbered parts when the text is too large. */
|
|
25
|
+
export function toDocuments(t, project) {
|
|
26
|
+
const text = scrub(render(t, project));
|
|
27
|
+
const parts = splitText(text, PART_BYTES);
|
|
28
|
+
const base = baseId(t);
|
|
29
|
+
const shared = {};
|
|
30
|
+
// Metadata is scrubbed like the text: a path or branch name can hold a secret too.
|
|
31
|
+
const set = (key, value) => {
|
|
32
|
+
const clean = value && scrub(value);
|
|
33
|
+
if (clean && Buffer.byteLength(clean) <= METADATA_VALUE_BYTES)
|
|
34
|
+
shared[key] = clean;
|
|
35
|
+
};
|
|
36
|
+
set("source", t.source);
|
|
37
|
+
set("session_id", t.sessionId);
|
|
38
|
+
set("agent_id", t.agentId);
|
|
39
|
+
set("project", project);
|
|
40
|
+
set("cwd", t.cwd);
|
|
41
|
+
set("git_branch", t.branch);
|
|
42
|
+
set("started_at", t.startedAt);
|
|
43
|
+
set("date", t.endedAt ?? t.startedAt); // last activity: MCP shows it as the document's date and orders by it
|
|
44
|
+
return parts.map((part, i) => ({
|
|
45
|
+
id: parts.length > 1 ? partId(base, i + 1) : base,
|
|
46
|
+
text: part,
|
|
47
|
+
metadata: {
|
|
48
|
+
...shared,
|
|
49
|
+
...(parts.length > 1 ? { part: i + 1, parts: parts.length } : {}),
|
|
50
|
+
content_hash: sha256(part),
|
|
51
|
+
},
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
54
|
+
export function sha256(text) {
|
|
55
|
+
return createHash("sha256").update(text).digest("hex");
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Split text into pieces of at most maxBytes UTF-8 bytes whose concatenation is the text.
|
|
59
|
+
* A piece ends after a newline when one falls in the second half of the window; a line
|
|
60
|
+
* longer than that is cut at a character boundary.
|
|
61
|
+
*/
|
|
62
|
+
export function splitText(text, maxBytes) {
|
|
63
|
+
const buf = Buffer.from(text, "utf8");
|
|
64
|
+
if (buf.length <= maxBytes)
|
|
65
|
+
return [text];
|
|
66
|
+
const parts = [];
|
|
67
|
+
let start = 0;
|
|
68
|
+
while (start < buf.length) {
|
|
69
|
+
let end = Math.min(start + maxBytes, buf.length);
|
|
70
|
+
if (end < buf.length) {
|
|
71
|
+
const newline = buf.lastIndexOf(0x0a, end - 1);
|
|
72
|
+
if (newline >= start + maxBytes / 2)
|
|
73
|
+
end = newline + 1;
|
|
74
|
+
else
|
|
75
|
+
while (end > start && (buf[end] & 0xc0) === 0x80)
|
|
76
|
+
end--; // not inside a character
|
|
77
|
+
}
|
|
78
|
+
parts.push(buf.toString("utf8", start, end));
|
|
79
|
+
start = end;
|
|
80
|
+
}
|
|
81
|
+
return parts;
|
|
82
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// A small GitHub client: REST with pagination and GraphQL, on fetch. Retries 5xx, 429 and
|
|
2
|
+
// rate-limit 403s, waiting what GitHub asks (Retry-After, or until X-RateLimit-Reset) up to
|
|
3
|
+
// MAX_WAIT_MS; anything else throws a GitHubError.
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
const API = "https://api.github.com";
|
|
6
|
+
const ATTEMPTS = 5;
|
|
7
|
+
const MAX_WAIT_MS = 15 * 60 * 1000;
|
|
8
|
+
/**
|
|
9
|
+
* Bounds one request, body included: a stall before the response is retried, one while reading
|
|
10
|
+
* the body ends the run; either way a hung connection never holds the run (and its lock) forever.
|
|
11
|
+
*/
|
|
12
|
+
export const REQUEST_TIMEOUT_MS = 120_000;
|
|
13
|
+
export class GitHubError extends Error {
|
|
14
|
+
status;
|
|
15
|
+
constructor(status, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.name = "GitHubError";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export class GitHub {
|
|
22
|
+
token;
|
|
23
|
+
/** Requests sent, retries included. */
|
|
24
|
+
calls = 0;
|
|
25
|
+
fetchFn;
|
|
26
|
+
base;
|
|
27
|
+
graphqlURL;
|
|
28
|
+
sleep;
|
|
29
|
+
timeoutMs;
|
|
30
|
+
constructor(token, options = {}) {
|
|
31
|
+
this.token = token;
|
|
32
|
+
this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
|
|
33
|
+
this.base = (options.baseURL ?? API).replace(/\/+$/, "");
|
|
34
|
+
this.graphqlURL = options.graphqlURL ?? `${this.base}/graphql`;
|
|
35
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
36
|
+
this.timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
37
|
+
}
|
|
38
|
+
async send(url, init = {}) {
|
|
39
|
+
for (let attempt = 1;; attempt++) {
|
|
40
|
+
this.calls++;
|
|
41
|
+
let res;
|
|
42
|
+
let failure;
|
|
43
|
+
try {
|
|
44
|
+
res = await this.fetchFn(url, {
|
|
45
|
+
...init,
|
|
46
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
47
|
+
headers: {
|
|
48
|
+
Accept: "application/vnd.github+json",
|
|
49
|
+
Authorization: `Bearer ${this.token}`,
|
|
50
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
51
|
+
"User-Agent": "conare-cli",
|
|
52
|
+
...init.headers,
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
if (res.ok)
|
|
56
|
+
return res;
|
|
57
|
+
failure = `${res.status} ${(await res.text()).slice(0, 300)}`;
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
failure = String(err);
|
|
61
|
+
}
|
|
62
|
+
const wait = res ? retryWait(res, attempt) : 2 ** attempt * 1000;
|
|
63
|
+
if (wait === undefined || attempt >= ATTEMPTS)
|
|
64
|
+
throw new GitHubError(res?.status ?? 0, `GitHub ${init.method ?? "GET"} ${url.replace(this.base, "")}: ${failure}`);
|
|
65
|
+
await this.sleep(wait);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** GET a REST path (or a full URL) as JSON. */
|
|
69
|
+
async json(path) {
|
|
70
|
+
const res = await this.send(path.startsWith("http") ? path : this.base + path);
|
|
71
|
+
return (await res.json());
|
|
72
|
+
}
|
|
73
|
+
/** Every item of a paginated REST list, following the Link header. */
|
|
74
|
+
async *paginate(path) {
|
|
75
|
+
let url = this.base + path;
|
|
76
|
+
while (url) {
|
|
77
|
+
const res = await this.send(url);
|
|
78
|
+
for (const item of (await res.json()))
|
|
79
|
+
yield item;
|
|
80
|
+
url = nextLink(res.headers.get("link"));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async all(path) {
|
|
84
|
+
const out = [];
|
|
85
|
+
for await (const item of this.paginate(path))
|
|
86
|
+
out.push(item);
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
async graphql(query, variables) {
|
|
90
|
+
const res = await this.send(this.graphqlURL, {
|
|
91
|
+
method: "POST",
|
|
92
|
+
body: JSON.stringify({ query, variables }),
|
|
93
|
+
headers: { "Content-Type": "application/json" },
|
|
94
|
+
});
|
|
95
|
+
const body = (await res.json());
|
|
96
|
+
if (body.errors?.length || !body.data) {
|
|
97
|
+
throw new GitHubError(res.status, `GitHub GraphQL: ${(body.errors ?? []).map((e) => e.message).join("; ") || "no data"}`);
|
|
98
|
+
}
|
|
99
|
+
return body.data;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** How long to wait before retrying this response, or undefined when retrying cannot help. */
|
|
103
|
+
export function retryWait(res, attempt, now = Date.now()) {
|
|
104
|
+
const after = Number(res.headers.get("retry-after"));
|
|
105
|
+
const limited = res.status === 429 || (res.status === 403 && (res.headers.get("x-ratelimit-remaining") === "0" || res.headers.has("retry-after")));
|
|
106
|
+
if (limited) {
|
|
107
|
+
let wait = Number.isFinite(after) && after > 0 ? after * 1000 : undefined;
|
|
108
|
+
const reset = Number(res.headers.get("x-ratelimit-reset"));
|
|
109
|
+
if (wait === undefined && Number.isFinite(reset) && reset > 0)
|
|
110
|
+
wait = reset * 1000 - now + 1000;
|
|
111
|
+
wait ??= 60_000;
|
|
112
|
+
return wait <= MAX_WAIT_MS ? Math.max(wait, 1000) : undefined;
|
|
113
|
+
}
|
|
114
|
+
if (res.status >= 500)
|
|
115
|
+
return 2 ** attempt * 1000;
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
export function nextLink(link) {
|
|
119
|
+
if (!link)
|
|
120
|
+
return undefined;
|
|
121
|
+
for (const part of link.split(",")) {
|
|
122
|
+
const m = /<([^>]+)>\s*;\s*rel="next"/.exec(part);
|
|
123
|
+
if (m)
|
|
124
|
+
return m[1];
|
|
125
|
+
}
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
/** GITHUB_TOKEN, else GH_TOKEN, else what the gh CLI is logged in with. */
|
|
129
|
+
export function githubToken(env = process.env) {
|
|
130
|
+
const fromEnv = env.GITHUB_TOKEN || env.GH_TOKEN;
|
|
131
|
+
if (fromEnv)
|
|
132
|
+
return fromEnv;
|
|
133
|
+
try {
|
|
134
|
+
return execFileSync("gh", ["auth", "token"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || undefined;
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
}
|