conare 0.7.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,217 @@
1
+ # conare
2
+
3
+ TypeScript client for [Conare](https://conare.ai): add documents, query them, connect apps.
4
+ No dependencies. Works on Node 18+, Bun, Deno and edge runtimes.
5
+
6
+ ## Quickstart
7
+
8
+ ```bash
9
+ npm install conare
10
+ export CONARE_API_KEY=sk-conare-... # conare.ai/console/keys
11
+ ```
12
+
13
+ ```ts
14
+ import { Conare } from "conare";
15
+
16
+ const conare = new Conare();
17
+ const docs = conare.namespace("docs");
18
+
19
+ await docs.add({ id: "refunds", text: "Refunds are available for 30 days.", metadata: { team: "support" } });
20
+
21
+ const results = await docs.query("how do refunds work?", { topK: 5 });
22
+ // [{ id: "refunds", text: "Refunds are available for 30 days.", score: 0.91, metadata: { team: "support" } }]
23
+ ```
24
+
25
+ A namespace is created by its first write. Writing the same id again replaces the document.
26
+
27
+ ## Reference
28
+
29
+ ### Client
30
+
31
+ ```ts
32
+ new Conare() // CONARE_API_KEY from the environment
33
+ new Conare({ apiKey, baseURL, timeout: 60_000, maxRetries: 2 })
34
+ ```
35
+
36
+ Every method also takes `{ signal, timeout }` as its last option.
37
+
38
+ ### Namespaces and documents
39
+
40
+ ```ts
41
+ const docs = conare.namespace("docs");
42
+
43
+ await docs.add({ id, text, metadata }); // one document
44
+ await docs.add([...]); // or many; sent 100 at a time. Returns the ids.
45
+ await docs.get("refunds"); // { id, text, metadata, updatedAt } or null
46
+ for await (const doc of docs.list()) {} // every document, page by page ({ limit } per page: 1-100, default 50)
47
+ await docs.delete("refunds"); // 404 document_not_found if it does not exist
48
+ await docs.drop(); // delete the namespace and its documents (also succeeds if it is empty)
49
+
50
+ await conare.namespaces(); // [{ name, documents }]
51
+ ```
52
+
53
+ Namespace names: 1-64 characters of `a-z 0-9 _ -`. Ids: up to 256 characters of
54
+ `A-Z a-z 0-9 . _ : -`. Metadata values are strings, numbers, booleans or arrays of strings.
55
+
56
+ ### Query
57
+
58
+ ```ts
59
+ await docs.query("how do refunds work?", {
60
+ topK: 10, // 1-100, default 10
61
+ filter: { team: "support" }, // optional metadata filter
62
+ rerank: true, // default true
63
+ });
64
+ ```
65
+
66
+ Hybrid search (vector and keyword), reranked. One result per document: its best passage.
67
+
68
+ Filters match metadata values exactly: `{ key: value }` means equals (or, for an array value,
69
+ contains). Operators: `$eq` and `$in`. Combine with `$and` and `$or`:
70
+
71
+ ```ts
72
+ { $or: [{ team: "support" }, { year: { $in: [2024, 2025] } }] }
73
+ { $and: [{ lang: { $in: ["en", "de"] } }, { draft: false }] }
74
+ ```
75
+
76
+ There is no `$ne`, `$nin` or range operator (`$gt $gte $lt $lte`): the API answers 400
77
+ `invalid_filter`. Store a value you want to filter on as its own metadata key instead.
78
+
79
+ ### Embed and rerank
80
+
81
+ ```ts
82
+ await conare.embed(["some text"], { type: "query" }); // number[][]; type defaults to "document"
83
+ await conare.rerank("refund window", ["a", "b"], { topK: 1 }); // [{ index, score, document }]
84
+ ```
85
+
86
+ ### Sources
87
+
88
+ Connect an app such as HubSpot or Gmail. It keeps syncing into one namespace, and each record
89
+ becomes a document. `sources.types()` lists the apps you can connect.
90
+
91
+ ```ts
92
+ const { source, connectUrl } = await conare.sources.connect({
93
+ type: "hubspot",
94
+ namespace: "crm",
95
+ redirectUrl: "https://yourapp.com/settings",
96
+ });
97
+ // Send the app owner to connectUrl. They sign in and come back to redirectUrl.
98
+
99
+ await conare.sources.types(); // [{ type, name, logoUrl }]
100
+ await conare.sources.list(); // [Source]
101
+ await conare.sources.get(source.id); // { id, type, name, namespace, status, error, documents, lastSyncedAt, createdAt }
102
+ await conare.sources.sync(source.id); // sync now
103
+ await conare.sources.delete(source.id, { deleteDocuments: true });
104
+ ```
105
+
106
+ `status` is `connecting`, `syncing`, `ready` or `error`.
107
+
108
+ ### Errors
109
+
110
+ Every failure is a `ConareError` with `status`, `code`, `message` and `requestId`
111
+ (`status` is 0 when no response arrived: `timeout`, `connection_error`). 429, 5xx and network
112
+ errors are retried twice with backoff, honouring `Retry-After`. `sources.connect()` is retried only
113
+ on 429 and 503, and `add()` gives every document without an id one of its own first, so a retry
114
+ never creates anything twice.
115
+
116
+ ```ts
117
+ import { ConareError } from "conare";
118
+
119
+ try {
120
+ await docs.add({ text: "" });
121
+ } catch (err) {
122
+ if (err instanceof ConareError) console.log(err.status, err.code, err.requestId);
123
+ }
124
+ ```
125
+
126
+ ## One namespace per user
127
+
128
+ To give each user of your app their own searchable data, use one namespace per user and connect
129
+ their apps into it:
130
+
131
+ ```ts
132
+ const user = conare.namespace(`user-${userId}`);
133
+ await user.add({ id: "note-1", text: "Prefers email over phone." });
134
+
135
+ const { connectUrl } = await conare.sources.connect({
136
+ type: "gmail",
137
+ namespace: `user-${userId}`,
138
+ redirectUrl: "https://yourapp.com/settings/connections",
139
+ });
140
+ // Redirect the user to connectUrl. Their mail syncs into their namespace only.
141
+
142
+ const context = await user.query("how should we contact them?");
143
+ ```
144
+
145
+ Keep the API key on your server. It can read and write every namespace in your organization.
146
+
147
+ ## MCP
148
+
149
+ Conare is also an MCP server at `https://api.conare.ai/mcp`, with tools to search, fetch, save
150
+ and delete documents and list namespaces.
151
+
152
+ Claude Code:
153
+
154
+ ```bash
155
+ claude mcp add --transport http conare https://api.conare.ai/mcp \
156
+ --header "Authorization: Bearer $CONARE_API_KEY"
157
+ ```
158
+
159
+ Cursor (`~/.cursor/mcp.json`):
160
+
161
+ ```json
162
+ {
163
+ "mcpServers": {
164
+ "conare": {
165
+ "url": "https://api.conare.ai/mcp",
166
+ "headers": { "Authorization": "Bearer sk-conare-..." }
167
+ }
168
+ }
169
+ }
170
+ ```
171
+
172
+ ## Sync Claude Code and Codex sessions
173
+
174
+ The package also ships a `conare` command that uploads your local Claude Code and Codex sessions,
175
+ so your agents can search what you worked on before.
176
+
177
+ ```bash
178
+ npx conare sync --key sk-conare-... # save the key to ~/.conare/sync.json, then sync
179
+ npx conare sync # sync again: only new or changed sessions are sent
180
+ npx conare sync --dry-run # list what would upload
181
+ npx conare sync --install # sync now, then every 10 minutes in the background
182
+ npx conare sync --uninstall # stop the background sync
183
+ ```
184
+
185
+ Each session becomes one document in the namespace `sessions`: a readable transcript with the
186
+ prompts, the answers, one line per tool call, and the errors. Tool output that succeeded, images
187
+ and thinking are left out, and secrets (API keys, tokens, private keys, passwords) are replaced
188
+ with `[REDACTED:<kind>]` before anything is sent. Ids are `claude:<session>`,
189
+ `claude:<session>:agent:<agent>` for a subagent, and `codex:<session>`; a session over 250 KB is
190
+ split into `<id>:part:000001`, `:part:000002`, and so on. Metadata: `source` (`claude-code` or
191
+ `codex`), `session_id`, `agent_id`, `project`, `cwd`, `git_branch`, `started_at`, `date` (the
192
+ last activity) and `content_hash`.
193
+
194
+ ```ts
195
+ const sessions = conare.namespace("sessions");
196
+ await sessions.query("why did we drop the Redis cache?", { filter: { project: "shop" } });
197
+ ```
198
+
199
+ It reads `~/.claude/projects` (or `$CLAUDE_CONFIG_DIR`) and `~/.codex/sessions` (or `$CODEX_HOME`).
200
+ The key comes from `CONARE_API_KEY`, else `~/.conare/sync.json`. `--install` copies the command to
201
+ `~/.conare/sync/` and adds a launchd agent on macOS or a systemd user timer on Linux; it logs to
202
+ `~/.conare/sync.log`.
203
+
204
+ ## Development
205
+
206
+ ```bash
207
+ bun install
208
+ bun run build
209
+ bun test # local fake API
210
+ CONARE_API_KEY=sk-conare-... bun test # also runs test/live.test.ts against the real API
211
+ ```
212
+
213
+ Releases: push a tag `sdk-v<version>` matching `package.json`; CI tests and publishes to npm.
214
+
215
+ ## Versions
216
+
217
+ 0.8.0 is the first release of this client. Versions of `conare` before it (0.7.x and older) were the retired memory CLI.
@@ -0,0 +1,69 @@
1
+ // Command line: `conare sync [flags]` and `conare --help`.
2
+ export const HELP = `Usage: npx conare sync [options]
3
+
4
+ Uploads your Claude Code and Codex sessions to Conare, one document per session in the
5
+ namespace "sessions". Only new or changed sessions are sent. Secrets are redacted first.
6
+
7
+ Options:
8
+ --dry-run list what would upload; upload nothing
9
+ --quiet print nothing on success
10
+ --install sync now, then every 10 minutes in the background
11
+ --uninstall stop the background sync
12
+ --key <key> save an API key (sk-conare-…) to ~/.conare/sync.json, then sync
13
+ -h, --help show this help
14
+
15
+ The key comes from CONARE_API_KEY, else ~/.conare/sync.json.
16
+ Create one at https://conare.ai/console/keys.
17
+ `;
18
+ export function parseArgs(argv) {
19
+ const args = { help: false, dryRun: false, quiet: false, install: false, uninstall: false };
20
+ const rest = [...argv];
21
+ let command;
22
+ while (rest.length > 0) {
23
+ const arg = rest.shift();
24
+ const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, undefined];
25
+ switch (flag) {
26
+ case "-h":
27
+ case "--help":
28
+ case "help":
29
+ args.help = true;
30
+ break;
31
+ case "--dry-run":
32
+ args.dryRun = true;
33
+ break;
34
+ case "--quiet":
35
+ args.quiet = true;
36
+ break;
37
+ case "--install":
38
+ args.install = true;
39
+ break;
40
+ case "--uninstall":
41
+ args.uninstall = true;
42
+ break;
43
+ case "--key": {
44
+ const key = inline ?? rest.shift();
45
+ if (!key || key.startsWith("-"))
46
+ return { error: "--key needs a value: --key sk-conare-…" };
47
+ if (!key.startsWith("sk-conare-"))
48
+ return { error: "The key should start with sk-conare-." };
49
+ args.key = key;
50
+ break;
51
+ }
52
+ default:
53
+ if (flag.startsWith("-") || command !== undefined)
54
+ return { error: `Unknown argument: ${arg}` };
55
+ command = arg;
56
+ }
57
+ }
58
+ if (args.help)
59
+ return args;
60
+ if (command === undefined)
61
+ return { ...args, help: true };
62
+ if (command !== "sync")
63
+ return { error: `Unknown command: ${command}` };
64
+ if (args.install && args.uninstall)
65
+ return { error: "Use --install or --uninstall, not both." };
66
+ if (args.dryRun && (args.install || args.uninstall))
67
+ return { error: "--dry-run cannot be combined with --install or --uninstall." };
68
+ return args;
69
+ }
@@ -0,0 +1,37 @@
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
+ installRoot: join(dir, "sync"),
14
+ claudeDir: env.CLAUDE_CONFIG_DIR || join(home, ".claude"),
15
+ codexDir: env.CODEX_HOME || join(home, ".codex"),
16
+ };
17
+ }
18
+ export function readSavedKey(keyFile) {
19
+ try {
20
+ const key = JSON.parse(readFileSync(keyFile, "utf8")).api_key;
21
+ return typeof key === "string" && key ? key : undefined;
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ export function saveKey(keyFile, key) {
28
+ writePrivate(keyFile, `${JSON.stringify({ api_key: key }, null, 2)}\n`);
29
+ }
30
+ /** Atomic write readable only by the user (the directory too). */
31
+ export function writePrivate(path, content) {
32
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
33
+ const tmp = `${path}.${process.pid}.tmp`;
34
+ writeFileSync(tmp, content, { mode: 0o600 });
35
+ chmodSync(tmp, 0o600); // mode applies only on create; a leftover tmp keeps its old one
36
+ renameSync(tmp, path);
37
+ }
@@ -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,127 @@
1
+ #!/usr/bin/env node
2
+ // The conare command. `conare sync` uploads Claude Code and Codex sessions through the SDK's
3
+ // own client. Node built-ins only; the library entry never imports this directory.
4
+ import { rmSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { fileURLToPath } from "node:url";
7
+ import { Conare, ConareError, VERSION } from "../index.js";
8
+ import { HELP, parseArgs } from "./args.js";
9
+ import { readSavedKey, resolvePaths, saveKey } from "./config.js";
10
+ import { PASSED_ENV, installCopy, installSchedule, pruneVersions, uninstallSchedule } from "./schedule.js";
11
+ import { accountOf, acquireLock } from "./state.js";
12
+ import { findTranscripts, formatBytes, runSync } from "./sync.js";
13
+ const MAX_RETRIES = 4;
14
+ /** Exit code for a refused key; --install does not schedule a sync that cannot succeed. */
15
+ const AUTH_FAILED = 3;
16
+ async function main(argv) {
17
+ const args = parseArgs(argv);
18
+ if ("error" in args) {
19
+ process.stderr.write(`${args.error}\n\n${HELP}`);
20
+ return 2;
21
+ }
22
+ if (args.help) {
23
+ process.stdout.write(HELP);
24
+ return 0;
25
+ }
26
+ const paths = resolvePaths();
27
+ const say = (line) => {
28
+ if (!args.quiet)
29
+ console.log(line);
30
+ };
31
+ // Errors reach the log when run by the schedule, so they carry a time there.
32
+ const fail = (line) => console.error(args.quiet ? `${new Date().toISOString()} ${line}` : line);
33
+ if (args.key) {
34
+ saveKey(paths.keyFile, args.key);
35
+ say(`Saved the key to ${tilde(paths.keyFile)}.`);
36
+ }
37
+ if (args.uninstall) {
38
+ const removed = uninstallSchedule({ platform: process.platform });
39
+ rmSync(paths.installRoot, { recursive: true, force: true });
40
+ say(removed ? "Removed the background sync." : "No background sync was installed.");
41
+ return 0;
42
+ }
43
+ const envKey = process.env.CONARE_API_KEY || undefined;
44
+ const apiKey = args.key ?? envKey ?? readSavedKey(paths.keyFile);
45
+ if (!apiKey && !args.dryRun) {
46
+ fail("No API key. Create one at https://conare.ai/console/keys, then run:\n npx conare sync --key sk-conare-…");
47
+ return 1;
48
+ }
49
+ if (args.install && !args.key && envKey && readSavedKey(paths.keyFile) !== envKey) {
50
+ // The schedule does not see this shell's environment; it reads the saved key.
51
+ saveKey(paths.keyFile, envKey);
52
+ say(`Saved the key from CONARE_API_KEY to ${tilde(paths.keyFile)} for the background sync.`);
53
+ }
54
+ if (args.dryRun)
55
+ return syncOnce(args, paths, apiKey, say, fail); // writes nothing: no lock
56
+ const release = acquireLock(paths.lockFile);
57
+ if (!release) {
58
+ if (!args.quiet)
59
+ fail("Another sync is running.");
60
+ return args.quiet ? 0 : 1;
61
+ }
62
+ let code;
63
+ try {
64
+ code = await syncOnce(args, paths, apiKey, say, fail);
65
+ }
66
+ finally {
67
+ release();
68
+ }
69
+ if (args.install) {
70
+ if (code === AUTH_FAILED)
71
+ return code;
72
+ const script = installCopy(fileURLToPath(new URL("..", import.meta.url)), paths.installRoot, VERSION);
73
+ const env = {};
74
+ for (const name of PASSED_ENV)
75
+ if (process.env[name])
76
+ env[name] = process.env[name];
77
+ const what = installSchedule({ node: process.execPath, script, logFile: paths.logFile, env }, { platform: process.platform });
78
+ pruneVersions(paths.installRoot, VERSION); // only now: a failed install keeps the old schedule's script
79
+ say(`Installed: sync every 10 minutes (${what}).\nLog: ${tilde(paths.logFile)}. Stop it with: npx conare sync --uninstall`);
80
+ }
81
+ return code;
82
+ }
83
+ async function syncOnce(args, paths, apiKey, say, fail) {
84
+ const client = apiKey ? new Conare({ apiKey, maxRetries: MAX_RETRIES }) : undefined;
85
+ const files = findTranscripts(paths);
86
+ say(`Found ${files.length} transcripts.`);
87
+ try {
88
+ const report = await runSync({
89
+ files,
90
+ stateFile: paths.stateFile,
91
+ account: client ? accountOf(client.baseURL, apiKey) : "",
92
+ client: args.dryRun ? undefined : client,
93
+ log: say,
94
+ });
95
+ if (args.dryRun) {
96
+ for (const p of report.planned)
97
+ say(` ${p.id} ${formatBytes(p.bytes)}`);
98
+ say(`Would upload ${report.documents} documents from ${report.sessions} sessions (${formatBytes(report.bytes)}). ${report.unchanged} unchanged.`);
99
+ return 0;
100
+ }
101
+ for (const r of report.rejected)
102
+ fail(`Not accepted, tried again next run: ${r.id}: ${r.message}`);
103
+ say(report.documents > 0 || report.deleted > 0
104
+ ? `Synced ${report.sessions} sessions: ${report.documents} documents, ${formatBytes(report.bytes)}. ${report.unchanged} unchanged.`
105
+ : `Up to date: ${report.unchanged} sessions.`);
106
+ return report.rejected.length > 0 ? 1 : 0;
107
+ }
108
+ catch (err) {
109
+ if (err instanceof ConareError && (err.status === 401 || err.status === 403)) {
110
+ fail(`The API key was refused (${err.status} ${err.code}). Save a valid one: npx conare sync --key sk-conare-…`);
111
+ return AUTH_FAILED;
112
+ }
113
+ const detail = err instanceof ConareError ? `${err.message} (${err.status || err.code}${err.requestId ? `, request ${err.requestId}` : ""})` : String(err);
114
+ fail(`Sync stopped: ${detail}. What was uploaded is saved; the rest is tried next run.`);
115
+ return 1;
116
+ }
117
+ }
118
+ function tilde(path) {
119
+ const home = homedir();
120
+ return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
121
+ }
122
+ main(process.argv.slice(2)).then((code) => {
123
+ process.exitCode = code;
124
+ }, (err) => {
125
+ console.error(err instanceof Error ? err.message : String(err));
126
+ process.exitCode = 1;
127
+ });
@@ -0,0 +1,61 @@
1
+ // The project a session worked in: the name of its git repository, else its directory.
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname } from "node:path";
5
+ const cache = new Map();
6
+ /**
7
+ * "conare" for /home/me/conare/sdk, and also for a linked worktree of that repository
8
+ * (/home/me/conare/.claude/worktrees/agent-1, whose .git file points into conare/.git).
9
+ * Falls back to the directory's own name when no repository is found (or it was deleted).
10
+ */
11
+ export function projectName(cwd) {
12
+ if (!cwd)
13
+ return undefined;
14
+ if (!cache.has(cwd))
15
+ cache.set(cwd, resolve(cwd));
16
+ return cache.get(cwd);
17
+ }
18
+ function resolve(cwd) {
19
+ const path = slashes(cwd).replace(/(.)\/+$/, "$1");
20
+ const home = slashes(homedir());
21
+ // The home directory itself is never the project (a dotfiles repo would claim everything).
22
+ for (let dir = path; dir !== home;) {
23
+ const found = repoRoot(dir);
24
+ if (found)
25
+ return name(found);
26
+ const parent = slashes(dirname(dir));
27
+ if (parent === dir)
28
+ break;
29
+ dir = parent;
30
+ }
31
+ // Claude Code puts agent worktrees at <repo>/.claude/worktrees/<name>.
32
+ const at = path.indexOf("/.claude/worktrees/");
33
+ return name(at > 0 ? path.slice(0, at) : path);
34
+ }
35
+ /** dir when it holds a repository; for a linked worktree, the main checkout. */
36
+ function repoRoot(dir) {
37
+ const git = `${dir === "/" ? "" : dir}/.git`;
38
+ try {
39
+ if (statSync(git).isDirectory())
40
+ return dir;
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ // A .git file: "gitdir: /repo/.git/worktrees/<name>" for a worktree. A submodule's
46
+ // points into the superproject's .git/modules and is a repository of its own.
47
+ try {
48
+ const gitdir = slashes(/^gitdir:\s*(.+)$/m.exec(readFileSync(git, "utf8"))?.[1]?.trim() ?? "");
49
+ const at = gitdir.indexOf("/.git/worktrees/");
50
+ return at > 0 ? gitdir.slice(0, at) : dir;
51
+ }
52
+ catch {
53
+ return dir;
54
+ }
55
+ }
56
+ function slashes(path) {
57
+ return path.replace(/\\/g, "/");
58
+ }
59
+ function name(dir) {
60
+ return dir.split("/").filter(Boolean).pop();
61
+ }
@@ -0,0 +1,69 @@
1
+ // Transcript → readable text: a short header, then the turns under role lines ("[User · …]",
2
+ // "[Assistant]"), with tool calls as one line each ("→ $ bun test") and kept tool output
3
+ // indented under the call.
4
+ /** "2026-09-30 12:45 UTC" from an RFC 3339 string. */
5
+ export function displayTime(iso) {
6
+ return iso ? `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC` : undefined;
7
+ }
8
+ export function renderHeader(t, project) {
9
+ const lines = [`# ${t.agent}`];
10
+ const add = (label, value) => {
11
+ if (value)
12
+ lines.push(`${label}: ${value}`);
13
+ };
14
+ add("Title", t.title?.replace(/\s+/g, " ").trim());
15
+ add("Project", project);
16
+ add("Directory", t.cwd);
17
+ add("Branch", t.branch);
18
+ add("Session", t.sessionId);
19
+ add("Agent", t.agentId);
20
+ add("Started", displayTime(t.startedAt));
21
+ add("Ended", displayTime(t.endedAt));
22
+ return lines.join("\n");
23
+ }
24
+ /** The whole document text. Consecutive messages of one role share a heading. */
25
+ export function render(t, project) {
26
+ const blocks = [renderHeader(t, project)];
27
+ let role;
28
+ let lastWasLine = false;
29
+ for (const m of t.messages) {
30
+ if (m.role !== role || m.time) {
31
+ blocks.push(heading(m));
32
+ role = m.role;
33
+ lastWasLine = false;
34
+ }
35
+ for (const part of m.parts) {
36
+ const line = part.type !== "text";
37
+ const text = renderPart(part);
38
+ // Tool lines, outputs and events stack without blank lines between them.
39
+ if (line && lastWasLine)
40
+ blocks[blocks.length - 1] += `\n${text}`;
41
+ else
42
+ blocks.push(text);
43
+ lastWasLine = line;
44
+ }
45
+ }
46
+ return `${blocks.join("\n\n")}\n`;
47
+ }
48
+ // "[User · 2026-09-30 12:45 UTC]": agents write markdown headings of their own, so a role
49
+ // line has a shape of its own.
50
+ function heading(m) {
51
+ const time = displayTime(m.time);
52
+ return `[${m.role}${time ? ` · ${time}` : ""}]`;
53
+ }
54
+ function renderPart(part) {
55
+ switch (part.type) {
56
+ case "text":
57
+ return part.text;
58
+ case "tool":
59
+ return `→ ${indent(part.text, " ")}`;
60
+ case "output":
61
+ return ` ${part.error ? "✗" : "←"} ${indent(part.text, " ")}`;
62
+ case "event":
63
+ return `· ${part.text}`;
64
+ }
65
+ }
66
+ /** Continuation lines of a multi-line value, indented under its first line. */
67
+ function indent(text, pad) {
68
+ return text.replace(/\n/g, `\n${pad}`);
69
+ }