conare 0.9.0 → 0.10.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 CHANGED
@@ -169,38 +169,6 @@ Cursor (`~/.cursor/mcp.json`):
169
169
  }
170
170
  ```
171
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
172
  ## Development
205
173
 
206
174
  ```bash
@@ -214,4 +182,4 @@ Releases: push a tag `sdk-v<version>` matching `package.json`; CI tests and publ
214
182
 
215
183
  ## Versions
216
184
 
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.
185
+ 0.8.0 is the first release of this client. Versions of `conare` before it (0.7.x and older) are the retired memory CLI.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.9.0";
1
+ export declare const VERSION = "0.10.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.9.0";
2
+ export const VERSION = "0.10.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  // ---- Errors ----------------------------------------------------------------
@@ -36,7 +36,12 @@ export class Conare {
36
36
  throw new ConareError(0, "missing_api_key", "Pass { apiKey } or set CONARE_API_KEY.");
37
37
  }
38
38
  this.apiKey = apiKey;
39
- this.baseURL = (options.baseURL ?? env("CONARE_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
39
+ const baseURL = options.baseURL ?? env("CONARE_BASE_URL") ?? DEFAULT_BASE_URL;
40
+ let end = baseURL.length;
41
+ // A loop, not .replace(/\/+$/, ""): that regex is quadratic on a long run of "/" (3.8 s at 100k).
42
+ while (end > 0 && baseURL[end - 1] === "/")
43
+ end--;
44
+ this.baseURL = baseURL.slice(0, end);
40
45
  this.timeout = options.timeout ?? 60_000;
41
46
  this.maxRetries = options.maxRetries ?? 2;
42
47
  this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
package/package.json CHANGED
@@ -1,11 +1,10 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
- "bin": { "conare": "./dist/cli/main.js" },
9
8
  "exports": {
10
9
  ".": {
11
10
  "types": "./dist/index.d.ts",
@@ -15,8 +14,8 @@
15
14
  "files": ["dist"],
16
15
  "sideEffects": false,
17
16
  "scripts": {
18
- "build": "rm -rf dist && tsc -p tsconfig.json && tsc -p tsconfig.cli.json && chmod +x dist/cli/main.js",
19
- "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.cli.json --noEmit",
17
+ "build": "rm -rf dist && tsc -p tsconfig.json",
18
+ "typecheck": "tsc -p tsconfig.json --noEmit",
20
19
  "test": "bun test",
21
20
  "prepublishOnly": "bun run build"
22
21
  },
@@ -26,7 +25,7 @@
26
25
  "license": "MIT",
27
26
  "engines": { "node": ">=18" },
28
27
  "devDependencies": {
29
- "@types/bun": "1.3.14",
28
+ "@types/bun": "1.4.2",
30
29
  "typescript": "5.9.3"
31
30
  }
32
31
  }
package/dist/cli/args.js DELETED
@@ -1,69 +0,0 @@
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
- }
@@ -1,37 +0,0 @@
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
- }
@@ -1,82 +0,0 @@
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
- }
package/dist/cli/main.js DELETED
@@ -1,127 +0,0 @@
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
- });
@@ -1,61 +0,0 @@
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
- }
@@ -1,69 +0,0 @@
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
- }