my-durable 0.0.47 → 0.0.49
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/apps/dpi-backend/src/archived.ts +332 -0
- package/apps/dpi-backend/src/routes.ts +11 -0
- package/apps/dpi-backend/src/store.ts +71 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CCTagPRK.css +1 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-BQX67D5M.js → index-CD2LAoea.js} +14 -14
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ArchivePanel.vue +197 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +7 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/style.css +26 -6
- package/apps/dpi-sdk/src/api.ts +13 -0
- package/apps/dpi-sdk/src/client.ts +14 -0
- package/apps/dpi-sdk/src/protocol/rest-routes.ts +3 -0
- package/docs/host-project-checklist.md +1 -1
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BJ1vWSJJ.css +0 -1
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only browsing and one-way restore of `<dataDir>/archive/` — the first
|
|
3
|
+
* slice of "old sessions as feature surface": sessions are never auto-deleted
|
|
4
|
+
* (user-decided policy #3 rationale), so the archive becomes worth browsing.
|
|
5
|
+
*
|
|
6
|
+
* `store.archive()` moves `<dataDir>/sessions/<uuid>/` to
|
|
7
|
+
* `<dataDir>/archive/<uuid>-<archivedAtMs>/` and deletes the catalog row —
|
|
8
|
+
* which until now made every bundle anonymous: the session's name/cwd/model
|
|
9
|
+
* lived only in the deleted row. This module adds a `session.json` manifest
|
|
10
|
+
* inside each bundle (`writeArchiveManifest`, for the store to call going
|
|
11
|
+
* forward) and reads BOTH worlds: for old bundles the dirname is the ONLY
|
|
12
|
+
* source of truth (uuid + archivedAt ms), and everything else degrades —
|
|
13
|
+
* `archived <first 8 of id>` name, empty cwd/model — instead of hiding rows.
|
|
14
|
+
*
|
|
15
|
+
* A bundle's `agent.sqlite` is a foreign database: opened with `{ readOnly: true }`
|
|
16
|
+
* and closed on every path (the gc/doctor rule for handles we do not own).
|
|
17
|
+
* `listArchived` never throws — an unreadable sqlite degrades to
|
|
18
|
+
* `turns: -1` / `lastMessageAt: null`, an unreadable dir to `bytes: 0` — while
|
|
19
|
+
* `archivedTranscript` reuses the SDK's `toTranscript`/`toMarkdown` so an
|
|
20
|
+
* archived session renders exactly like a live one, and throws the one
|
|
21
|
+
* "archive bundle unreadable" the route maps to 404. `restoreArchive` is the
|
|
22
|
+
* single mutation: one rename back under `sessions/<id>` (refused while a live
|
|
23
|
+
* session with that id exists), synthesize-and-write a manifest for old bundles.
|
|
24
|
+
*
|
|
25
|
+
* No express, no Store import: the leader wires routes and store calls.
|
|
26
|
+
*/
|
|
27
|
+
import { chmodSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
28
|
+
import { mkdir, rename, stat } from "node:fs/promises";
|
|
29
|
+
import { basename, join } from "node:path";
|
|
30
|
+
import { DatabaseSync } from "node:sqlite";
|
|
31
|
+
import { toMarkdown, toTranscript, type TranscriptItem } from "../../dpi-sdk/src/transcript.js";
|
|
32
|
+
import type { WireEntry } from "../../dpi-sdk/src/api.js";
|
|
33
|
+
|
|
34
|
+
/** Written into every bundle by `writeArchiveManifest`; the manifest of record once it exists. */
|
|
35
|
+
const MANIFEST_NAME = "session.json";
|
|
36
|
+
/** The one file every archived session dir carries (`store.archive()` moved it verbatim). */
|
|
37
|
+
const DB_NAME = "agent.sqlite";
|
|
38
|
+
/** Manifests and restored dirs keep the house rule: 0600 files, 0700 dirs. */
|
|
39
|
+
const FILE_MODE = 0o600;
|
|
40
|
+
const DIR_MODE = 0o700;
|
|
41
|
+
|
|
42
|
+
/** `<uuid>-<archivedAtMs>`: the only identity an old bundle has. 36 uuid chars + 13 ms digits. */
|
|
43
|
+
const BUNDLE_DIR_PATTERN = /^([0-9a-f-]{36})-(\d{13})$/;
|
|
44
|
+
/** Full lowercase uuid, 8-4-4-4-12: a PREFIX of another uuid must never match a bundle. */
|
|
45
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
46
|
+
|
|
47
|
+
/** The identity a catalog row used to hold — written into the bundle so archiving stops being lossy. */
|
|
48
|
+
export interface ArchiveManifest {
|
|
49
|
+
sessionId: string;
|
|
50
|
+
name: string;
|
|
51
|
+
cwd: string;
|
|
52
|
+
model: string;
|
|
53
|
+
provider: string;
|
|
54
|
+
createdAt: number;
|
|
55
|
+
archivedAt: number;
|
|
56
|
+
packageVersion: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One row of the archive listing: manifest data where it exists, dirname + degradation where it does not. */
|
|
60
|
+
export interface ArchivedView {
|
|
61
|
+
sessionId: string;
|
|
62
|
+
archivedAt: number;
|
|
63
|
+
/** Manifest name, or `archived <first 8 of id>` for old bundles. */
|
|
64
|
+
name: string;
|
|
65
|
+
/** Manifest cwd, or "" when unknown. */
|
|
66
|
+
cwd: string;
|
|
67
|
+
/** Manifest model, or "" when unknown. */
|
|
68
|
+
model: string;
|
|
69
|
+
/** Count of pi.user + pi.assistant entries; -1 when the sqlite is unreadable. */
|
|
70
|
+
turns: number;
|
|
71
|
+
/** Max `model[].timestamp` across entries; null when unreadable (or no messages). */
|
|
72
|
+
lastMessageAt: number | null;
|
|
73
|
+
/** Recursive dir size; 0 when unreadable. */
|
|
74
|
+
bytes: number;
|
|
75
|
+
hasManifest: boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The same shape `store.transcript()` returns, so archived sessions render like live ones. */
|
|
79
|
+
export type ArchivedTranscript =
|
|
80
|
+
| { format: "markdown"; text: string }
|
|
81
|
+
| { format: "json"; items: TranscriptItem[] };
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Write `session.json` (2-space JSON + trailing newline, 0600) into `bundleDir`.
|
|
85
|
+
* Overwrites silently: a re-archive of the same bundle updates its identity.
|
|
86
|
+
*/
|
|
87
|
+
export function writeArchiveManifest(bundleDir: string, m: ArchiveManifest): void {
|
|
88
|
+
const path = join(bundleDir, MANIFEST_NAME);
|
|
89
|
+
writeFileSync(path, `${JSON.stringify(m, null, 2)}\n`, { mode: FILE_MODE });
|
|
90
|
+
chmodSync(path, FILE_MODE); // mode only applies on create; keep 0600 across overwrites
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Read a bundle's manifest. Absent or corrupt (bad JSON, wrong shape) →
|
|
95
|
+
* undefined — an old bundle is normal, not an error. Never throws.
|
|
96
|
+
*/
|
|
97
|
+
export function readArchiveManifest(bundleDir: string): ArchiveManifest | undefined {
|
|
98
|
+
try {
|
|
99
|
+
const parsed: unknown = JSON.parse(readFileSync(join(bundleDir, MANIFEST_NAME), "utf8"));
|
|
100
|
+
if (typeof parsed !== "object" || parsed === null) return undefined;
|
|
101
|
+
const m = parsed as Record<string, unknown>;
|
|
102
|
+
if (
|
|
103
|
+
typeof m.sessionId !== "string" ||
|
|
104
|
+
typeof m.name !== "string" ||
|
|
105
|
+
typeof m.cwd !== "string" ||
|
|
106
|
+
typeof m.model !== "string" ||
|
|
107
|
+
typeof m.provider !== "string" ||
|
|
108
|
+
typeof m.createdAt !== "number" ||
|
|
109
|
+
typeof m.archivedAt !== "number" ||
|
|
110
|
+
typeof m.packageVersion !== "string"
|
|
111
|
+
) {
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
sessionId: m.sessionId,
|
|
116
|
+
name: m.name,
|
|
117
|
+
cwd: m.cwd,
|
|
118
|
+
model: m.model,
|
|
119
|
+
provider: m.provider,
|
|
120
|
+
createdAt: m.createdAt,
|
|
121
|
+
archivedAt: m.archivedAt,
|
|
122
|
+
packageVersion: m.packageVersion,
|
|
123
|
+
};
|
|
124
|
+
} catch {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Parse one `entries.record` / tolerate one bad row: corrupt records are skipped, never fatal. */
|
|
130
|
+
function parseRecord(record: unknown): Record<string, unknown> | undefined {
|
|
131
|
+
try {
|
|
132
|
+
const parsed: unknown = typeof record === "string" ? JSON.parse(record) : record;
|
|
133
|
+
return typeof parsed === "object" && parsed !== null ? (parsed as Record<string, unknown>) : undefined;
|
|
134
|
+
} catch {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* turns/lastMessageAt from the bundle's sqlite, degraded on any error: a
|
|
141
|
+
* foreign handle we close on every path — listing must never throw for a
|
|
142
|
+
* bundle that is merely unreadable.
|
|
143
|
+
*/
|
|
144
|
+
function bundleStats(bundleDir: string): { turns: number; lastMessageAt: number | null } {
|
|
145
|
+
let db: DatabaseSync | undefined;
|
|
146
|
+
try {
|
|
147
|
+
db = new DatabaseSync(join(bundleDir, DB_NAME), { readOnly: true });
|
|
148
|
+
const rows = db.prepare("SELECT record FROM entries").all() as unknown[];
|
|
149
|
+
let turns = 0;
|
|
150
|
+
let lastMessageAt: number | null = null;
|
|
151
|
+
for (const row of rows) {
|
|
152
|
+
const entry = parseRecord((row as { record?: unknown }).record);
|
|
153
|
+
if (!entry) continue;
|
|
154
|
+
if (entry.kind === "pi.user" || entry.kind === "pi.assistant") turns += 1;
|
|
155
|
+
if (!Array.isArray(entry.model)) continue;
|
|
156
|
+
for (const message of entry.model) {
|
|
157
|
+
const timestamp = (message as { timestamp?: unknown } | null)?.timestamp;
|
|
158
|
+
if (typeof timestamp === "number" && (lastMessageAt === null || timestamp > lastMessageAt)) {
|
|
159
|
+
lastMessageAt = timestamp;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return { turns, lastMessageAt };
|
|
164
|
+
} catch {
|
|
165
|
+
return { turns: -1, lastMessageAt: null };
|
|
166
|
+
} finally {
|
|
167
|
+
try {
|
|
168
|
+
db?.close();
|
|
169
|
+
} catch {
|
|
170
|
+
// never-opened or already closed: nothing to release
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Recursive size of a bundle dir; 0 when unreadable. Symlinks are not followed (lstat-free stat on entries we can read). */
|
|
176
|
+
function dirBytes(dir: string): number {
|
|
177
|
+
let total = 0;
|
|
178
|
+
let names: string[];
|
|
179
|
+
try {
|
|
180
|
+
names = readdirSync(dir);
|
|
181
|
+
} catch {
|
|
182
|
+
return 0;
|
|
183
|
+
}
|
|
184
|
+
for (const name of names) {
|
|
185
|
+
try {
|
|
186
|
+
const s = statSync(join(dir, name));
|
|
187
|
+
if (s.isDirectory()) total += dirBytes(join(dir, name));
|
|
188
|
+
else if (s.isFile()) total += s.size;
|
|
189
|
+
} catch {
|
|
190
|
+
// broken symlink / vanished entry: not sizeable, not fatal
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return total;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Every bundle in `archiveDir`, newest archivedAt first. Manifest fields where
|
|
198
|
+
* present, dirname-derived fallbacks where not; unreadable pieces degrade
|
|
199
|
+
* rather than hide. Missing archiveDir → []. Never throws.
|
|
200
|
+
*/
|
|
201
|
+
export function listArchived(archiveDir: string): ArchivedView[] {
|
|
202
|
+
let names: string[];
|
|
203
|
+
try {
|
|
204
|
+
names = readdirSync(archiveDir);
|
|
205
|
+
} catch {
|
|
206
|
+
return [];
|
|
207
|
+
}
|
|
208
|
+
const views: ArchivedView[] = [];
|
|
209
|
+
for (const name of names) {
|
|
210
|
+
const match = BUNDLE_DIR_PATTERN.exec(name);
|
|
211
|
+
if (!match) continue;
|
|
212
|
+
const bundleDir = join(archiveDir, name);
|
|
213
|
+
try {
|
|
214
|
+
if (!statSync(bundleDir).isDirectory()) continue;
|
|
215
|
+
} catch {
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const sessionId = match[1];
|
|
219
|
+
const archivedAt = Number(match[2]);
|
|
220
|
+
const manifest = readArchiveManifest(bundleDir);
|
|
221
|
+
const { turns, lastMessageAt } = bundleStats(bundleDir);
|
|
222
|
+
views.push({
|
|
223
|
+
sessionId,
|
|
224
|
+
archivedAt,
|
|
225
|
+
name: manifest?.name ?? `archived ${sessionId.slice(0, 8)}`,
|
|
226
|
+
cwd: manifest?.cwd ?? "",
|
|
227
|
+
model: manifest?.model ?? "",
|
|
228
|
+
turns,
|
|
229
|
+
lastMessageAt,
|
|
230
|
+
bytes: dirBytes(bundleDir),
|
|
231
|
+
hasManifest: manifest !== undefined,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
views.sort((a, b) => b.archivedAt - a.archivedAt || (a.sessionId < b.sessionId ? 1 : -1));
|
|
235
|
+
return views;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Path of the newest bundle for `sessionId`, or null. The id must be a FULL
|
|
240
|
+
* uuid (8-4-4-4-12), so a prefix of another session's uuid can never match,
|
|
241
|
+
* and the dirname must match it exactly.
|
|
242
|
+
*/
|
|
243
|
+
export function findBundle(archiveDir: string, sessionId: string): string | null {
|
|
244
|
+
const id = sessionId.toLowerCase();
|
|
245
|
+
if (!UUID_PATTERN.test(id)) return null;
|
|
246
|
+
let names: string[];
|
|
247
|
+
try {
|
|
248
|
+
names = readdirSync(archiveDir);
|
|
249
|
+
} catch {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
let best: { name: string; archivedAt: number } | null = null;
|
|
253
|
+
for (const name of names) {
|
|
254
|
+
const match = BUNDLE_DIR_PATTERN.exec(name);
|
|
255
|
+
if (!match || match[1] !== id) continue;
|
|
256
|
+
const archivedAt = Number(match[2]);
|
|
257
|
+
if (!best || archivedAt > best.archivedAt) best = { name, archivedAt };
|
|
258
|
+
}
|
|
259
|
+
return best ? join(archiveDir, best.name) : null;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Transcript of an archived bundle, same shape as the live-session endpoint:
|
|
264
|
+
* ALL entries (in `conversation_id, commit_seq` order) through the SDK's
|
|
265
|
+
* `toTranscript`, then `toMarkdown` for markdown. Corrupt records are skipped;
|
|
266
|
+
* an unreadable sqlite throws `Error("archive bundle unreadable")` for the
|
|
267
|
+
* route to map to 404.
|
|
268
|
+
*/
|
|
269
|
+
export function archivedTranscript(bundleDir: string, format: "markdown" | "json"): ArchivedTranscript {
|
|
270
|
+
let db: DatabaseSync | undefined;
|
|
271
|
+
const entries: WireEntry[] = [];
|
|
272
|
+
try {
|
|
273
|
+
db = new DatabaseSync(join(bundleDir, DB_NAME), { readOnly: true });
|
|
274
|
+
const rows = db.prepare("SELECT record FROM entries ORDER BY conversation_id, commit_seq").all() as unknown[];
|
|
275
|
+
for (const row of rows) {
|
|
276
|
+
const entry = parseRecord((row as { record?: unknown }).record);
|
|
277
|
+
if (entry) entries.push(entry as unknown as WireEntry);
|
|
278
|
+
}
|
|
279
|
+
} catch {
|
|
280
|
+
throw new Error("archive bundle unreadable");
|
|
281
|
+
} finally {
|
|
282
|
+
try {
|
|
283
|
+
db?.close();
|
|
284
|
+
} catch {
|
|
285
|
+
// never-opened or already closed: nothing to release
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
const items = toTranscript(entries);
|
|
289
|
+
return format === "markdown" ? { format: "markdown", text: toMarkdown(items) } : { format: "json", items };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Move the newest bundle for `sessionId` back under `<dataDir>/sessions/<sessionId>`
|
|
294
|
+
* (one rename — nothing is copied, nothing is deleted). Refused while a live
|
|
295
|
+
* session with that id exists (`a live session with this id already exists`);
|
|
296
|
+
* unknown id → `no archived session <id>` for the route to map to 404. Old
|
|
297
|
+
* bundles gain a synthesized manifest (dirname archivedAt as createdAt too) so
|
|
298
|
+
* the restored session is no longer anonymous. Returns the bundle's manifest.
|
|
299
|
+
*/
|
|
300
|
+
export async function restoreArchive(
|
|
301
|
+
archiveDir: string,
|
|
302
|
+
dataDir: string,
|
|
303
|
+
sessionId: string,
|
|
304
|
+
): Promise<ArchiveManifest | undefined> {
|
|
305
|
+
const sessionsDir = join(dataDir, "sessions");
|
|
306
|
+
const target = join(sessionsDir, sessionId);
|
|
307
|
+
try {
|
|
308
|
+
await stat(target);
|
|
309
|
+
throw new Error("a live session with this id already exists");
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (error instanceof Error && error.message === "a live session with this id already exists") throw error;
|
|
312
|
+
}
|
|
313
|
+
const bundle = findBundle(archiveDir, sessionId);
|
|
314
|
+
if (!bundle) throw new Error(`no archived session ${sessionId}`);
|
|
315
|
+
await mkdir(sessionsDir, { recursive: true, mode: DIR_MODE });
|
|
316
|
+
await rename(bundle, target);
|
|
317
|
+
const existing = readArchiveManifest(target);
|
|
318
|
+
if (existing) return existing;
|
|
319
|
+
const archivedAt = Number(BUNDLE_DIR_PATTERN.exec(basename(bundle))?.[2] ?? 0);
|
|
320
|
+
const synthesized: ArchiveManifest = {
|
|
321
|
+
sessionId,
|
|
322
|
+
name: `archived ${sessionId.slice(0, 8)}`,
|
|
323
|
+
cwd: "",
|
|
324
|
+
model: "",
|
|
325
|
+
provider: "",
|
|
326
|
+
createdAt: archivedAt,
|
|
327
|
+
archivedAt,
|
|
328
|
+
packageVersion: "",
|
|
329
|
+
};
|
|
330
|
+
writeArchiveManifest(target, synthesized);
|
|
331
|
+
return synthesized;
|
|
332
|
+
}
|
|
@@ -264,6 +264,17 @@ export function v1(
|
|
|
264
264
|
r.get("/sessions/:s/compaction", route(async (_req, res) => res.json(store.compactionOf(L(res).row.id))));
|
|
265
265
|
r.patch("/sessions/:s/compaction", route(async (req, res) => res.json(store.setCompaction(L(res).row, req.body ?? {}))));
|
|
266
266
|
r.delete("/sessions/:s", route(async (_req, res) => res.json(await store.archive(L(res).row))));
|
|
267
|
+
|
|
268
|
+
// ------------------------------------------------------- old sessions
|
|
269
|
+
// The archive is a feature surface (policy #3): list, read a transcript,
|
|
270
|
+
// restore back to live. Nothing here deletes — deletion stays `dpi gc`.
|
|
271
|
+
r.get("/archive", route(async (_req, res) => res.json({ sessions: store.archivedList() })));
|
|
272
|
+
r.get("/archive/:id/transcript", route(async (req, res) =>
|
|
273
|
+
res.json(store.archivedTranscriptView(param(req, "id"), String(req.query.format ?? "markdown"))),
|
|
274
|
+
));
|
|
275
|
+
r.post("/archive/:id/restore", route(async (req, res) =>
|
|
276
|
+
res.status(201).json(await store.restoreArchivedSession(param(req, "id"))),
|
|
277
|
+
));
|
|
267
278
|
// One downloadable .zip: manifest + session record + every agent's transcript/config.
|
|
268
279
|
r.get("/sessions/:s/export", route(async (_req, res) => res.json(await store.exportSession(L(res).row))));
|
|
269
280
|
r.get("/sessions/:s/events", route(async (_req, res) => sessionStream(store, L(res).row, res)));
|
|
@@ -62,6 +62,14 @@ import {
|
|
|
62
62
|
type GraphTask,
|
|
63
63
|
} from "./graphs.js";
|
|
64
64
|
import { ScheduleRegistry, type ScheduleCreateInput, type ScheduleRecord } from "./schedules.js";
|
|
65
|
+
import {
|
|
66
|
+
listArchived,
|
|
67
|
+
findBundle,
|
|
68
|
+
archivedTranscript,
|
|
69
|
+
restoreArchive,
|
|
70
|
+
writeArchiveManifest,
|
|
71
|
+
type ArchivedView,
|
|
72
|
+
} from "./archived.js";
|
|
65
73
|
import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } from "./notify-sinks.js";
|
|
66
74
|
import { zipSync, type ZipEntry } from "./zip.js";
|
|
67
75
|
import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
|
|
@@ -1110,12 +1118,26 @@ export class Store {
|
|
|
1110
1118
|
this.opened.delete(row.id);
|
|
1111
1119
|
}
|
|
1112
1120
|
await mkdir(this.archiveDir, { recursive: true });
|
|
1113
|
-
const
|
|
1121
|
+
const archivedAt = Date.now();
|
|
1122
|
+
const target = join(this.archiveDir, `${row.id}-${archivedAt}`);
|
|
1114
1123
|
try {
|
|
1115
1124
|
await renamePath(dirname(row.dbPath), target);
|
|
1116
1125
|
} catch (e) {
|
|
1117
1126
|
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
|
1118
1127
|
}
|
|
1128
|
+
// The bundle keeps its identity: from now on every archive carries a
|
|
1129
|
+
// session.json so the archive stays browsable years later (old bundles
|
|
1130
|
+
// predating this are listed with a best-effort name).
|
|
1131
|
+
writeArchiveManifest(target, {
|
|
1132
|
+
sessionId: row.id,
|
|
1133
|
+
name: row.name,
|
|
1134
|
+
cwd: row.cwd,
|
|
1135
|
+
model: row.model,
|
|
1136
|
+
provider: row.provider,
|
|
1137
|
+
createdAt: row.createdAt,
|
|
1138
|
+
archivedAt,
|
|
1139
|
+
packageVersion: PACKAGE_VERSION,
|
|
1140
|
+
});
|
|
1119
1141
|
this.catalog.prepare("DELETE FROM conversation_names WHERE sessionId=?").run(row.id);
|
|
1120
1142
|
this.catalog.prepare("DELETE FROM sessions WHERE id=?").run(row.id);
|
|
1121
1143
|
this.errors.delete(row.id);
|
|
@@ -1123,6 +1145,54 @@ export class Store {
|
|
|
1123
1145
|
return { archived: target };
|
|
1124
1146
|
}
|
|
1125
1147
|
|
|
1148
|
+
/**
|
|
1149
|
+
* The old-session surface (policy #3 rationale: nothing auto-deletes, so
|
|
1150
|
+
* the archive is worth browsing). List is cheap and never throws; the
|
|
1151
|
+
* transcript/restore paths map their module errors to API faults.
|
|
1152
|
+
*/
|
|
1153
|
+
archivedList(): ArchivedView[] {
|
|
1154
|
+
return listArchived(this.archiveDir);
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
archivedTranscriptView(sessionId: string, format: string) {
|
|
1158
|
+
const bundle = findBundle(this.archiveDir, sessionId);
|
|
1159
|
+
if (!bundle) throw notFound(`no archived session ${sessionId}`);
|
|
1160
|
+
try {
|
|
1161
|
+
return archivedTranscript(bundle, format === "markdown" ? "markdown" : "json");
|
|
1162
|
+
} catch {
|
|
1163
|
+
throw notFound(`archive bundle unreadable for ${sessionId}`);
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
async restoreArchivedSession(sessionId: string): Promise<SessionSummary> {
|
|
1168
|
+
if (this.list().some((r) => r.id === sessionId))
|
|
1169
|
+
throw invalid("a live session with this id already exists");
|
|
1170
|
+
const manifest = await restoreArchive(this.archiveDir, this.options.dataDir, sessionId).catch(() => undefined);
|
|
1171
|
+
if (!manifest) throw notFound(`no archived session ${sessionId}`);
|
|
1172
|
+
const row: SessionRow = {
|
|
1173
|
+
id: manifest.sessionId,
|
|
1174
|
+
name: manifest.name || "Untitled session",
|
|
1175
|
+
cwd: manifest.cwd,
|
|
1176
|
+
dbPath: join(this.sessionsDir, manifest.sessionId, "agent.sqlite"),
|
|
1177
|
+
createdAt: manifest.createdAt,
|
|
1178
|
+
model: manifest.model,
|
|
1179
|
+
provider: manifest.provider,
|
|
1180
|
+
};
|
|
1181
|
+
this.catalog.exec("BEGIN");
|
|
1182
|
+
try {
|
|
1183
|
+
this.catalog
|
|
1184
|
+
.prepare("INSERT INTO sessions VALUES(?,?,?,?,?,?,?)")
|
|
1185
|
+
.run(row.id, row.name, row.cwd, row.dbPath, row.createdAt, row.model, row.provider);
|
|
1186
|
+
this.catalog.exec("COMMIT");
|
|
1187
|
+
} catch (e) {
|
|
1188
|
+
this.catalog.exec("ROLLBACK");
|
|
1189
|
+
throw e;
|
|
1190
|
+
}
|
|
1191
|
+
this.notify();
|
|
1192
|
+
// sessionSummary handles a not-yet-opened session (the closed-bundle path).
|
|
1193
|
+
return await this.sessionSummary(row);
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1126
1196
|
async openAgent(row: SessionRow, create = false, thinkingLevel: ThinkingLevel = "low") {
|
|
1127
1197
|
const current = this.opened.get(row.id);
|
|
1128
1198
|
if (current) return current.harness;
|