@parcha/agentrun-import 0.1.0-beta.58 → 0.1.0-beta.60
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 +111 -20
- package/dist/cli.js +23 -8
- package/dist/home.d.ts +24 -1
- package/dist/home.js +394 -146
- package/dist/index.d.ts +7 -5
- package/dist/index.js +4 -2
- package/dist/internal.d.ts +18 -0
- package/dist/internal.js +12 -0
- package/dist/lines.d.ts +24 -1
- package/dist/lines.js +135 -25
- package/dist/mirror.d.ts +13 -0
- package/dist/mirror.js +15 -0
- package/dist/pool-worker.d.ts +6 -0
- package/dist/pool-worker.js +50 -0
- package/dist/pool.d.ts +106 -0
- package/dist/pool.js +288 -0
- package/dist/price.d.ts +13 -5
- package/dist/price.js +31 -21
- package/dist/read.d.ts +14 -4
- package/dist/read.js +41 -7
- package/dist/reader.d.ts +38 -8
- package/dist/readers/claude-code.d.ts +24 -0
- package/dist/readers/claude-code.js +51 -35
- package/dist/readers/codex.d.ts +60 -1
- package/dist/readers/codex.js +494 -52
- package/dist/readers/copilot.d.ts +4 -0
- package/dist/readers/copilot.js +224 -0
- package/dist/readers/index.d.ts +2 -0
- package/dist/readers/index.js +4 -0
- package/dist/readers/line-readers.d.ts +7 -0
- package/dist/readers/line-readers.js +10 -0
- package/dist/readers/opencode.d.ts +42 -0
- package/dist/readers/opencode.js +920 -0
- package/dist/readers/pi.js +2 -2
- package/dist/record-index.d.ts +32 -1
- package/dist/record-index.js +133 -13
- package/dist/scan-wasm.d.ts +1 -0
- package/dist/scan-wasm.js +2 -0
- package/dist/scan.d.ts +21 -0
- package/dist/scan.js +164 -0
- package/dist/text.d.ts +3 -0
- package/dist/text.js +36 -2
- package/dist/types.d.ts +20 -3
- package/dist/usage.d.ts +6 -2
- package/dist/usage.js +42 -1
- package/package.json +4 -2
|
@@ -0,0 +1,920 @@
|
|
|
1
|
+
// OpenCode: the sessions it keeps under $XDG_DATA_HOME/opencode (~/.local/share/opencode without it).
|
|
2
|
+
// opencode.db (opencode-<channel>.db for a dev or preview channel, or the database OPENCODE_DB names), SQLite. A 1.x
|
|
3
|
+
// database keeps each session in `session`, its messages in `message` and their parts in `part`, each row's `data`
|
|
4
|
+
// the message or part as JSON. A 2.x database keeps its own in `session_v2`, `session_message` (one row per message,
|
|
5
|
+
// typed) and `session_part` (an assistant message's content), and the 1.x tables beside them, copied over as it opens
|
|
6
|
+
// them: a session in both is the 2.x one.
|
|
7
|
+
// storage/, the JSON OpenCode wrote before SQLite: session/<project>/<session>.json, message/<session>/<message>.json,
|
|
8
|
+
// part/<message>/<part>.json. A session a database also holds is the database's.
|
|
9
|
+
// Schema from anomalyco/opencode: v1.19.5 (packages/core/src/session/sql.ts, packages/schema/src/v1/session.ts,
|
|
10
|
+
// packages/opencode/src/storage/storage.ts) and dev at 23fd3da786 (packages/core/src/session/sql.ts,
|
|
11
|
+
// packages/schema/src/session-message.ts, packages/core/src/database/migration/). A row or file that is not JSON, or
|
|
12
|
+
// not a record known here, is passed over.
|
|
13
|
+
//
|
|
14
|
+
// A locator is one session: { file: <database>, id: <session id> }, or a storage session's own JSON file. A locator of a
|
|
15
|
+
// database with no id reads each of its sessions. The cursor is the file's device and inode, whether turns were kept,
|
|
16
|
+
// a stamp of the session's rows (each table's row count and latest time_updated, or the storage files' sizes and
|
|
17
|
+
// times), and what the read found: an unchanged session is not read again; a changed one is read again whole (a session
|
|
18
|
+
// is never read in part), going on from the same file; a replaced file is read from its start.
|
|
19
|
+
//
|
|
20
|
+
// Tokens: normalizeUsage's "opencode" format (usage.ts), told the session's OpenCode version. Each step of an assistant
|
|
21
|
+
// message is one request, its usage on the step-finish part that ends it; OpenCode keeps only the last step's tokens on
|
|
22
|
+
// the message.
|
|
23
|
+
//
|
|
24
|
+
// A fork: 2.x names its source and how far it copied (fork_session_id, fork_boundary), and its copied rows are passed
|
|
25
|
+
// over by seq. 1.x's Session.fork (packages/opencode/src/session/index.ts at v1.0.0, session/session.ts at v1.18.5)
|
|
26
|
+
// copies each message and part under new ids, keeping its time, model, tokens and cost, and names no source. So each
|
|
27
|
+
// request and prompt is also keyed by what a copy keeps (fingerprint): one the import has read already (`seen`) is a
|
|
28
|
+
// copy, counted once, in the session read first.
|
|
29
|
+
//
|
|
30
|
+
// OpenCode's claude-agent provider runs Claude Code, which writes the same requests into its own session files: each
|
|
31
|
+
// such request's content names that Claude Code session in `native.sessionID` (2.x only; the provider came after the
|
|
32
|
+
// 1.x tables). The reader keeps those requests and names the session they mirror (Mirror), for a total to set the copy
|
|
33
|
+
// aside when it reads that session too.
|
|
34
|
+
import { createHash } from "node:crypto";
|
|
35
|
+
import { lstat, readdir, readFile, stat } from "node:fs/promises";
|
|
36
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
37
|
+
import { pathToFileURL } from "node:url";
|
|
38
|
+
import { entries, rememberUser } from "../reader.js";
|
|
39
|
+
import { effortOf as effortName, FAILED, isObject, mostEffortOf, str } from "../text.js";
|
|
40
|
+
export { FAILED };
|
|
41
|
+
import { ACTIVE_GAP_MS } from "../types.js";
|
|
42
|
+
import { normalizeUsage } from "../usage.js";
|
|
43
|
+
/** A non-negative finite number: a count of tokens, a cost or a time. */
|
|
44
|
+
const num = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
|
|
45
|
+
const json = (value) => {
|
|
46
|
+
if (typeof value !== "string")
|
|
47
|
+
return undefined;
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(value);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
// "default" is OpenCode's name for no variant.
|
|
56
|
+
const effortOf = (value) => (value === "default" ? undefined : effortName(value));
|
|
57
|
+
const modelOf = (provider, model) => (str(provider) && str(model) ? `${provider}/${model}` : undefined);
|
|
58
|
+
/** A request's or prompt's key from what a 1.x fork's copy of it keeps (a request's time, model, raw tokens and cost; a
|
|
59
|
+
* prompt's time and words): `o:` and a hash, which holds no text. */
|
|
60
|
+
const fingerprint = (fields) => `o:${createHash("sha256").update(JSON.stringify(fields)).digest("hex").slice(0, 32)}`;
|
|
61
|
+
const contextOf = (seen, before, latest) => ({ seen: seen ?? new Set(), before: new Set(before), owned: new Set(), now: Date.now(), latest });
|
|
62
|
+
/** A read that ended clean (its database's look after passed, every file of it read) adds what it found to `seen`: one
|
|
63
|
+
* that fails partway adds none, as a line source's file does not. */
|
|
64
|
+
const commit = (context, out) => {
|
|
65
|
+
for (const key of context.owned)
|
|
66
|
+
context.seen.add(key);
|
|
67
|
+
return out;
|
|
68
|
+
};
|
|
69
|
+
/** What a time past now, which a clock set ahead wrote, reads as: when `file` (or its write-ahead log) was last written,
|
|
70
|
+
* never past now. The same at each look, so the session ages out as its file does: never live for ever. */
|
|
71
|
+
async function latestOf(file) {
|
|
72
|
+
const times = await Promise.all([file, `${file}-wal`].map((path) => stat(path).then((stats) => stats.mtimeMs, () => 0)));
|
|
73
|
+
return Math.min(Math.max(...times), Date.now());
|
|
74
|
+
}
|
|
75
|
+
// The title OpenCode gives a session until it writes one (a subagent's keeps it): no title.
|
|
76
|
+
const DEFAULT_TITLE = /^(?:New|Child) session - \d{4}-\d\d-\d\dT/;
|
|
77
|
+
/** One session as it is read: its turns, every request (`answers`, kept or not), the times of its records. */
|
|
78
|
+
class Reading {
|
|
79
|
+
head;
|
|
80
|
+
keep;
|
|
81
|
+
many;
|
|
82
|
+
context;
|
|
83
|
+
session;
|
|
84
|
+
answers = [];
|
|
85
|
+
times = [];
|
|
86
|
+
cost = 0;
|
|
87
|
+
unpriced = false;
|
|
88
|
+
/** `many`: the head's file holds many sessions (a database), so its locator names the session's id. */
|
|
89
|
+
constructor(head, keep, many, context) {
|
|
90
|
+
this.head = head;
|
|
91
|
+
this.keep = keep;
|
|
92
|
+
this.many = many;
|
|
93
|
+
this.context = context;
|
|
94
|
+
this.session = { source: "opencode", id: head.id, file: head.file, state: "completed", child: false, turns: [], users: 0, activeMs: 0, copies: 0 };
|
|
95
|
+
if (head.cwd)
|
|
96
|
+
this.session.cwd = head.cwd;
|
|
97
|
+
if (head.model)
|
|
98
|
+
this.session.model = head.model;
|
|
99
|
+
if (head.parent)
|
|
100
|
+
Object.assign(this.session, { child: true, parent: head.parent });
|
|
101
|
+
if (head.title && !DEFAULT_TITLE.test(head.title))
|
|
102
|
+
this.session.sourceTitle = head.title;
|
|
103
|
+
}
|
|
104
|
+
/** A time read off a row; one past now (a clock set ahead would keep the session live, and past 8.64e15 is no Date)
|
|
105
|
+
* reads as its file's last write (latestOf). */
|
|
106
|
+
when(value) {
|
|
107
|
+
const at = num(value);
|
|
108
|
+
return at === undefined ? undefined : at > this.context.now ? this.context.latest : at;
|
|
109
|
+
}
|
|
110
|
+
at(...times) {
|
|
111
|
+
for (const at of times) {
|
|
112
|
+
const time = this.when(at);
|
|
113
|
+
if (time !== undefined)
|
|
114
|
+
this.times.push(time);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
usage(tokens) {
|
|
118
|
+
return normalizeUsage("opencode", tokens, { version: this.head.version });
|
|
119
|
+
}
|
|
120
|
+
/** Whether a record keyed `key` is a copy of one the import has read (not one of this locator's own, read again). */
|
|
121
|
+
copy(key) {
|
|
122
|
+
return !this.context.before.has(key) && (this.context.seen.has(key) || this.context.owned.has(key));
|
|
123
|
+
}
|
|
124
|
+
own(key) {
|
|
125
|
+
this.context.owned.add(key);
|
|
126
|
+
}
|
|
127
|
+
/** Where the read is, to go back to (back) when what came after is a copy. */
|
|
128
|
+
mark() {
|
|
129
|
+
return { turns: this.session.turns.length, answers: this.answers.length, times: this.times.length, model: this.session.model, cwd: this.session.cwd };
|
|
130
|
+
}
|
|
131
|
+
back(mark) {
|
|
132
|
+
this.session.turns.length = mark.turns;
|
|
133
|
+
this.answers.length = mark.answers;
|
|
134
|
+
this.times.length = mark.times;
|
|
135
|
+
for (const key of ["model", "cwd"])
|
|
136
|
+
if (mark[key] === undefined)
|
|
137
|
+
delete this.session[key];
|
|
138
|
+
else
|
|
139
|
+
this.session[key] = mark[key];
|
|
140
|
+
}
|
|
141
|
+
/** Requests found copies, and their calls' results, out of the session. */
|
|
142
|
+
drop(copies) {
|
|
143
|
+
const calls = new Set([...copies].flatMap((turn) => turn.calls.map((call) => call.id)));
|
|
144
|
+
const kept = this.answers.filter((turn) => !copies.has(turn));
|
|
145
|
+
this.answers.splice(0, this.answers.length, ...kept);
|
|
146
|
+
const turns = this.session.turns.filter((turn) => !copies.has(turn) && !(turn.role === "toolResult" && calls.has(turn.callId)));
|
|
147
|
+
this.session.turns.splice(0, this.session.turns.length, ...turns);
|
|
148
|
+
}
|
|
149
|
+
add(turn) {
|
|
150
|
+
rememberUser(this.session, turn);
|
|
151
|
+
if (turn.role === "assistant")
|
|
152
|
+
this.answers.push(turn);
|
|
153
|
+
if (this.keep)
|
|
154
|
+
this.session.turns.push(turn);
|
|
155
|
+
}
|
|
156
|
+
answer(at, model, effort) {
|
|
157
|
+
if (model)
|
|
158
|
+
this.session.model = model;
|
|
159
|
+
const turn = { role: "assistant", text: "", calls: [], at, ...(model ? { model } : {}), ...(effort ? { effort } : {}) };
|
|
160
|
+
this.add(turn);
|
|
161
|
+
return turn;
|
|
162
|
+
}
|
|
163
|
+
call(turn, id, name, input) {
|
|
164
|
+
turn.calls.push({ type: "toolCall", id, name, arguments: isObject(input) && this.keep ? input : {} });
|
|
165
|
+
}
|
|
166
|
+
result(callId, name, text, isError, at) {
|
|
167
|
+
this.add({ role: "toolResult", callId, name, text, isError, at });
|
|
168
|
+
}
|
|
169
|
+
mirror(turn, link) {
|
|
170
|
+
turn.mirrors = link;
|
|
171
|
+
const links = (this.session.mirrors ??= []);
|
|
172
|
+
if (!links.some((known) => known.source === link.source && known.sessionId === link.sessionId))
|
|
173
|
+
links.push(link);
|
|
174
|
+
}
|
|
175
|
+
/** A message's cost, which the session's sums; unknown once a request with usage has none. */
|
|
176
|
+
priced(cost, used) {
|
|
177
|
+
const usd = num(cost);
|
|
178
|
+
if (usd !== undefined)
|
|
179
|
+
this.cost += usd;
|
|
180
|
+
else if (used)
|
|
181
|
+
this.unpriced = true;
|
|
182
|
+
}
|
|
183
|
+
ended(state) {
|
|
184
|
+
this.session.state = state;
|
|
185
|
+
}
|
|
186
|
+
done() {
|
|
187
|
+
const session = this.session;
|
|
188
|
+
// Without turns, no answer text nor error message: each request is kept for its counts, in the result and the cursor
|
|
189
|
+
// alike.
|
|
190
|
+
if (!this.keep)
|
|
191
|
+
for (const answer of this.answers) {
|
|
192
|
+
answer.text = "";
|
|
193
|
+
if (answer.error !== undefined)
|
|
194
|
+
answer.error = FAILED;
|
|
195
|
+
}
|
|
196
|
+
if (!this.unpriced)
|
|
197
|
+
session.costUsd = this.cost;
|
|
198
|
+
const times = this.times.sort((a, b) => a - b);
|
|
199
|
+
const first = times[0] ?? this.when(this.head.created);
|
|
200
|
+
const last = times.at(-1) ?? this.when(this.head.updated);
|
|
201
|
+
if (first !== undefined)
|
|
202
|
+
session.startedAt = new Date(first).toISOString();
|
|
203
|
+
if (last !== undefined)
|
|
204
|
+
session.endedAt = new Date(last).toISOString();
|
|
205
|
+
for (let i = 1; i < times.length; i += 1)
|
|
206
|
+
if (times[i] - times[i - 1] <= ACTIVE_GAP_MS)
|
|
207
|
+
session.activeMs += times[i] - times[i - 1];
|
|
208
|
+
const effort = mostEffortOf(session.turns);
|
|
209
|
+
if (effort)
|
|
210
|
+
session.effort = effort;
|
|
211
|
+
return { locator: this.many ? { file: this.head.file, id: session.id } : { file: this.head.file }, session, requests: this.answers };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/** A 1.x error's message ({name, data: {message}}), or a 2.x one's ({type, message}). */
|
|
215
|
+
const errorOf = (error) => isObject(error) ? (str(isObject(error.data) ? error.data.message : undefined) ?? str(error.message) ?? str(error.name) ?? str(error.type) ?? "unknown error") : undefined;
|
|
216
|
+
/** How a 1.x request's message ended by its error, if it has one: stopped (the person aborted it), else failed. None:
|
|
217
|
+
* no error. */
|
|
218
|
+
const endedBy = (info) => (isObject(info.error) && info.error.name === "MessageAbortedError" ? "stopped" : errorOf(info.error) !== undefined ? "failed" : undefined);
|
|
219
|
+
/** One 1.x session from its row or file, its messages (each with its parts) in the order OpenCode keeps them. A prompt
|
|
220
|
+
* or request a 1.x fork copied (fingerprint) that the import has read already is a copy: passed over, counted. */
|
|
221
|
+
function v1Session(reading, messages) {
|
|
222
|
+
for (const { info, parts } of messages) {
|
|
223
|
+
const time = isObject(info.time) ? info.time : {};
|
|
224
|
+
const created = reading.when(time.created) ?? 0;
|
|
225
|
+
if (info.role === "user") {
|
|
226
|
+
const text = parts
|
|
227
|
+
.filter((part) => part.type === "text" && typeof part.text === "string" && part.synthetic !== true && part.ignored !== true)
|
|
228
|
+
.map((part) => part.text)
|
|
229
|
+
.join("\n");
|
|
230
|
+
const key = fingerprint(["user", num(time.created) ?? null, text]);
|
|
231
|
+
if (reading.copy(key)) {
|
|
232
|
+
reading.session.copies += 1;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
reading.own(key);
|
|
236
|
+
reading.at(time.created, time.completed);
|
|
237
|
+
if (text)
|
|
238
|
+
reading.add({ role: "user", text, at: created, uuids: [key] });
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const mark = reading.mark();
|
|
242
|
+
reading.at(time.created, time.completed);
|
|
243
|
+
if (info.role !== "assistant")
|
|
244
|
+
continue;
|
|
245
|
+
if (!reading.session.cwd && isObject(info.path) && str(info.path.cwd))
|
|
246
|
+
reading.session.cwd = info.path.cwd;
|
|
247
|
+
const model = modelOf(info.providerID, info.modelID);
|
|
248
|
+
const effort = effortOf(info.variant);
|
|
249
|
+
// Each step is one request, its usage and cost on the step-finish part that ends it; a message with no step-finish
|
|
250
|
+
// (an older OpenCode's) is one request, its usage the message's. `raw`: each request's tokens and cost as written,
|
|
251
|
+
// what its fingerprint is of (a fork made by a later OpenCode reads its usage another way).
|
|
252
|
+
const raw = new Map();
|
|
253
|
+
let turn;
|
|
254
|
+
let turns = 0;
|
|
255
|
+
let stepped = false;
|
|
256
|
+
let last;
|
|
257
|
+
const openTurn = (at) => {
|
|
258
|
+
if (!turn) {
|
|
259
|
+
turn = last = reading.answer(turns === 0 ? created : (at ?? last?.at ?? created), model, effort);
|
|
260
|
+
turns += 1;
|
|
261
|
+
}
|
|
262
|
+
return turn;
|
|
263
|
+
};
|
|
264
|
+
for (const part of parts) {
|
|
265
|
+
const partTime = isObject(part.time) ? reading.when(part.time.start) : undefined;
|
|
266
|
+
if (part.type === "text" && typeof part.text === "string" && part.synthetic !== true && part.ignored !== true) {
|
|
267
|
+
const into = openTurn(partTime);
|
|
268
|
+
into.text = [into.text, part.text].filter(Boolean).join("\n");
|
|
269
|
+
}
|
|
270
|
+
else if (part.type === "tool" && isObject(part.state)) {
|
|
271
|
+
const state = part.state;
|
|
272
|
+
const id = String(part.callID ?? "");
|
|
273
|
+
const name = String(part.tool ?? "");
|
|
274
|
+
const span = isObject(state.time) ? state.time : {};
|
|
275
|
+
reading.at(span.start, span.end);
|
|
276
|
+
reading.call(openTurn(reading.when(span.start)), id, name, state.input);
|
|
277
|
+
const end = reading.when(span.end) ?? reading.when(span.start) ?? created;
|
|
278
|
+
if (state.status === "completed")
|
|
279
|
+
reading.result(id, name, typeof state.output === "string" ? state.output : "", false, end);
|
|
280
|
+
else if (state.status === "error")
|
|
281
|
+
reading.result(id, name, str(state.error) ?? "", true, end);
|
|
282
|
+
}
|
|
283
|
+
else if (part.type === "step-finish") {
|
|
284
|
+
stepped = true;
|
|
285
|
+
const into = openTurn();
|
|
286
|
+
raw.set(into, [part.tokens ?? null, part.cost ?? null]);
|
|
287
|
+
const usage = reading.usage(part.tokens);
|
|
288
|
+
if (usage)
|
|
289
|
+
into.usage = usage;
|
|
290
|
+
const cost = num(part.cost);
|
|
291
|
+
if (cost !== undefined)
|
|
292
|
+
into.costUsd = cost;
|
|
293
|
+
turn = undefined;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const usage = reading.usage(info.tokens);
|
|
297
|
+
if (!stepped && (turns > 0 || usage)) {
|
|
298
|
+
const into = openTurn();
|
|
299
|
+
raw.set(into, [info.tokens ?? null, info.cost ?? null]);
|
|
300
|
+
if (usage)
|
|
301
|
+
into.usage = usage;
|
|
302
|
+
const cost = num(info.cost);
|
|
303
|
+
if (cost !== undefined)
|
|
304
|
+
into.costUsd = cost;
|
|
305
|
+
}
|
|
306
|
+
const error = errorOf(info.error);
|
|
307
|
+
const aborted = endedBy(info) === "stopped";
|
|
308
|
+
if (error && !aborted)
|
|
309
|
+
(last ?? openTurn()).error = error;
|
|
310
|
+
// Each request by its fingerprint: the message's time and model, its step, its tokens and cost as written. All of
|
|
311
|
+
// them copies: the message is a fork's copy, passed over whole. Some: those are left out, the rest kept.
|
|
312
|
+
const mine = reading.answers.slice(mark.answers);
|
|
313
|
+
const keys = mine.map((answer, step) => fingerprint([num(time.created) ?? null, step, model ?? null, ...(raw.get(answer) ?? [null, null])]));
|
|
314
|
+
const copies = new Set(mine.filter((_, i) => reading.copy(keys[i])));
|
|
315
|
+
if (mine.length > 0 && copies.size === mine.length) {
|
|
316
|
+
reading.back(mark);
|
|
317
|
+
reading.session.copies += 1;
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
mine.forEach((answer, i) => {
|
|
321
|
+
if (copies.has(answer))
|
|
322
|
+
return;
|
|
323
|
+
answer.key = keys[i];
|
|
324
|
+
reading.own(keys[i]);
|
|
325
|
+
});
|
|
326
|
+
if (copies.size) {
|
|
327
|
+
reading.drop(copies);
|
|
328
|
+
reading.session.copies += copies.size;
|
|
329
|
+
// The message's cost holds the copies' too: its own requests' instead, unknown when one that used tokens has none.
|
|
330
|
+
for (const answer of mine)
|
|
331
|
+
if (!copies.has(answer))
|
|
332
|
+
reading.priced(answer.costUsd, answer.usage !== undefined);
|
|
333
|
+
}
|
|
334
|
+
else
|
|
335
|
+
reading.priced(info.cost, usage !== undefined || stepped);
|
|
336
|
+
reading.ended(endedBy(info) ?? "completed");
|
|
337
|
+
}
|
|
338
|
+
return reading.done();
|
|
339
|
+
}
|
|
340
|
+
/** A 2.x tool result's text: its content's text, a file named by its name. */
|
|
341
|
+
const contentText = (content) => Array.isArray(content)
|
|
342
|
+
? content
|
|
343
|
+
.map((item) => (isObject(item) ? (typeof item.text === "string" ? item.text : item.type === "file" ? `[file${str(item.name) ? ` ${item.name}` : ""}]` : "") : ""))
|
|
344
|
+
.filter(Boolean)
|
|
345
|
+
.join("\n")
|
|
346
|
+
: "";
|
|
347
|
+
const IDLE = { succeeded: "completed", failed: "failed", interrupted: "stopped" };
|
|
348
|
+
/** One 2.x session from its session_message rows in seq order and its session_part rows' content by message. Rows a
|
|
349
|
+
* fork copied from its source (seq up to `copiedThrough`) are copies; so is a prompt or request whose fingerprint the
|
|
350
|
+
* import has read already (a 1.x fork's copy, moved to 2.x without its source named). */
|
|
351
|
+
function v2Session(reading, rows, parts, copiedThrough) {
|
|
352
|
+
for (const row of rows) {
|
|
353
|
+
if (typeof row.seq === "number" && row.seq <= copiedThrough) {
|
|
354
|
+
reading.session.copies += 1;
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
const data = json(row.data);
|
|
358
|
+
if (!isObject(data))
|
|
359
|
+
continue;
|
|
360
|
+
const time = isObject(data.time) ? data.time : {};
|
|
361
|
+
const written = num(time.created) ?? num(row.time_created);
|
|
362
|
+
const created = reading.when(written) ?? 0;
|
|
363
|
+
const model = isObject(data.model) ? modelOf(data.model.providerID, data.model.id) : undefined;
|
|
364
|
+
const request = row.type === "assistant" || (row.type === "compaction" && data.status !== "running");
|
|
365
|
+
const used = request ? (model ?? reading.session.model) : undefined;
|
|
366
|
+
const key = row.type === "user" ? fingerprint(["user", written ?? null, typeof data.text === "string" ? data.text : null]) : request ? fingerprint([written ?? null, 0, used ?? null, data.tokens ?? null, data.cost ?? null]) : undefined;
|
|
367
|
+
if (key !== undefined) {
|
|
368
|
+
if (reading.copy(key)) {
|
|
369
|
+
reading.session.copies += 1;
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
reading.own(key);
|
|
373
|
+
}
|
|
374
|
+
reading.at(created, time.completed);
|
|
375
|
+
if (row.type === "user" && typeof data.text === "string" && data.text)
|
|
376
|
+
reading.add({ role: "user", text: data.text, at: created, uuids: [key] });
|
|
377
|
+
else if (row.type === "model-switched" && model)
|
|
378
|
+
reading.session.model = model;
|
|
379
|
+
else if (row.type === "idle" && typeof data.outcome === "string" && IDLE[data.outcome])
|
|
380
|
+
reading.ended(IDLE[data.outcome]);
|
|
381
|
+
else if (request) {
|
|
382
|
+
const turn = reading.answer(created, used, isObject(data.model) ? effortOf(data.model.variant) : undefined);
|
|
383
|
+
turn.key = key;
|
|
384
|
+
if (row.type === "compaction" && typeof data.summary === "string")
|
|
385
|
+
turn.text = data.summary;
|
|
386
|
+
const content = [...(parts.get(String(row.id)) ?? []), ...(Array.isArray(data.content) ? data.content : [])];
|
|
387
|
+
for (const item of content) {
|
|
388
|
+
if (!isObject(item))
|
|
389
|
+
continue;
|
|
390
|
+
if (item.type === "text" && typeof item.text === "string")
|
|
391
|
+
turn.text = [turn.text, item.text].filter(Boolean).join("\n");
|
|
392
|
+
else if (item.type === "tool" && isObject(item.state)) {
|
|
393
|
+
const id = String(item.id ?? "");
|
|
394
|
+
const name = String(item.name ?? "");
|
|
395
|
+
const span = isObject(item.time) ? item.time : {};
|
|
396
|
+
reading.at(span.created, span.completed);
|
|
397
|
+
reading.call(turn, id, name, item.state.input);
|
|
398
|
+
const end = reading.when(span.completed) ?? reading.when(span.created) ?? created;
|
|
399
|
+
if (item.state.status === "completed")
|
|
400
|
+
reading.result(id, name, contentText(item.state.content), false, end);
|
|
401
|
+
else if (item.state.status === "error")
|
|
402
|
+
reading.result(id, name, errorOf(item.state.error) ?? contentText(item.state.content), true, end);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
const sessionId = isObject(data.model) && data.model.providerID === "claude-agent"
|
|
406
|
+
? content.map((item) => (isObject(item) && isObject(item.native) && typeof item.native.sessionID === "string" ? item.native.sessionID.trim() : "")).find(Boolean)
|
|
407
|
+
: undefined;
|
|
408
|
+
if (sessionId)
|
|
409
|
+
reading.mirror(turn, { source: "claude-code", sessionId });
|
|
410
|
+
const usage = reading.usage(data.tokens);
|
|
411
|
+
if (usage)
|
|
412
|
+
turn.usage = usage;
|
|
413
|
+
const cost = num(data.cost);
|
|
414
|
+
if (cost !== undefined)
|
|
415
|
+
turn.costUsd = cost;
|
|
416
|
+
reading.priced(data.cost, usage !== undefined);
|
|
417
|
+
const error = errorOf(data.error);
|
|
418
|
+
if (error)
|
|
419
|
+
turn.error = error;
|
|
420
|
+
if (row.type === "assistant")
|
|
421
|
+
reading.ended(error ? "failed" : "completed");
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return reading.done();
|
|
425
|
+
}
|
|
426
|
+
/** What says whether OpenCode has a database open, and whether it wrote to it: the file's own stat, and its -wal and
|
|
427
|
+
* -shm (made as a connection opens it in WAL mode, removed as the last one closes). */
|
|
428
|
+
const lookAt = async (file) => ({
|
|
429
|
+
stats: await stat(file),
|
|
430
|
+
owned: (await Promise.all(["-wal", "-shm"].map((end) => lstat(`${file}${end}`).then(() => true, () => false)))).some(Boolean),
|
|
431
|
+
});
|
|
432
|
+
// Read through a variable: a Bun build bundles node:sqlite as missing, and Node has no bun:sqlite.
|
|
433
|
+
const BUN_SQLITE = "bun:sqlite";
|
|
434
|
+
const NODE_SQLITE = "node:sqlite";
|
|
435
|
+
/** How long a read waits on OpenCode's own write (a lock it holds) before it fails, ms; as Bun sets it. */
|
|
436
|
+
const BUSY_MS = 5000;
|
|
437
|
+
const BUSY_PRAGMA = "PRAGMA busy_timeout = 5000";
|
|
438
|
+
// SQLite's open flags: read-only, and the name a URI (file:…?immutable=1).
|
|
439
|
+
const SQLITE_OPEN_READONLY = 0x01;
|
|
440
|
+
const SQLITE_OPEN_URI = 0x40;
|
|
441
|
+
/** `file` opened read-only, waiting BUSY_MS on a lock: with Node's node:sqlite, or Bun's bun:sqlite under Bun (Bun 1.3
|
|
442
|
+
* has no node:sqlite, and its opener takes no timeout: the connection's busy_timeout, which writes nothing). A WAL
|
|
443
|
+
* database OpenCode has closed (no -wal, no -shm) is opened immutable: a read-only open of it would make both in
|
|
444
|
+
* OpenCode's folder, and leave them there, owned by whoever read. With either there, OpenCode has it open (they are
|
|
445
|
+
* its), and it is opened as OpenCode shares it. */
|
|
446
|
+
async function openDb(file, closed) {
|
|
447
|
+
let query;
|
|
448
|
+
let close;
|
|
449
|
+
let exec;
|
|
450
|
+
const url = pathToFileURL(resolve(file));
|
|
451
|
+
url.searchParams.set("immutable", "1");
|
|
452
|
+
if (process.versions.bun) {
|
|
453
|
+
const { Database } = (await import(BUN_SQLITE));
|
|
454
|
+
const db = closed ? new Database(url.href, SQLITE_OPEN_READONLY | SQLITE_OPEN_URI) : new Database(file, { readonly: true });
|
|
455
|
+
db.query(BUSY_PRAGMA).all();
|
|
456
|
+
query = (sql, params) => db.query(sql).all(...params);
|
|
457
|
+
exec = (sql) => void db.query(sql).all();
|
|
458
|
+
close = () => db.close();
|
|
459
|
+
}
|
|
460
|
+
else {
|
|
461
|
+
const { DatabaseSync } = (await import(NODE_SQLITE));
|
|
462
|
+
const db = new DatabaseSync(closed ? url : file, { readOnly: true, timeout: BUSY_MS });
|
|
463
|
+
query = (sql, params) => db.prepare(sql).all(...params);
|
|
464
|
+
exec = (sql) => db.exec(sql);
|
|
465
|
+
close = () => db.close();
|
|
466
|
+
}
|
|
467
|
+
let bytes = 0;
|
|
468
|
+
return {
|
|
469
|
+
all(sql, ...params) {
|
|
470
|
+
const rows = query(sql, params);
|
|
471
|
+
for (const row of rows)
|
|
472
|
+
if (typeof row.data === "string")
|
|
473
|
+
bytes += Buffer.byteLength(row.data);
|
|
474
|
+
return rows;
|
|
475
|
+
},
|
|
476
|
+
exec,
|
|
477
|
+
close,
|
|
478
|
+
read: () => bytes,
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
/** `use` of `file` open (openDb), then closed, every query of it in one read transaction: with OpenCode writing to it
|
|
482
|
+
* (its -wal there), each one reads the database as the first one did, never a message without the parts OpenCode wrote
|
|
483
|
+
* with it. Opened immutable, the read assumed nothing changed: one OpenCode opened or wrote meanwhile (its -wal or -shm
|
|
484
|
+
* there now, or the file's size, time or inode another) fails, never a clean read: the import names it and reads it
|
|
485
|
+
* again next time. */
|
|
486
|
+
export async function withDb(file, use) {
|
|
487
|
+
const before = await lookAt(file);
|
|
488
|
+
const db = await openDb(file, !before.owned);
|
|
489
|
+
let out;
|
|
490
|
+
try {
|
|
491
|
+
db.exec("BEGIN");
|
|
492
|
+
try {
|
|
493
|
+
out = use(db);
|
|
494
|
+
}
|
|
495
|
+
finally {
|
|
496
|
+
db.exec("COMMIT");
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
finally {
|
|
500
|
+
db.close();
|
|
501
|
+
}
|
|
502
|
+
if (!before.owned) {
|
|
503
|
+
const after = await lookAt(file);
|
|
504
|
+
if (after.owned || after.stats.size !== before.stats.size || after.stats.mtimeMs !== before.stats.mtimeMs || after.stats.ino !== before.stats.ino)
|
|
505
|
+
throw new Error(`${file} changed while it was read: OpenCode opened it`);
|
|
506
|
+
}
|
|
507
|
+
return out;
|
|
508
|
+
}
|
|
509
|
+
const headOf = (row, file) => ({
|
|
510
|
+
id: String(row.id),
|
|
511
|
+
file,
|
|
512
|
+
...(str(row.directory) ? { cwd: row.directory } : {}),
|
|
513
|
+
...(str(row.parent_id) ? { parent: row.parent_id } : {}),
|
|
514
|
+
...(str(row.title) ? { title: row.title } : {}),
|
|
515
|
+
...(str(row.version) ? { version: row.version } : {}),
|
|
516
|
+
...(num(row.time_created) !== undefined ? { created: row.time_created } : {}),
|
|
517
|
+
...(num(row.time_updated) !== undefined ? { updated: row.time_updated } : {}),
|
|
518
|
+
});
|
|
519
|
+
/** Which of a database's tables are there: its 2.x sessions, and its 1.x ones. */
|
|
520
|
+
function tablesOf(db) {
|
|
521
|
+
const all = new Set(db.all("SELECT name FROM sqlite_master WHERE type = 'table'").map((row) => String(row.name)));
|
|
522
|
+
return { v2: all.has("session_v2") && all.has("session_message"), parts2: all.has("session_part"), v1: all.has("session") && all.has("message"), parts1: all.has("part"), all };
|
|
523
|
+
}
|
|
524
|
+
/** A database's session ids, each once, with each one's last write (the latest time_updated of its rows): its 2.x
|
|
525
|
+
* sessions, then the 1.x ones it has not moved to its 2.x tables. */
|
|
526
|
+
async function sessionIds(file) {
|
|
527
|
+
return withDb(file, (db) => {
|
|
528
|
+
const tables = tablesOf(db);
|
|
529
|
+
const ids = new Map();
|
|
530
|
+
const later = (id, at) => ids.has(String(id)) && ids.set(String(id), Math.max(ids.get(String(id)), num(at) ?? 0));
|
|
531
|
+
const v2 = tables.v2 ? db.all("SELECT id, time_updated FROM session_v2 ORDER BY time_created, id") : [];
|
|
532
|
+
for (const row of v2)
|
|
533
|
+
ids.set(String(row.id), num(row.time_updated) ?? 0);
|
|
534
|
+
if (tables.v1)
|
|
535
|
+
for (const row of db.all("SELECT id, time_updated FROM session ORDER BY time_created, id"))
|
|
536
|
+
if (!ids.has(String(row.id)))
|
|
537
|
+
ids.set(String(row.id), num(row.time_updated) ?? 0);
|
|
538
|
+
// A session's messages and parts are written after its row: theirs count, in the tables its read takes.
|
|
539
|
+
const own = new Set(v2.map((row) => String(row.id)));
|
|
540
|
+
for (const [table, two] of [["session_message", true], ["session_part", true], ["message", false], ["part", false]])
|
|
541
|
+
if (tables.all.has(table))
|
|
542
|
+
for (const row of db.all(`SELECT session_id, max(time_updated) AS t FROM ${table} GROUP BY session_id`))
|
|
543
|
+
if (own.has(String(row.session_id)) === two)
|
|
544
|
+
later(row.session_id, row.t);
|
|
545
|
+
return ids;
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
// Each table's rows of one session, by the column that names it.
|
|
549
|
+
const SESSION_TABLES = [
|
|
550
|
+
["session_v2", "id"],
|
|
551
|
+
["session_message", "session_id"],
|
|
552
|
+
["session_part", "session_id"],
|
|
553
|
+
["session", "id"],
|
|
554
|
+
["message", "session_id"],
|
|
555
|
+
["part", "session_id"],
|
|
556
|
+
];
|
|
557
|
+
/** What a read of `id` (each session, without one) is of: each table's row count and latest time_updated. */
|
|
558
|
+
function stampOf(db, tables, id) {
|
|
559
|
+
return JSON.stringify(SESSION_TABLES.filter(([table]) => tables.has(table)).map(([table, column]) => {
|
|
560
|
+
const [row] = db.all(`SELECT count(*) AS n, max(time_updated) AS t FROM ${table}${id === undefined ? "" : ` WHERE ${column} = ?`}`, ...(id === undefined ? [] : [id]));
|
|
561
|
+
return [table, row?.n ?? 0, row?.t ?? null];
|
|
562
|
+
}));
|
|
563
|
+
}
|
|
564
|
+
/** The sessions of an open database: the one `id` names (none when it is not there), else each. */
|
|
565
|
+
function dbSessions(db, file, tables, keep, id, context) {
|
|
566
|
+
const out = [];
|
|
567
|
+
const read = new Set();
|
|
568
|
+
const where = id === undefined ? "" : " WHERE id = ?";
|
|
569
|
+
const by = id === undefined ? [] : [id];
|
|
570
|
+
if (tables.v2) {
|
|
571
|
+
for (const row of db.all(`SELECT * FROM session_v2${where} ORDER BY time_created, id`, ...by)) {
|
|
572
|
+
const stored = json(row.model);
|
|
573
|
+
const model = isObject(stored) ? modelOf(stored.providerID, stored.id) : undefined;
|
|
574
|
+
const head = { ...headOf(row, file), ...(model ? { model } : {}) };
|
|
575
|
+
const parts = new Map();
|
|
576
|
+
if (tables.parts2)
|
|
577
|
+
for (const part of db.all("SELECT message_id, data FROM session_part WHERE session_id = ? ORDER BY message_id, ordinal", head.id)) {
|
|
578
|
+
const data = json(part.data);
|
|
579
|
+
if (isObject(data))
|
|
580
|
+
(parts.get(String(part.message_id)) ?? parts.set(String(part.message_id), []).get(String(part.message_id))).push(data);
|
|
581
|
+
}
|
|
582
|
+
const rows = db.all("SELECT id, type, seq, time_created, data FROM session_message WHERE session_id = ? ORDER BY seq", head.id);
|
|
583
|
+
out.push(v2Session(new Reading(head, keep, true, context), rows, parts, copiedThrough(db, row)));
|
|
584
|
+
read.add(head.id);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
if (tables.v1) {
|
|
588
|
+
for (const row of db.all(`SELECT id, parent_id, directory, title, version, time_created, time_updated FROM session${where} ORDER BY time_created, id`, ...by)) {
|
|
589
|
+
const head = headOf(row, file);
|
|
590
|
+
if (read.has(head.id))
|
|
591
|
+
continue;
|
|
592
|
+
const parts = new Map();
|
|
593
|
+
if (tables.parts1)
|
|
594
|
+
for (const part of db.all("SELECT id, message_id, data FROM part WHERE session_id = ? ORDER BY id", head.id)) {
|
|
595
|
+
const data = json(part.data);
|
|
596
|
+
if (isObject(data))
|
|
597
|
+
(parts.get(String(part.message_id)) ?? parts.set(String(part.message_id), []).get(String(part.message_id))).push({ ...data, id: part.id });
|
|
598
|
+
}
|
|
599
|
+
const messages = db.all("SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created, id", head.id).flatMap((message) => {
|
|
600
|
+
const info = json(message.data);
|
|
601
|
+
return isObject(info) ? [{ info: { ...info, id: message.id }, parts: parts.get(String(message.id)) ?? [] }] : [];
|
|
602
|
+
});
|
|
603
|
+
out.push(v1Session(new Reading(head, keep, true, context), messages));
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return out;
|
|
607
|
+
}
|
|
608
|
+
/** The last seq a 2.x fork copied from its source session (fork_boundary: through or before a message of the source),
|
|
609
|
+
* -1 when it is no fork or its boundary is not found. */
|
|
610
|
+
function copiedThrough(db, row) {
|
|
611
|
+
const boundary = json(row.fork_boundary);
|
|
612
|
+
if (!str(row.fork_session_id) || !isObject(boundary) || !str(boundary.messageID))
|
|
613
|
+
return -1;
|
|
614
|
+
const [at] = db.all("SELECT seq FROM session_message WHERE session_id = ? AND id = ?", row.fork_session_id, boundary.messageID);
|
|
615
|
+
const seq = num(at?.seq);
|
|
616
|
+
if (seq === undefined)
|
|
617
|
+
return -1;
|
|
618
|
+
if (boundary.type === "through")
|
|
619
|
+
return seq;
|
|
620
|
+
if (boundary.type !== "before")
|
|
621
|
+
return -1;
|
|
622
|
+
const [before] = db.all("SELECT max(seq) AS seq FROM session_message WHERE session_id = ? AND seq < ?", row.fork_session_id, seq);
|
|
623
|
+
return num(before?.seq) ?? -1;
|
|
624
|
+
}
|
|
625
|
+
/** A file or folder gone (deleted while read, or never made): none. Any other error (no access, I/O) is the read's: a
|
|
626
|
+
* session is never read short of what it holds. */
|
|
627
|
+
const gone = (error) => {
|
|
628
|
+
const code = isObject(error) ? error.code : undefined;
|
|
629
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
630
|
+
return undefined;
|
|
631
|
+
throw error;
|
|
632
|
+
};
|
|
633
|
+
/** An OpenCode id, as its storage names a file or folder by it: one of another shape (a path's "..", a "/") names no
|
|
634
|
+
* file of the storage's, and is passed over. */
|
|
635
|
+
const SAFE_ID = /^[\w-]+$/;
|
|
636
|
+
/** The folder `names` make under `root`, each an id and a folder of its own, never a link: none when one is not. */
|
|
637
|
+
async function ownDir(root, ...names) {
|
|
638
|
+
let dir = root;
|
|
639
|
+
for (const name of names) {
|
|
640
|
+
if (!SAFE_ID.test(name))
|
|
641
|
+
return undefined;
|
|
642
|
+
dir = join(dir, name);
|
|
643
|
+
if (!(await lstat(dir).catch(gone))?.isDirectory())
|
|
644
|
+
return undefined;
|
|
645
|
+
}
|
|
646
|
+
return dir;
|
|
647
|
+
}
|
|
648
|
+
/** The JSON files in the folder `names` make under `root` (ownDir), never through a link, in name order (OpenCode's
|
|
649
|
+
* ids sort by time). */
|
|
650
|
+
async function jsonFiles(root, ...names) {
|
|
651
|
+
const dir = await ownDir(root, ...names);
|
|
652
|
+
if (dir === undefined)
|
|
653
|
+
return [];
|
|
654
|
+
return ((await readdir(dir, { withFileTypes: true }).catch(gone)) ?? [])
|
|
655
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
|
|
656
|
+
.map((entry) => join(dir, entry.name))
|
|
657
|
+
.sort();
|
|
658
|
+
}
|
|
659
|
+
/** One JSON record's file: none when it is gone or is no JSON object (a malformed record is passed over). */
|
|
660
|
+
const readJson = async (file, bytes) => {
|
|
661
|
+
const text = await readFile(file, "utf8").catch(gone);
|
|
662
|
+
if (bytes && text !== undefined)
|
|
663
|
+
bytes.n += Buffer.byteLength(text);
|
|
664
|
+
const value = json(text);
|
|
665
|
+
return isObject(value) ? value : undefined;
|
|
666
|
+
};
|
|
667
|
+
const createdOf = (info) => (isObject(info.time) ? (num(info.time.created) ?? 0) : 0);
|
|
668
|
+
/** The storage folder a session's JSON file is in (storage/session/<project>/<session>.json). */
|
|
669
|
+
const storageOf = (file) => dirname(dirname(dirname(file)));
|
|
670
|
+
/** Each session of OpenCode's JSON storage: its file and id, by the time it was made. */
|
|
671
|
+
async function storageSessions(dir) {
|
|
672
|
+
const sessions = [];
|
|
673
|
+
for (const project of await entries(join(dir, "session"))) {
|
|
674
|
+
if (!project.isDirectory())
|
|
675
|
+
continue;
|
|
676
|
+
for (const file of await jsonFiles(dir, "session", project.name).catch(() => [])) {
|
|
677
|
+
// One that cannot be read is listed by its name (OpenCode's <id>.json), so its read fails and is said.
|
|
678
|
+
const info = await readJson(file).catch(() => ({ id: basename(file, ".json") }));
|
|
679
|
+
if (info && str(info.id) && SAFE_ID.test(info.id))
|
|
680
|
+
sessions.push({ info, file });
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
sessions.sort((a, b) => createdOf(a.info) - createdOf(b.info) || String(a.info.id).localeCompare(String(b.info.id)));
|
|
684
|
+
return sessions.map(({ info, file }) => ({ file, id: info.id }));
|
|
685
|
+
}
|
|
686
|
+
/** What a read of a storage session is of: its file's, its messages' and their parts' sizes and times. */
|
|
687
|
+
async function storageStamp(file) {
|
|
688
|
+
const dir = storageOf(file);
|
|
689
|
+
const hash = createHash("sha256");
|
|
690
|
+
const add = async (path) => {
|
|
691
|
+
const stats = await stat(path).catch(() => null);
|
|
692
|
+
hash.update(`${path}\0${stats?.size ?? -1}\0${stats?.mtimeMs ?? -1}\n`);
|
|
693
|
+
};
|
|
694
|
+
await add(file);
|
|
695
|
+
for (const message of await jsonFiles(dir, "message", basename(file, ".json"))) {
|
|
696
|
+
await add(message);
|
|
697
|
+
for (const part of await jsonFiles(dir, "part", basename(message, ".json")))
|
|
698
|
+
await add(part);
|
|
699
|
+
}
|
|
700
|
+
return hash.digest("hex");
|
|
701
|
+
}
|
|
702
|
+
/** One session of the JSON storage, from its file: its messages and parts by their files' names (ownDir), never by an
|
|
703
|
+
* id a file holds. */
|
|
704
|
+
async function storageSession(file, keep, bytes, context) {
|
|
705
|
+
const info = await readJson(file, bytes);
|
|
706
|
+
if (!info || !str(info.id) || !SAFE_ID.test(info.id))
|
|
707
|
+
return [];
|
|
708
|
+
const dir = storageOf(file);
|
|
709
|
+
const time = isObject(info.time) ? info.time : {};
|
|
710
|
+
const head = headOf({ id: info.id, directory: info.directory, parent_id: info.parentID, title: info.title, version: info.version, time_created: time.created, time_updated: time.updated }, file);
|
|
711
|
+
const messages = [];
|
|
712
|
+
for (const messageFile of await jsonFiles(dir, "message", basename(file, ".json"))) {
|
|
713
|
+
const message = await readJson(messageFile, bytes);
|
|
714
|
+
if (!message || !str(message.id))
|
|
715
|
+
continue;
|
|
716
|
+
const parts = [];
|
|
717
|
+
for (const partFile of await jsonFiles(dir, "part", basename(messageFile, ".json"))) {
|
|
718
|
+
const part = await readJson(partFile, bytes);
|
|
719
|
+
if (part)
|
|
720
|
+
parts.push(part);
|
|
721
|
+
}
|
|
722
|
+
messages.push({ info: message, parts });
|
|
723
|
+
}
|
|
724
|
+
messages.sort((a, b) => createdOf(a.info) - createdOf(b.info) || String(a.info.id).localeCompare(String(b.info.id)));
|
|
725
|
+
return [v1Session(new Reading(head, keep, false, context), messages)];
|
|
726
|
+
}
|
|
727
|
+
/** Whether a locator with no id is a storage session's JSON file (storage/session/<project>/<id>.json), not a database:
|
|
728
|
+
* by its name, so a database that does not open is read as one, and its read fails. */
|
|
729
|
+
function isStorage(file) {
|
|
730
|
+
return file.endsWith(".json");
|
|
731
|
+
}
|
|
732
|
+
/** OpenCode's databases and JSON storage under `home`, as OpenCode finds them in `env`: its data folder
|
|
733
|
+
* $XDG_DATA_HOME/opencode (~/.local/share/opencode without it), opencode.db and each channel's opencode-<channel>.db in
|
|
734
|
+
* it; and first the database OPENCODE_DB names, a path as given or one relative to the data folder. OpenCode opens
|
|
735
|
+
* only that one; the ones it wrote before are still the person's history. Never through a link; a database's -wal and
|
|
736
|
+
* -shm files are its own. No env is none: the home's folder. */
|
|
737
|
+
export async function openCodeFiles(home, env = {}) {
|
|
738
|
+
const root = join(env.XDG_DATA_HOME || join(home, ".local", "share"), "opencode");
|
|
739
|
+
const dbs = (await entries(root))
|
|
740
|
+
.filter((entry) => entry.isFile() && /^opencode(?:-[\w.-]+)?\.db$/.test(entry.name))
|
|
741
|
+
.map((entry) => join(root, entry.name))
|
|
742
|
+
.sort();
|
|
743
|
+
// ":memory:" names no file, and is found as none.
|
|
744
|
+
const named = env.OPENCODE_DB ? resolve(root, env.OPENCODE_DB) : undefined;
|
|
745
|
+
if (named && !dbs.includes(named) && (await lstat(named).catch(() => null))?.isFile())
|
|
746
|
+
dbs.unshift(named);
|
|
747
|
+
const storage = join(root, "storage");
|
|
748
|
+
return (await lstat(join(storage, "session")).catch(() => null))?.isDirectory() && (await lstat(storage)).isDirectory() ? { dbs, storage } : { dbs };
|
|
749
|
+
}
|
|
750
|
+
/** Whether a 1.x message (its info and parts) is a request OpenCode has not ended: not completed, or a tool part of it
|
|
751
|
+
* pending (a permission prompt waiting) or running. One its error ended (endedBy: failed, stopped) has ended, as its
|
|
752
|
+
* read says, completed or not. */
|
|
753
|
+
const running = (info, parts) => isObject(info) &&
|
|
754
|
+
info.role === "assistant" &&
|
|
755
|
+
endedBy(info) === undefined &&
|
|
756
|
+
(!(isObject(info.time) && num(info.time.completed) !== undefined) || parts.some((part) => isObject(part) && part.type === "tool" && isObject(part.state) && (part.state.status === "pending" || part.state.status === "running")));
|
|
757
|
+
/** Whether OpenCode is running a database's session now, whatever its rows' times say (a run parked on a permission
|
|
758
|
+
* prompt writes none): a 2.x session's time_busy (set as a run starts, never cleared) after its time_idle (set as it
|
|
759
|
+
* ends), where its database has the column; a 1.x one's last message `running`. */
|
|
760
|
+
function busyIn(db, tables, id, v2) {
|
|
761
|
+
if (v2) {
|
|
762
|
+
const columns = new Set(db.all("SELECT name FROM pragma_table_info('session_v2')").map((row) => String(row.name)));
|
|
763
|
+
if (!columns.has("time_busy"))
|
|
764
|
+
return false;
|
|
765
|
+
const [row] = db.all(`SELECT time_busy, ${columns.has("time_idle") ? "time_idle" : "NULL AS time_idle"} FROM session_v2 WHERE id = ?`, id);
|
|
766
|
+
const busy = num(row?.time_busy);
|
|
767
|
+
return busy !== undefined && busy > (num(row?.time_idle) ?? -1);
|
|
768
|
+
}
|
|
769
|
+
if (!tables.all.has("message"))
|
|
770
|
+
return false;
|
|
771
|
+
const [last] = db.all("SELECT id, data FROM message WHERE session_id = ? AND json_valid(data) ORDER BY time_created DESC, id DESC LIMIT 1", id);
|
|
772
|
+
if (!last)
|
|
773
|
+
return false;
|
|
774
|
+
const parts = tables.parts1 ? db.all("SELECT data FROM part WHERE message_id = ?", String(last.id)).map((part) => json(part.data)) : [];
|
|
775
|
+
return running(json(last.data), parts);
|
|
776
|
+
}
|
|
777
|
+
/** A database session's own size, last write and parent: the bytes of its messages' and parts' data (the 2.x tables' when the
|
|
778
|
+
* session is there, else 1.x's: the rows a read of it takes) and the latest time_updated of its rows. */
|
|
779
|
+
function dbSize(db, tables, id, latest) {
|
|
780
|
+
const [v2] = tables.v2 ? db.all("SELECT parent_id, time_created FROM session_v2 WHERE id = ?", id) : [];
|
|
781
|
+
const [row] = v2 ? [v2] : tables.v1 ? db.all("SELECT parent_id, time_created FROM session WHERE id = ?", id) : [];
|
|
782
|
+
if (!row)
|
|
783
|
+
return null;
|
|
784
|
+
const data = (v2 ? ["session_message", "session_part"] : ["message", "part"]).filter((table) => tables.all.has(table));
|
|
785
|
+
const bytes = data.reduce((n, table) => n + Number(db.all(`SELECT coalesce(sum(length(CAST(data AS BLOB))), 0) AS n FROM ${table} WHERE session_id = ?`, id)[0]?.n ?? 0), 0);
|
|
786
|
+
const times = SESSION_TABLES.filter(([table]) => tables.all.has(table)).map(([table, column]) => num(db.all(`SELECT max(time_updated) AS t FROM ${table} WHERE ${column} = ?`, id)[0]?.t) ?? 0);
|
|
787
|
+
// A row written by a clock set ahead is as old as its database's last write (latestOf): not live for ever. A session
|
|
788
|
+
// OpenCode is running (busyIn) is written now.
|
|
789
|
+
const last = Math.max(0, ...times);
|
|
790
|
+
return { bytes, mtimeMs: busyIn(db, tables, id, v2 !== undefined) ? Date.now() : last > Date.now() ? latest : last, ...(str(row.parent_id) ? { parent: row.parent_id } : {}), ...(num(row.time_created) !== undefined ? { created: row.time_created } : {}) };
|
|
791
|
+
}
|
|
792
|
+
/** A storage session's size and last write: its session file's, its messages' and their parts' together, now when its
|
|
793
|
+
* last message is `running`; its parent, its session file's. */
|
|
794
|
+
async function storageSize(file) {
|
|
795
|
+
const own = await stat(file).catch(() => null);
|
|
796
|
+
if (!own)
|
|
797
|
+
return null;
|
|
798
|
+
const dir = storageOf(file);
|
|
799
|
+
// A file or folder that cannot be read leaves the size as far as it goes: the read says it.
|
|
800
|
+
const info = await readJson(file).catch(() => undefined);
|
|
801
|
+
const created = info && isObject(info.time) ? num(info.time.created) : undefined;
|
|
802
|
+
const size = { bytes: own.size, mtimeMs: own.mtimeMs, ...(info && str(info.parentID) ? { parent: info.parentID } : {}), ...(created !== undefined ? { created } : {}) };
|
|
803
|
+
const add = async (path) => {
|
|
804
|
+
const stats = await stat(path).catch(() => null);
|
|
805
|
+
if (!stats)
|
|
806
|
+
return;
|
|
807
|
+
size.bytes += stats.size;
|
|
808
|
+
size.mtimeMs = Math.max(size.mtimeMs, stats.mtimeMs);
|
|
809
|
+
};
|
|
810
|
+
const messages = await jsonFiles(dir, "message", basename(file, ".json")).catch(() => []);
|
|
811
|
+
for (const message of messages) {
|
|
812
|
+
await add(message);
|
|
813
|
+
for (const part of await jsonFiles(dir, "part", basename(message, ".json")).catch(() => []))
|
|
814
|
+
await add(part);
|
|
815
|
+
}
|
|
816
|
+
// The last message by its name (OpenCode's message ids sort by time).
|
|
817
|
+
const last = messages.at(-1);
|
|
818
|
+
if (last) {
|
|
819
|
+
const parts = await Promise.all((await jsonFiles(dir, "part", basename(last, ".json")).catch(() => [])).map((part) => readJson(part).catch(() => undefined)));
|
|
820
|
+
if (running(await readJson(last).catch(() => undefined), parts))
|
|
821
|
+
size.mtimeMs = Date.now();
|
|
822
|
+
}
|
|
823
|
+
return size;
|
|
824
|
+
}
|
|
825
|
+
/** A session read as a turns: false cursor keeps it: no prompt, title or working directory (counts, ids and paths alone),
|
|
826
|
+
* so a read resumed from it gives none of them, as a line source's does. */
|
|
827
|
+
function withoutText(found) {
|
|
828
|
+
const { firstPrompt: _prompt, titleText: _title, sourceTitle: _source, cwd: _cwd, ...session } = found.session;
|
|
829
|
+
return structuredClone({ ...found, session: session });
|
|
830
|
+
}
|
|
831
|
+
export const opencode = {
|
|
832
|
+
source: "opencode",
|
|
833
|
+
name: "OpenCode",
|
|
834
|
+
harness: "opencode",
|
|
835
|
+
/** One locator per session, each session once: the database's that wrote it last (a channel's opencode-<channel>.db
|
|
836
|
+
* may keep a stale copy of opencode.db's session; on a tie, the first, OPENCODE_DB's first), else its storage file. A
|
|
837
|
+
* database that cannot be listed is its own locator. */
|
|
838
|
+
async discover(home, env) {
|
|
839
|
+
const { dbs, storage } = await openCodeFiles(home, env);
|
|
840
|
+
const out = [];
|
|
841
|
+
const known = new Set();
|
|
842
|
+
// Each session's place in `out`, and when the database there wrote it last.
|
|
843
|
+
const at = new Map();
|
|
844
|
+
for (const file of dbs) {
|
|
845
|
+
// One that cannot be listed is its own locator, so its read fails and is said: never a database of no sessions.
|
|
846
|
+
const ids = await sessionIds(file).catch(() => undefined);
|
|
847
|
+
if (!ids)
|
|
848
|
+
out.push({ file });
|
|
849
|
+
for (const [id, updated] of ids ?? []) {
|
|
850
|
+
const held = at.get(id);
|
|
851
|
+
if (!held) {
|
|
852
|
+
known.add(id);
|
|
853
|
+
at.set(id, { index: out.length, updated });
|
|
854
|
+
out.push({ file, id });
|
|
855
|
+
}
|
|
856
|
+
else if (updated > held.updated) {
|
|
857
|
+
held.updated = updated;
|
|
858
|
+
out[held.index] = { file, id };
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
if (storage)
|
|
863
|
+
for (const { file, id } of await storageSessions(storage))
|
|
864
|
+
if (!known.has(id)) {
|
|
865
|
+
known.add(id);
|
|
866
|
+
out.push({ file });
|
|
867
|
+
}
|
|
868
|
+
return out;
|
|
869
|
+
},
|
|
870
|
+
/** Oldest session first, whichever file holds it: a 1.x fork (a newer session, whose id sorts first: OpenCode's
|
|
871
|
+
* session ids descend) holds copies of its source's records, which count in the source. One whose start is not
|
|
872
|
+
* known comes after, in the listing's order. */
|
|
873
|
+
order: (a, b) => (a.created ?? Number.MAX_SAFE_INTEGER) - (b.created ?? Number.MAX_SAFE_INTEGER),
|
|
874
|
+
/** A database's locator names its session; a storage file is OpenCode's <id>.json. */
|
|
875
|
+
idOf: ({ file, id }) => id ?? basename(file, ".json"),
|
|
876
|
+
async read(locator, cursor, { turns: keep = true, seen } = {}) {
|
|
877
|
+
const { file, id } = locator;
|
|
878
|
+
const stats = await stat(file);
|
|
879
|
+
const resumed = cursor !== undefined && cursor.source === "opencode" && cursor.keep === keep && cursor.dev === stats.dev && cursor.ino === stats.ino;
|
|
880
|
+
// A changed session read again whole: the fingerprints its last read added are its own, no copies.
|
|
881
|
+
const context = contextOf(seen, resumed ? cursor.owned : [], await latestOf(file));
|
|
882
|
+
const result = (stamp, sessions, read) => {
|
|
883
|
+
if (resumed && cursor.stamp === stamp)
|
|
884
|
+
return { sessions: structuredClone(cursor.sessions), cursor, read: 0, resumed };
|
|
885
|
+
// A record its last read held that this one does not (OpenCode deleted or changed a message): a copy of it a fork
|
|
886
|
+
// holds was the record's copy, counted nowhere, and a fresh read counts it there. Not resumed: the caller reads the
|
|
887
|
+
// source again from nothing (parseHome's readSource), as a fresh read would.
|
|
888
|
+
const lost = resumed && [...context.before].some((key) => !context.owned.has(key));
|
|
889
|
+
return { sessions, cursor: { source: "opencode", dev: stats.dev, ino: stats.ino, keep, stamp, sessions: keep ? structuredClone(sessions) : sessions.map(withoutText), owned: [...context.owned] }, read, resumed: resumed && !lost };
|
|
890
|
+
};
|
|
891
|
+
if (id === undefined && isStorage(file)) {
|
|
892
|
+
const stamp = await storageStamp(file);
|
|
893
|
+
if (resumed && cursor.stamp === stamp)
|
|
894
|
+
return result(stamp, [], 0);
|
|
895
|
+
const bytes = { n: 0 };
|
|
896
|
+
return commit(context, result(stamp, await storageSession(file, keep, bytes, context), bytes.n));
|
|
897
|
+
}
|
|
898
|
+
return commit(context, await withDb(file, (db) => {
|
|
899
|
+
const tables = tablesOf(db);
|
|
900
|
+
const stamp = stampOf(db, tables.all, id);
|
|
901
|
+
if (resumed && cursor.stamp === stamp)
|
|
902
|
+
return result(stamp, [], 0);
|
|
903
|
+
const before = db.read();
|
|
904
|
+
const sessions = dbSessions(db, file, tables, keep, id, context);
|
|
905
|
+
return result(stamp, sessions, db.read() - before);
|
|
906
|
+
}));
|
|
907
|
+
},
|
|
908
|
+
/** A database session's own (dbSize), not its database's: one live session leaves the others importable, and none
|
|
909
|
+
* is too large for the size of the rest. A storage session's files together; a database without an id, its file's. */
|
|
910
|
+
async stat({ file, id }) {
|
|
911
|
+
if (id === undefined && isStorage(file))
|
|
912
|
+
return storageSize(file);
|
|
913
|
+
if (id === undefined) {
|
|
914
|
+
const stats = await stat(file);
|
|
915
|
+
return { bytes: stats.size, mtimeMs: stats.mtimeMs };
|
|
916
|
+
}
|
|
917
|
+
const latest = await latestOf(file);
|
|
918
|
+
return withDb(file, (db) => dbSize(db, tablesOf(db), id, latest));
|
|
919
|
+
},
|
|
920
|
+
};
|