@4shub/ldl 0.0.0-stage → 0.1.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
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # ldl · Letta Downloader
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `ldl` makes a new native **Letta Code local-backend** agent from a Letta Cloud agent. It reads Cloud data through the individual endpoints, then builds the local files directly. It does not use agent-file export/import or write to Cloud.
4
+
5
+ ## Try it locally
6
+
7
+ Requires Node.js 20.12+, Git, and a Letta Code build with the native local backend and v2 transcript support. This is **not** an importer for a self-hosted Letta API server or its database.
8
+
9
+ ```sh
10
+ npm ci
11
+ npx --yes --package . -- ldl
12
+ ```
13
+
14
+ The TUI asks for a masked API key, lets you search for an agent, confirms the destination, then prints the command to open the copy. `--storage-dir` overrides `LETTA_LOCAL_BACKEND_DIR` and `~/.letta/lc-local-backend`. Each run creates a new agent ID. This package has not been published to npm.
15
+
16
+ ## What's copied
17
+
18
+ - **Native:** agent name, description, tags, system prompt, compatible model handle, core memory blocks (as MemFS files for non-MemFS agents), the primary Cloud MemFS repository when enabled, and transcripts for the default, active and archived conversations.
19
+ - **Preserved as data:** raw message rows, agent settings, tool and source definitions when returned by Cloud, core block metadata, legacy archival passages when exposed, and an ID mapping. These are not activated as tools or indexed as archival memory. Unsupported message types, remote attachment references, and unpaired tool returns may only be usable as raw data. Cloud context references are mapped where possible, not guaranteed to reproduce the exact next Cloud turn.
20
+ - **Not migrated:** attached source documents, secondary/shared MemFS repositories, secrets, credentials, provider configuration, Cloud integrations, schedules, environment/workspace files, and permissions. Local model access must be configured separately. Exit the local agent session before editing its data directly.
21
+
22
+ Downloads use one REST request at a time with a 2.5-second minimum cooldown, pages of 50 messages, bounded exponential backoff and `Retry-After` handling. `--delay-ms 5000` slows requests further. The percentage is an estimate weighted by completed conversations; message totals are used when supplied by the API. When no total is available, the message tally still updates on every page. Cloud reads are not a transactional snapshot; avoid chatting with the source agent during the copy. A cancelled/failed download does not publish an agent, and restarting begins a new copy.
23
+
24
+ The key is never saved by `ldl`. The exported content itself may be sensitive: keep the local storage folder private and review the imported agent and its memory before running it. Source: [Letta REST API reference](https://docs.letta.com/api/resources/agents) and the [Letta Code local backend](https://github.com/letta-ai/letta-code/tree/main/src/backend/local).
25
+
26
+ ## Development
27
+
28
+ ```sh
29
+ npm ci
30
+ npm test
31
+ npm pack --dry-run
32
+ ```
33
+
34
+ Set `LDL_LETTA_CODE_CHECKOUT` to a Letta Code source checkout with dependencies installed to also load a migrated fixture through its real `LocalStore`. The optional smoke test uses `bun` (or the `LDL_BUN` executable path).
package/package.json CHANGED
@@ -1,6 +1,13 @@
1
1
  {
2
2
  "name": "@4shub/ldl",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Download a Letta Cloud agent into Letta Code's local backend",
5
+ "type": "module",
6
+ "bin": { "ldl": "src/cli.js" },
7
+ "files": ["src"],
8
+ "engines": { "node": ">=20.12.0" },
9
+ "scripts": { "start": "node src/cli.js", "test": "node --test" },
10
+ "dependencies": { "@clack/prompts": "^1.9.0" },
11
+ "repository": "github:4shub/ldl",
12
+ "license": "UNLICENSED"
13
+ }
package/src/cli.js ADDED
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs, stripVTControlCharacters } from 'node:util';
3
+ import { resolve } from 'node:path';
4
+ import { autocomplete, cancel, confirm, intro, isCancel, log, outro, password, spinner } from '@clack/prompts';
5
+ import { collect, createCloud } from './cloud.js';
6
+ import { migrate, storageDir } from './migrate.js';
7
+
8
+ const help = `ldl — Letta Downloader
9
+
10
+ Usage: ldl [--storage-dir <path>] [--delay-ms <milliseconds>]
11
+
12
+ --storage-dir Letta Code local storage (default: $LETTA_LOCAL_BACKEND_DIR
13
+ or ~/.letta/lc-local-backend)
14
+ --delay-ms Time between Cloud API requests (default and minimum: 2500)
15
+ -h, --help Show help
16
+ `;
17
+ const printable = (text) => stripVTControlCharacters(String(text)).replace(/[\x00-\x1f\x7f\u202a-\u202e\u2066-\u2069]/g, ' ').slice(0, 120);
18
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
19
+
20
+ async function main() {
21
+ const { values } = parseArgs({ options: {
22
+ help: { type: 'boolean', short: 'h' }, 'storage-dir': { type: 'string' }, 'delay-ms': { type: 'string' },
23
+ } });
24
+ if (values.help) { process.stdout.write(help); return; }
25
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error('Run ldl from an interactive terminal.');
26
+ const delay = Number(values['delay-ms'] ?? 2500);
27
+ if (!Number.isInteger(delay) || delay < 2500 || delay > 300_000) throw new Error('--delay-ms must be between 2500 and 300000.');
28
+ if (values['storage-dir'] === '') throw new Error('--storage-dir cannot be empty.');
29
+ const root = values['storage-dir'] ? resolve(values['storage-dir']) : storageDir();
30
+ intro('ldl · Letta Downloader');
31
+ const secret = await password({ message: 'Letta Cloud API key', validate: (value) => !value?.trim() ? 'Enter a key to continue' : undefined });
32
+ if (isCancel(secret)) { cancel('Cancelled.'); return; }
33
+ const key = secret.trim();
34
+ const controller = new AbortController();
35
+ const activity = spinner({ onCancel: () => controller.abort() });
36
+ let spinning = false;
37
+ const start = (message) => { activity.start(message); spinning = true; };
38
+ const stop = (message) => { if (spinning) activity.stop(message); spinning = false; };
39
+ const abort = () => controller.abort();
40
+ process.on('SIGINT', abort);
41
+ process.on('SIGTERM', abort);
42
+ try {
43
+ start('Listing your Cloud agents…');
44
+ const cloud = createCloud({ key, delay, signal: controller.signal, onWait: (message) => activity.message(message) });
45
+ const agents = await collect(cloud, '/v1/agents/', { limit: 100 });
46
+ stop(`${agents.length} Cloud agents found`);
47
+ if (!agents.length) { outro('Nothing to download.'); return; }
48
+ const id = await autocomplete({
49
+ message: 'Pick an agent', maxItems: 10, placeholder: 'Type a name to filter',
50
+ options: agents.map((agent) => ({ value: agent.id, label: printable(agent.name || agent.id), hint: printable(agent.id) })),
51
+ });
52
+ if (isCancel(id)) { cancel('Cancelled.'); return; }
53
+ const confirmed = await confirm({ message: `Create a new local copy in ${printable(root)}?`, initialValue: true });
54
+ if (isCancel(confirmed) || !confirmed) { cancel('Cancelled.'); return; }
55
+ start('Starting download…');
56
+ const result = await migrate({ cloud, key, sourceId: id, root, signal: controller.signal, report: (message) => activity.message(message) });
57
+ stop(`100% · ${result.conversations} conversations · ${result.messages.toLocaleString()} message rows downloaded`);
58
+ for (const warning of result.warnings) log.warn(warning);
59
+ log.info(`Open in Letta Code:\nLETTA_LOCAL_BACKEND_EXPERIMENTAL=1 LETTA_LOCAL_BACKEND_DIR=${quote(root)} letta --agent ${result.id}`);
60
+ outro(`Local agent: ${result.id}`);
61
+ } catch (error) {
62
+ stop(controller.signal.aborted ? 'Cancelled' : 'Download failed');
63
+ if (controller.signal.aborted) { process.exitCode = 130; return; }
64
+ throw error;
65
+ } finally {
66
+ process.off('SIGINT', abort);
67
+ process.off('SIGTERM', abort);
68
+ }
69
+ }
70
+
71
+ main().catch((error) => {
72
+ log.error(error?.status === 401 ? 'Letta Cloud rejected the API key.' : printable(error.message));
73
+ process.exitCode = 1;
74
+ });
package/src/cloud.js ADDED
@@ -0,0 +1,100 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
2
+
3
+ export const CLOUD = 'https://api.letta.com';
4
+ const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);
5
+
6
+ export class ApiError extends Error {
7
+ constructor(path, status) {
8
+ super(`Letta Cloud returned HTTP ${status} for ${path}`);
9
+ this.status = status;
10
+ }
11
+ }
12
+
13
+ export function retryAfterMs(header, now = Date.now()) {
14
+ if (!header) return 0;
15
+ const value = /^\d+(\.\d+)?$/.test(header) ? Number(header) * 1000 : Date.parse(header) - now;
16
+ return Number.isFinite(value) ? Math.max(0, value) : 0;
17
+ }
18
+
19
+ export function createCloud({ key, delay = 2500, signal, onWait = () => {}, fetcher = fetch, wait = sleep }) {
20
+ let next = 0;
21
+ let tail = Promise.resolve();
22
+ async function request(path, query) {
23
+ const url = new URL(path, CLOUD);
24
+ if (url.origin !== CLOUD || !url.pathname.startsWith('/v1/')) throw new Error('Invalid Letta Cloud API path');
25
+ for (const [k, v] of Object.entries(query ?? {})) {
26
+ if (Array.isArray(v)) for (const item of v) url.searchParams.append(k, item);
27
+ else if (v != null) url.searchParams.set(k, v);
28
+ }
29
+ for (let attempt = 0; attempt <= 5; attempt++) {
30
+ signal?.throwIfAborted();
31
+ if (next > Date.now()) await wait(next - Date.now(), undefined, { signal });
32
+ let response;
33
+ try {
34
+ response = await fetcher(url, {
35
+ headers: { authorization: `Bearer ${key}`, accept: 'application/json' },
36
+ redirect: 'error',
37
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(45_000)]) : AbortSignal.timeout(45_000),
38
+ });
39
+ if (response.ok) {
40
+ const data = await response.json();
41
+ next = Date.now() + delay;
42
+ return { data, headers: response.headers };
43
+ }
44
+ } catch (error) {
45
+ signal?.throwIfAborted();
46
+ if (error instanceof SyntaxError) throw new Error(`Invalid JSON returned for ${path}`);
47
+ if (attempt === 5) throw new Error(`Network request failed for ${path}`);
48
+ }
49
+ if (response) await response.body?.cancel().catch(() => {});
50
+ next = Date.now() + Math.max(delay, retryAfterMs(response?.headers.get('retry-after')));
51
+ if (response && (!RETRYABLE.has(response.status) || attempt === 5)) throw new ApiError(path, response.status);
52
+ const backoff = Math.max(next - Date.now(), 5000 * 2 ** attempt + Math.round(Math.random() * 1000));
53
+ // Fail instead of retrying early when the requested cooldown is unusually long.
54
+ if (backoff > 15 * 60_000) throw new Error('Letta Cloud requested a cooldown longer than 15 minutes. Try again later.');
55
+ next = Date.now() + backoff;
56
+ onWait(`Cloud ${response?.status ?? 'network error'} · retrying in ${Math.ceil(backoff / 1000)}s`);
57
+ }
58
+ }
59
+ return {
60
+ get(path, query) {
61
+ const task = tail.then(() => request(path, query));
62
+ tail = task.catch(() => {});
63
+ return task;
64
+ },
65
+ };
66
+ }
67
+
68
+ export async function* pages(cloud, path, { limit = 50, ...query } = {}) {
69
+ let after;
70
+ const cursors = new Set();
71
+ do {
72
+ const { data, headers } = await cloud.get(path, { limit, ...query, after });
73
+ const rows = Array.isArray(data) ? data : data?.items ?? data?.messages;
74
+ if (!Array.isArray(rows)) throw new Error(`Unexpected list response for ${path}`);
75
+ if (!rows.length) return;
76
+ after = rows.at(-1)?.id;
77
+ if (typeof after !== 'string' || !after || cursors.has(after)) throw new Error(`Pagination did not advance for ${path}`);
78
+ cursors.add(after);
79
+ const count = nonnegativeCount(headers.get('x-total-count') ?? data?.total_count ?? data?.total);
80
+ yield { rows, count };
81
+ // Message APIs can split or filter rows; a short page isn't necessarily EOF.
82
+ } while (after);
83
+ }
84
+
85
+ export function nonnegativeCount(value) {
86
+ if (value == null || (typeof value !== 'number' && !/^\d+$/.test(value))) return null;
87
+ const number = Number(value);
88
+ return Number.isSafeInteger(number) && number >= 0 ? number : null;
89
+ }
90
+
91
+ export async function collect(cloud, path, opts) {
92
+ const data = new Map();
93
+ for await (const { rows } of pages(cloud, path, opts)) {
94
+ for (const row of rows) {
95
+ if (typeof row?.id !== 'string') throw new Error(`Missing row ID for ${path}`);
96
+ data.set(row.id, row);
97
+ }
98
+ }
99
+ return [...data.values()];
100
+ }
package/src/memory.js ADDED
@@ -0,0 +1,56 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { chmod, mkdir, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ import { CLOUD } from './cloud.js';
6
+
7
+ const exec = promisify(execFile);
8
+
9
+ function git(cwd, args, signal, extra = []) {
10
+ const configs = [['core.hooksPath', '/dev/null'], ['credential.helper', ''], ['http.followRedirects', 'false'], ...extra];
11
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_') && key !== 'LETTA_API_KEY'));
12
+ configs.forEach(([key, value], index) => {
13
+ env[`GIT_CONFIG_KEY_${index}`] = key;
14
+ env[`GIT_CONFIG_VALUE_${index}`] = value;
15
+ });
16
+ return exec('git', args, { cwd, signal, timeout: 180_000, maxBuffer: 16 * 1024 * 1024, env: {
17
+ ...env, GIT_CONFIG_COUNT: String(configs.length), GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0',
18
+ } });
19
+ }
20
+
21
+ export async function prepareMemory({ dir, blocks, remote, sourceId, key, signal }) {
22
+ await mkdir(dir, { recursive: true, mode: 0o700 });
23
+ try {
24
+ if (remote) {
25
+ const headers = [['http.extraHeader', `Authorization: Basic ${Buffer.from(`letta:${key}`).toString('base64')}`]];
26
+ if (process.env.LETTA_MEMFS_BACKEND === 'hosted') headers.push(['http.extraHeader', 'x-letta-memfs-backend: hosted']);
27
+ // No checkout until entry types have been validated. Never persist the key or source remote.
28
+ await git(dir, ['clone', '--no-checkout', '--single-branch', '--no-tags', '--template=', `${CLOUD}/v1/git/${sourceId}/state.git`, '.'], signal, headers);
29
+ const { stdout } = await git(dir, ['ls-tree', '-rz', 'HEAD'], signal);
30
+ if (stdout.split('\0').some((entry) => /^(120000|160000) /.test(entry))) {
31
+ throw new Error('Unsupported symlink or submodule in Cloud MemFS');
32
+ }
33
+ await git(dir, ['remote', 'remove', 'origin'], signal);
34
+ await git(dir, ['reset', '--hard', 'HEAD'], signal);
35
+ } else {
36
+ await git(dir, ['init', '--initial-branch=main', '--template='], signal);
37
+ const system = join(dir, 'system');
38
+ await mkdir(system, { mode: 0o700 });
39
+ for (const [index, block] of blocks.entries()) {
40
+ if (typeof block?.value !== 'string' || block.label === 'memory_filesystem') continue;
41
+ const label = typeof block.label === 'string' ? block.label : 'block';
42
+ const name = label.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').slice(0, 60) || 'block';
43
+ const description = typeof block.description === 'string' && block.description.trim() ? block.description : label || 'Imported block';
44
+ await writeFile(join(system, `${String(index + 1).padStart(3, '0')}-${name}.md`),
45
+ `---\ndescription: ${JSON.stringify(description)}\n${block.read_only ? 'read_only: true\n' : ''}---\n${block.value}\n`, { mode: 0o600 });
46
+ }
47
+ await git(dir, ['add', '--', 'system'], signal);
48
+ await git(dir, ['-c', 'user.name=Letta Downloader', '-c', 'user.email=ldl@localhost', 'commit', '--allow-empty', '-m', 'Seed migrated Cloud memory'], signal);
49
+ }
50
+ await chmod(dir, 0o700);
51
+ } catch (error) {
52
+ signal?.throwIfAborted();
53
+ if (error.message === 'Unsupported symlink or submodule in Cloud MemFS') throw error;
54
+ throw new Error(remote ? 'Could not clone Cloud MemFS. Verify Git is installed and the key can read the agent’s MemFS repository.' : 'Could not initialize local MemFS. Verify Git is installed and the destination is writable.');
55
+ }
56
+ }
package/src/migrate.js ADDED
@@ -0,0 +1,129 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { link, mkdir, mkdtemp, rename, rm, writeFile, appendFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { ApiError, collect, nonnegativeCount, pages } from './cloud.js';
6
+ import { prepareMemory } from './memory.js';
7
+ import { openTranscript, writeJson } from './transcript.js';
8
+
9
+ export const storageDir = () => resolve(process.env.LETTA_LOCAL_BACKEND_DIR ?? join(homedir(), '.letta', 'lc-local-backend'));
10
+ const encoded = (key) => Buffer.from(key).toString('base64url');
11
+ const cloudAgentId = /^agent-[a-z0-9_-]+$/i;
12
+ const strings = (value) => Array.isArray(value) ? value.filter((x) => typeof x === 'string') : [];
13
+ const optionalEndpoint = (error) => error instanceof ApiError && [403, 404, 405, 501].includes(error.status);
14
+
15
+ export async function migrate({ cloud, key, sourceId, root = storageDir(), signal, report = () => {}, memory = prepareMemory }) {
16
+ if (!cloudAgentId.test(sourceId)) throw new Error('Unexpected Cloud agent ID');
17
+ const base = `/v1/agents/${sourceId}`;
18
+ const localId = `agent-local-${randomUUID()}`;
19
+ await mkdir(root, { recursive: true, mode: 0o700 });
20
+ const stage = await mkdtemp(join(root, '.ldl-'));
21
+ const moves = [];
22
+ const warnings = [];
23
+ try {
24
+ report('Reading agent settings and memory blocks…');
25
+ const { data: agent } = await cloud.get(base, { include: ['agent.tags', 'agent.tools', 'agent.sources'] });
26
+ if (agent?.id !== sourceId) throw new Error('Cloud returned the wrong agent');
27
+ const { data: blocks } = await cloud.get(`${base}/core-memory/blocks`);
28
+ if (!Array.isArray(blocks)) throw new Error('Unexpected memory block response');
29
+ const model = typeof agent.model === 'string' && agent.model.includes('/') && !agent.model.startsWith('letta/') ? agent.model : 'local/default';
30
+ const record = {
31
+ id: localId, name: agent.name ?? 'Letta Cloud agent', description: agent.description ?? null,
32
+ system: agent.system ?? '', tags: strings(agent.tags), model, model_settings: {}, hidden: false,
33
+ };
34
+ await writeJson(join(stage, 'agent.json'), record);
35
+
36
+ report('Listing active and archived conversations…');
37
+ const listed = await collect(cloud, '/v1/conversations/', { agent_id: sourceId, archive_status: 'all', order_by: 'created_at', order: 'asc' });
38
+ if (listed.some((row) => row.agent_id && row.agent_id !== sourceId)) throw new Error('Cloud returned conversations for another agent');
39
+ const sessions = [
40
+ { id: 'default', message_ids: agent.message_ids, created_at: agent.created_at },
41
+ ...listed.filter((row) => row.id !== 'default'),
42
+ ];
43
+ const stagedConversations = join(stage, 'conversations');
44
+ await mkdir(stagedConversations, { mode: 0o700 });
45
+ const mapping = [];
46
+ let totalRows = 0;
47
+ let skippedRows = 0;
48
+ for (const [i, listedSession] of sessions.entries()) {
49
+ signal?.throwIfAborted();
50
+ const isDefault = listedSession.id === 'default';
51
+ const source = isDefault ? listedSession : (await cloud.get(`/v1/conversations/${encodeURIComponent(listedSession.id)}`)).data;
52
+ if (source?.id !== listedSession.id || (source.agent_id && source.agent_id !== sourceId)) throw new Error('Cloud returned the wrong conversation');
53
+ const id = isDefault ? 'default' : `local-conv-${randomUUID()}`;
54
+ const folder = encoded(isDefault ? `default:${localId}` : `conversation:${id}`);
55
+ const dir = join(stagedConversations, folder);
56
+ await mkdir(dir, { mode: 0o700 });
57
+ const writer = await openTranscript(dir, {
58
+ id, agent_id: localId, archived: source.archived === true, archived_at: source.archived_at ?? null,
59
+ summary: typeof source.summary === 'string' ? source.summary : null,
60
+ }, source, model);
61
+ const path = `/v1/conversations/${encodeURIComponent(source.id)}/messages`;
62
+ const query = { agent_id: isDefault ? sourceId : undefined };
63
+ let downloaded = 0;
64
+ let count = nonnegativeCount(source.message_count);
65
+ const progress = () => {
66
+ const fraction = count != null && count > 0 ? Math.min(0.99, downloaded / count) : 0;
67
+ const estimate = Math.floor((i + fraction) * 90 / sessions.length);
68
+ report(`~${estimate}% · Conversation ${i + 1}/${sessions.length} · ${downloaded.toLocaleString()}${count == null ? '' : `/${count.toLocaleString()}`} messages`);
69
+ };
70
+ progress();
71
+ for await (const page of pages(cloud, path, { ...query, order: 'asc' })) {
72
+ downloaded += await writer.append(page.rows);
73
+ count ??= page.count;
74
+ progress();
75
+ }
76
+ const stats = await writer.finish();
77
+ mapping.push({ source: source.id, id, ...stats });
78
+ totalRows += stats.messages;
79
+ skippedRows += stats.unprojected;
80
+ }
81
+
82
+ report('~90% · Copying memory files…');
83
+ await memory({ dir: join(stage, 'memfs', 'memory'), blocks, remote: record.tags.includes('git-memory-enabled'), sourceId, key, signal });
84
+ const backup = join(stage, 'backup');
85
+ await mkdir(backup, { mode: 0o700 });
86
+ await writeJson(join(backup, 'agent.json'), agent);
87
+ await writeJson(join(backup, 'blocks.json'), blocks);
88
+ report('~94% · Reading legacy archival passages…');
89
+ const archiveFile = join(backup, 'archival-passages.jsonl');
90
+ await writeFile(archiveFile, '', { mode: 0o600 });
91
+ let passages = 0;
92
+ try {
93
+ for await (const { rows } of pages(cloud, `${base}/archival-memory`)) {
94
+ await appendFile(archiveFile, rows.map((row) => `${JSON.stringify(row)}\n`).join(''));
95
+ passages += rows.length;
96
+ }
97
+ } catch (error) {
98
+ if (!optionalEndpoint(error)) throw error;
99
+ warnings.push('Legacy archival passages API unavailable.');
100
+ }
101
+ if (passages) warnings.push(`${passages} archival passages saved as JSONL, not indexed locally.`);
102
+ if (skippedRows) warnings.push(`${skippedRows} Cloud message rows retained in raw transcripts only.`);
103
+ await writeJson(join(backup, 'migration.json'), { sourceId, localId, conversations: mapping, passages, warnings });
104
+
105
+ signal?.throwIfAborted();
106
+ report('~98% · Installing into the local backend…');
107
+ const install = async (from, directory, name) => {
108
+ const parent = join(root, directory);
109
+ await mkdir(parent, { recursive: true, mode: 0o700 });
110
+ const target = join(parent, name);
111
+ await rename(from, target);
112
+ moves.push(target);
113
+ };
114
+ for (const folder of mapping.map(({ id }) => encoded(id === 'default' ? `default:${localId}` : `conversation:${id}`))) {
115
+ await install(join(stagedConversations, folder), 'conversations', folder);
116
+ }
117
+ await install(join(stage, 'memfs'), 'memfs', localId);
118
+ await install(backup, 'ldl-backups', localId);
119
+ await mkdir(join(root, 'agents'), { mode: 0o700, recursive: true });
120
+ // Publish the agent last, with a no-overwrite operation.
121
+ await link(join(stage, 'agent.json'), join(root, 'agents', `${encoded(localId)}.json`));
122
+ return { id: localId, conversations: mapping.length, messages: totalRows, warnings, root };
123
+ } catch (error) {
124
+ for (const path of moves.reverse()) await rm(path, { recursive: true, force: true });
125
+ throw error;
126
+ } finally {
127
+ await rm(stage, { recursive: true, force: true });
128
+ }
129
+ }
@@ -0,0 +1,131 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { appendFile, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+
5
+ export const writeJson = (file, data) => writeFile(file, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
6
+ const lines = (rows) => rows.map((row) => `${JSON.stringify(row)}\n`).join('');
7
+ const text = (value) => ({ type: 'text', text: value });
8
+ const date = (value, fallback) => Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : fallback;
9
+ const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
10
+
11
+ function contentParts(content, images = false) {
12
+ if (typeof content === 'string') return [text(content)];
13
+ return Array.isArray(content) ? content.flatMap((part) => {
14
+ if (part?.type === 'text' && typeof part.text === 'string') return [text(part.text)];
15
+ if (images && part?.type === 'image' && part.source?.type === 'base64' &&
16
+ typeof part.source.data === 'string' && typeof part.source.media_type === 'string') {
17
+ return [{ type: 'image', data: part.source.data, mimeType: part.source.media_type }];
18
+ }
19
+ return [];
20
+ }) : [];
21
+ }
22
+
23
+ function argumentsObject(value) {
24
+ try {
25
+ const parsed = typeof value === 'string' ? JSON.parse(value) : value;
26
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
27
+ } catch { /* Original is retained in cloud-messages.jsonl. */ }
28
+ return {};
29
+ }
30
+
31
+ const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
32
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
33
+
34
+ export async function openTranscript(dir, conversation, source, model) {
35
+ const path = join(dir, 'messages.jsonl');
36
+ const raw = join(dir, 'cloud-messages.jsonl');
37
+ const created = date(source.created_at, new Date().toISOString());
38
+ const active = new Set(strings(source.in_context_message_ids ?? source.message_ids));
39
+ const calls = new Map();
40
+ const seen = new Set();
41
+ let parentId = null;
42
+ let assistant;
43
+ let mostRecent = null;
44
+ let unprojected = 0;
45
+ const add = (entries, row, fields, suffix = '') => {
46
+ const timestamp = date(row.date, created);
47
+ const id = `${row.id}${suffix}`;
48
+ const entryId = randomUUID().replaceAll('-', '').slice(0, 16);
49
+ entries.push({ type: 'message', id: entryId, parentId, timestamp, message: {
50
+ id, timestamp: Date.parse(timestamp), metadata: { created_at: timestamp,
51
+ agent_id: conversation.agent_id, conversation_id: conversation.id }, ...fields,
52
+ } });
53
+ parentId = entryId;
54
+ return id;
55
+ };
56
+ const activeIds = [];
57
+ const isActive = (row) => active.has(row.id) || active.has(row.id.replace(/-\d+$/, ''));
58
+ const flush = (entries) => {
59
+ if (!assistant) return;
60
+ const id = add(entries, assistant.row, {
61
+ role: 'assistant', content: assistant.parts, provider: 'ldl-history', model,
62
+ api: 'openai-completions', usage, stopReason: assistant.toolCall ? 'toolUse' : 'stop',
63
+ });
64
+ for (const part of assistant.parts) if (part.type === 'toolCall') calls.set(part.id, { name: part.name, active: assistant.active });
65
+ if (assistant.active) activeIds.push(id);
66
+ assistant = undefined;
67
+ };
68
+ await writeFile(path, lines([{ type: 'session', version: 3, id: conversation.id, timestamp: created, cwd: process.cwd() }]), { mode: 0o600 });
69
+ await writeFile(raw, '', { mode: 0o600 });
70
+ return {
71
+ async append(rows) {
72
+ const entries = [];
73
+ const originals = [];
74
+ for (const row of rows) {
75
+ if (typeof row?.id !== 'string') throw new Error('Cloud message had no ID');
76
+ if (seen.has(row.id)) continue;
77
+ seen.add(row.id);
78
+ originals.push(row);
79
+ mostRecent = date(row.date, mostRecent);
80
+ if (['assistant_message', 'reasoning_message', 'tool_call_message'].includes(row.message_type)) {
81
+ const toolCalls = Array.isArray(row.tool_calls) && row.tool_calls.length ? row.tool_calls : [row.tool_call];
82
+ const parts = row.message_type === 'assistant_message' ? contentParts(row.content) :
83
+ row.message_type === 'reasoning_message' ? (typeof row.reasoning === 'string' ? [{ type: 'thinking', thinking: row.reasoning }] : []) :
84
+ toolCalls.filter((call) => call && typeof call.tool_call_id === 'string' && typeof call.name === 'string').map((call) => ({
85
+ type: 'toolCall', id: call.tool_call_id, name: call.name, arguments: argumentsObject(call.arguments),
86
+ }));
87
+ if (!parts.length) { unprojected++; continue; }
88
+ if (assistant && assistant.row.step_id && row.step_id && assistant.row.step_id !== row.step_id) flush(entries);
89
+ assistant ??= { row, parts: [], active: false, toolCall: false };
90
+ assistant.parts.push(...parts);
91
+ assistant.active ||= isActive(row);
92
+ assistant.toolCall ||= row.message_type === 'tool_call_message';
93
+ continue;
94
+ }
95
+ flush(entries);
96
+ if (row.message_type === 'user_message') {
97
+ const content = contentParts(row.content, true);
98
+ if (content.length) {
99
+ const id = add(entries, row, { role: 'user', content, ...(row.otid ? { otid: row.otid } : {}) });
100
+ if (isActive(row)) activeIds.push(id);
101
+ } else unprojected++;
102
+ } else if (row.message_type === 'tool_return_message') {
103
+ const returns = Array.isArray(row.tool_returns) && row.tool_returns.length ? row.tool_returns : [row];
104
+ for (const [index, result] of returns.entries()) {
105
+ const call = calls.get(result?.tool_call_id);
106
+ if (!call) { unprojected++; continue; }
107
+ const id = add(entries, row, { role: 'toolResult', toolCallId: result.tool_call_id, toolName: call.name,
108
+ content: contentParts(result.tool_return, true), isError: result.status === 'error' }, index ? `:result:${index}` : '');
109
+ if (isActive(row) && call.active) activeIds.push(id);
110
+ }
111
+ } else unprojected++;
112
+ }
113
+ if (originals.length) await appendFile(raw, lines(originals));
114
+ if (entries.length) await appendFile(path, lines(entries));
115
+ return originals.length;
116
+ },
117
+ async finish() {
118
+ const entries = [];
119
+ flush(entries);
120
+ if (entries.length) await appendFile(path, lines(entries));
121
+ await writeJson(join(dir, 'manifest.json'), {
122
+ schema_version: 2, message_format: 'pi-session-entry-jsonl', provider_stack: 'pi-ai', created_at: created,
123
+ });
124
+ await writeJson(join(dir, 'conversation.json'), {
125
+ ...conversation, created_at: created, updated_at: date(source.updated_at, mostRecent ?? created),
126
+ last_message_at: date(source.last_message_at, mostRecent), in_context_message_ids: activeIds,
127
+ });
128
+ return { unprojected, messages: seen.size };
129
+ },
130
+ };
131
+ }