zidane 6.0.0 → 6.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 +27 -0
- package/dist/{acp-Irby04Us.js → acp-cfR8T19u.js} +8 -8
- package/dist/{acp-Irby04Us.js.map → acp-cfR8T19u.js.map} +1 -1
- package/dist/acp-cli.js +7 -7
- package/dist/acp-cli.js.map +1 -1
- package/dist/acp.d.ts +1 -1
- package/dist/acp.js +1 -1
- package/dist/{agent-DkSmGkDM.js → agent-DZRA7wip.js} +377 -61
- package/dist/agent-DZRA7wip.js.map +1 -0
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -1
- package/dist/{anthropic-CTHsdFG9.js → anthropic-DNJbRMUK.js} +7 -7
- package/dist/anthropic-DNJbRMUK.js.map +1 -0
- package/dist/atomic-write-B7zr1ddF.js.map +1 -1
- package/dist/{auth-BDSu_0t3.js → auth-B3cB5K6d.js} +7 -7
- package/dist/auth-B3cB5K6d.js.map +1 -0
- package/dist/cache-telemetry-BKAwsNxm.js.map +1 -1
- package/dist/chat/pure.d.ts +4 -4
- package/dist/chat/pure.js +3 -3
- package/dist/chat.d.ts +44 -21
- package/dist/chat.d.ts.map +1 -1
- package/dist/chat.js +7 -7
- package/dist/chat.js.map +1 -1
- package/dist/completion-core-CXYSVhZo.js.map +1 -1
- package/dist/context-breakdown-Dzo25N45.js.map +1 -1
- package/dist/contexts/daytona.d.ts +3 -1
- package/dist/contexts/daytona.d.ts.map +1 -1
- package/dist/contexts/daytona.js +2 -2
- package/dist/contexts/daytona.js.map +1 -1
- package/dist/contexts/docker.d.ts.map +1 -1
- package/dist/contexts/docker.js +2 -2
- package/dist/contexts/docker.js.map +1 -1
- package/dist/contexts/e2b.d.ts +3 -1
- package/dist/contexts/e2b.d.ts.map +1 -1
- package/dist/contexts/e2b.js +1 -1
- package/dist/contexts/e2b.js.map +1 -1
- package/dist/{contexts-Vone3qQQ.js → contexts-BIbcfBFH.js} +2 -2
- package/dist/contexts-BIbcfBFH.js.map +1 -0
- package/dist/contexts.js +1 -1
- package/dist/edit-utils-EGosADZq.js.map +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/eval.js +4 -3
- package/dist/eval.js.map +1 -1
- package/dist/exec-file-size-PXkr-MGA.js.map +1 -1
- package/dist/extensions.d.ts +1 -1
- package/dist/extensions.js +1 -1
- package/dist/{fetch-url-CWE8X5OD.js → fetch-url-_5WKWpbQ.js} +2 -2
- package/dist/{fetch-url-CWE8X5OD.js.map → fetch-url-_5WKWpbQ.js.map} +1 -1
- package/dist/{format-BNOXpl-1.js → format-BF745pLL.js} +9 -2
- package/dist/format-BF745pLL.js.map +1 -0
- package/dist/generate-data-WL_yGVL6.js.map +1 -1
- package/dist/hash-DJRzmcPI.js.map +1 -1
- package/dist/headless.d.ts +1 -1
- package/dist/headless.js +4 -4
- package/dist/headless.js.map +1 -1
- package/dist/{index-B8UtiZy7.d.ts → index-BGpM2YaU.d.ts} +378 -5
- package/dist/index-BGpM2YaU.d.ts.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +11 -11
- package/dist/index.js.map +1 -1
- package/dist/logger-DBX9uYOw.js.map +1 -1
- package/dist/{login-DOF8pMVM.js → login-DZLG__2f.js} +4 -3
- package/dist/{login-DOF8pMVM.js.map → login-DZLG__2f.js.map} +1 -1
- package/dist/mcp-CcvuVXB9.js.map +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/media-sniff-Bn76JxAu.js.map +1 -1
- package/dist/{messages-CwujiS74.js → messages-C5BDOjUG.js} +2 -2
- package/dist/{messages-CwujiS74.js.map → messages-C5BDOjUG.js.map} +1 -1
- package/dist/oauth-8LqbeI_Q.js.map +1 -1
- package/dist/{openai-compat-BvgYGSR1.js → openai-compat-B0kqvZqN.js} +2 -2
- package/dist/openai-compat-B0kqvZqN.js.map +1 -0
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/output/terminal.js +1 -1
- package/dist/output/terminal.js.map +1 -1
- package/dist/output-cap-kBUHBlnq.js.map +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/anthropic.js +1 -1
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/arcee.js +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/baseten.js +2 -2
- package/dist/providers/baseten.js.map +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/cerebras.js +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/local.js +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai-compat.js +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openai.js +8 -8
- package/dist/providers/openai.js.map +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/openrouter.js +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers/xai.js +1 -1
- package/dist/{providers-z6LDMAr3.js → providers-BMlrTr6a.js} +3 -3
- package/dist/{providers-z6LDMAr3.js.map → providers-BMlrTr6a.js.map} +1 -1
- package/dist/providers.d.ts +1 -1
- package/dist/providers.js +4 -4
- package/dist/read-state-Dq_TXUX1.js.map +1 -1
- package/dist/{resolve-Cr8JSL_O.js → resolve-CC8Lmwcj.js} +3 -3
- package/dist/{resolve-Cr8JSL_O.js.map → resolve-CC8Lmwcj.js.map} +1 -1
- package/dist/restate.d.ts +1 -1
- package/dist/restate.d.ts.map +1 -1
- package/dist/restate.js.map +1 -1
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/session/sqlite.d.ts.map +1 -1
- package/dist/session/sqlite.js +75 -20
- package/dist/session/sqlite.js.map +1 -1
- package/dist/{session-CsdDIPY8.js → session-CsKzK8-P.js} +3 -3
- package/dist/session-CsKzK8-P.js.map +1 -0
- package/dist/session.d.ts +2 -2
- package/dist/session.js +2 -2
- package/dist/{skills-Bsb0rvWI.js → skills-BjeXSRlQ.js} +2 -2
- package/dist/{skills-Bsb0rvWI.js.map → skills-BjeXSRlQ.js.map} +1 -1
- package/dist/skills.d.ts +1 -1
- package/dist/skills.js +2 -2
- package/dist/stdio-loader-Ce68wUmM.js.map +1 -1
- package/dist/{tool-formatters-DY0TDb1r.d.ts → tool-formatters-CMwjDvkp.d.ts} +2 -2
- package/dist/tool-formatters-CMwjDvkp.d.ts.map +1 -0
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/fetch-url.d.ts.map +1 -1
- package/dist/tools/fetch-url.js +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools/web-search.js +1 -1
- package/dist/tools/web-search.js.map +1 -1
- package/dist/tools.d.ts +2 -2
- package/dist/tools.js +2 -2
- package/dist/{transcript-anchors-DSRPWjiH.js → transcript-anchors-BTNe1OJi.js} +346 -89
- package/dist/transcript-anchors-BTNe1OJi.js.map +1 -0
- package/dist/{transcript-anchors-Cb-bDbNH.d.ts → transcript-anchors-D5wvdKQQ.d.ts} +37 -3
- package/dist/transcript-anchors-D5wvdKQQ.d.ts.map +1 -0
- package/dist/tui.d.ts +21 -6
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +497 -83
- package/dist/tui.js.map +1 -1
- package/dist/{turn-operations-Dq9Kx7m2.js → turn-operations-CEt_l3fy.js} +23 -8
- package/dist/turn-operations-CEt_l3fy.js.map +1 -0
- package/dist/{turn-operations-CgMROLsr.d.ts → turn-operations-JO5MYM9_.d.ts} +27 -9
- package/dist/turn-operations-JO5MYM9_.d.ts.map +1 -0
- package/dist/types-BIarq1qE.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/{xai-B_e6TOA8.js → xai-C_aq671K.js} +3 -3
- package/dist/{xai-B_e6TOA8.js.map → xai-C_aq671K.js.map} +1 -1
- package/docs/ARCHITECTURE.md +4 -0
- package/docs/CHAT.md +12 -10
- package/docs/SKILL.md +1 -1
- package/docs/TUI.md +3 -3
- package/package.json +2 -2
- package/dist/agent-DkSmGkDM.js.map +0 -1
- package/dist/anthropic-CTHsdFG9.js.map +0 -1
- package/dist/auth-BDSu_0t3.js.map +0 -1
- package/dist/contexts-Vone3qQQ.js.map +0 -1
- package/dist/format-BNOXpl-1.js.map +0 -1
- package/dist/index-B8UtiZy7.d.ts.map +0 -1
- package/dist/openai-compat-BvgYGSR1.js.map +0 -1
- package/dist/session-CsdDIPY8.js.map +0 -1
- package/dist/tool-formatters-DY0TDb1r.d.ts.map +0 -1
- package/dist/transcript-anchors-Cb-bDbNH.d.ts.map +0 -1
- package/dist/transcript-anchors-DSRPWjiH.js.map +0 -1
- package/dist/turn-operations-CgMROLsr.d.ts.map +0 -1
- package/dist/turn-operations-Dq9Kx7m2.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.d.ts","names":[],"sources":["../../src/session/sqlite.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"sqlite.d.ts","names":[],"sources":["../../src/session/sqlite.ts"],"mappings":";;;UA4GiB,kBAAA;;EAEf,IAAI;AAAA;AAAA,iBAGU,iBAAA,CAAkB,OAAA,EAAS,kBAAA,GAAqB,YAAY;;;;;;;;;;;iBAqtB5D,cAAA,CAAe,MAAA,WAAiB,YAAY"}
|
package/dist/session/sqlite.js
CHANGED
|
@@ -26,6 +26,7 @@ function createSqliteStore(options) {
|
|
|
26
26
|
CREATE TABLE IF NOT EXISTS turns (
|
|
27
27
|
session_id TEXT NOT NULL,
|
|
28
28
|
seq INTEGER NOT NULL,
|
|
29
|
+
role TEXT,
|
|
29
30
|
data TEXT NOT NULL,
|
|
30
31
|
PRIMARY KEY (session_id, seq),
|
|
31
32
|
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
|
|
@@ -62,7 +63,7 @@ function createSqliteStore(options) {
|
|
|
62
63
|
const stmtDelete = db.prepare("DELETE FROM sessions WHERE id = ?");
|
|
63
64
|
const stmtDeleteTurnsForSession = db.prepare("DELETE FROM turns WHERE session_id = ?");
|
|
64
65
|
const stmtDeleteRunsForSession = db.prepare("DELETE FROM runs WHERE session_id = ?");
|
|
65
|
-
const stmtInsertTurn = db.prepare("INSERT INTO turns (session_id, seq, data) VALUES (?, ?, ?)");
|
|
66
|
+
const stmtInsertTurn = db.prepare("INSERT INTO turns (session_id, seq, role, data) VALUES (?, ?, ?, ?)");
|
|
66
67
|
const stmtUpsertRun = db.prepare(`
|
|
67
68
|
INSERT INTO runs (session_id, run_id, started_at, data) VALUES (?, ?, ?, ?)
|
|
68
69
|
ON CONFLICT(session_id, run_id) DO UPDATE SET
|
|
@@ -93,7 +94,7 @@ function createSqliteStore(options) {
|
|
|
93
94
|
stmtUpsertHeader.run(session.id, session.agentId ?? null, session.projectRoot ?? null, session.status, JSON.stringify(session.metadata ?? {}), session.createdAt, session.updatedAt);
|
|
94
95
|
stmtDeleteTurnsForSession.run(session.id);
|
|
95
96
|
stmtDeleteRunsForSession.run(session.id);
|
|
96
|
-
session.turns.forEach((t, i) => stmtInsertTurn.run(session.id, i, JSON.stringify(t)));
|
|
97
|
+
session.turns.forEach((t, i) => stmtInsertTurn.run(session.id, i, t.role ?? null, JSON.stringify(t)));
|
|
97
98
|
for (const run of session.runs) stmtUpsertRun.run(session.id, run.id, run.startedAt, JSON.stringify(run));
|
|
98
99
|
});
|
|
99
100
|
const ensureHeaderSync = (sessionId) => {
|
|
@@ -105,7 +106,7 @@ function createSqliteStore(options) {
|
|
|
105
106
|
ensureHeaderSync(sessionId);
|
|
106
107
|
let nextSeq = (stmtMaxSeq.get(sessionId).m ?? -1) + 1;
|
|
107
108
|
for (const turn of turns) {
|
|
108
|
-
stmtInsertTurn.run(sessionId, nextSeq, JSON.stringify(turn));
|
|
109
|
+
stmtInsertTurn.run(sessionId, nextSeq, turn.role ?? null, JSON.stringify(turn));
|
|
109
110
|
nextSeq += 1;
|
|
110
111
|
}
|
|
111
112
|
stmtTouch.run(Date.now(), sessionId);
|
|
@@ -129,23 +130,42 @@ function createSqliteStore(options) {
|
|
|
129
130
|
stmtDelete.run(sessionId);
|
|
130
131
|
},
|
|
131
132
|
async list(filter) {
|
|
132
|
-
const
|
|
133
|
-
const
|
|
134
|
-
if (filter?.agentId) {
|
|
135
|
-
conditions.push("agent_id = ?");
|
|
136
|
-
params.push(filter.agentId);
|
|
137
|
-
}
|
|
138
|
-
if ("projectRoot" in (filter ?? {})) {
|
|
139
|
-
const v = filter.projectRoot;
|
|
140
|
-
if (v === null) conditions.push("project_root IS NULL");
|
|
141
|
-
else if (typeof v === "string") {
|
|
142
|
-
conditions.push("project_root = ?");
|
|
143
|
-
params.push(v);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
const sql = `SELECT id FROM sessions ${conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""} ORDER BY updated_at DESC ${typeof filter?.limit === "number" && filter.limit > 0 ? `LIMIT ${filter.limit}` : ""}`.replace(/\s+/g, " ").trim();
|
|
133
|
+
const { where, limit, params } = buildListFilter(filter);
|
|
134
|
+
const sql = `SELECT id FROM sessions ${where} ORDER BY updated_at DESC ${limit}`.replace(/\s+/g, " ").trim();
|
|
147
135
|
return db.query(sql).all(...params).map((r) => r.id);
|
|
148
136
|
},
|
|
137
|
+
async listMeta(filter) {
|
|
138
|
+
const { where, limit, params } = buildListFilter(filter);
|
|
139
|
+
const sql = `
|
|
140
|
+
SELECT
|
|
141
|
+
s.id,
|
|
142
|
+
s.project_root,
|
|
143
|
+
s.metadata,
|
|
144
|
+
s.updated_at,
|
|
145
|
+
(SELECT COUNT(*) FROM turns t WHERE t.session_id = s.id) AS turn_count,
|
|
146
|
+
(SELECT COUNT(*) FROM turns t WHERE t.session_id = s.id AND t.role = 'user') AS user_count,
|
|
147
|
+
(SELECT COUNT(*) FROM runs r WHERE r.session_id = s.id) AS run_count,
|
|
148
|
+
CASE WHEN json_valid(s.metadata)
|
|
149
|
+
AND TRIM(COALESCE(json_extract(s.metadata, '$.title'), '')) <> '' THEN NULL
|
|
150
|
+
ELSE (SELECT t.data FROM turns t WHERE t.session_id = s.id AND t.role = 'user'
|
|
151
|
+
ORDER BY t.seq LIMIT 1)
|
|
152
|
+
END AS first_user_turn
|
|
153
|
+
FROM sessions s ${where} ORDER BY s.updated_at DESC ${limit}
|
|
154
|
+
`;
|
|
155
|
+
return db.query(sql).all(...params).map((r) => {
|
|
156
|
+
const firstUserTurn = r.first_user_turn ? safeParseRow(r.first_user_turn, r.id, "turn") : null;
|
|
157
|
+
return {
|
|
158
|
+
id: r.id,
|
|
159
|
+
metadata: safeParseRecord(r.metadata),
|
|
160
|
+
...r.project_root ? { projectRoot: r.project_root } : {},
|
|
161
|
+
updatedAt: r.updated_at,
|
|
162
|
+
turnCount: r.turn_count,
|
|
163
|
+
userMessageCount: r.user_count,
|
|
164
|
+
runCount: r.run_count,
|
|
165
|
+
...firstUserTurn ? { firstUserTurn } : {}
|
|
166
|
+
};
|
|
167
|
+
});
|
|
168
|
+
},
|
|
149
169
|
async appendTurns(sessionId, turns) {
|
|
150
170
|
txnAppendTurns.immediate(sessionId, turns);
|
|
151
171
|
},
|
|
@@ -184,7 +204,7 @@ function createSqliteStore(options) {
|
|
|
184
204
|
*/
|
|
185
205
|
function migrate(db, dbPath) {
|
|
186
206
|
const onDiskVersion = db.query("PRAGMA user_version").get()?.user_version ?? 0;
|
|
187
|
-
if (onDiskVersion > SCHEMA_VERSION) throw new Error(`[zidane/sqlite] "${dbPath}" has schema version ${onDiskVersion}, but this zidane build only supports up to ${SCHEMA_VERSION}. It was written by a newer zidane — upgrade zidane, or point this build at a different sessions DB.`);
|
|
207
|
+
if (onDiskVersion > SCHEMA_VERSION && onDiskVersion !== 5) throw new Error(`[zidane/sqlite] "${dbPath}" has schema version ${onDiskVersion}, but this zidane build only supports up to ${SCHEMA_VERSION}. It was written by a newer zidane — upgrade zidane, or point this build at a different sessions DB.`);
|
|
188
208
|
const sessionCols = db.query("PRAGMA table_info(sessions)").all();
|
|
189
209
|
const hasCol = (n) => sessionCols.some((c) => c.name === n);
|
|
190
210
|
if (!hasCol("project_root")) db.run("ALTER TABLE sessions ADD COLUMN project_root TEXT");
|
|
@@ -199,7 +219,11 @@ function migrate(db, dbPath) {
|
|
|
199
219
|
throw new Error(`[zidane/sqlite] v3→v4 migration could not drop legacy "data" column: ${errorMessage(err)}. Restore from "${dbPath}.zidane-pre-v4.bak" with an older zidane build and report this — your sessions are intact in the backup file.`);
|
|
200
220
|
}
|
|
201
221
|
}
|
|
202
|
-
if (
|
|
222
|
+
if (!db.query("PRAGMA table_info(turns)").all().some((c) => c.name === "role")) db.run("ALTER TABLE turns ADD COLUMN role TEXT");
|
|
223
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_turns_role_null ON turns(session_id) WHERE role IS NULL");
|
|
224
|
+
if (db.query(`SELECT 1 FROM turns WHERE role IS NULL AND json_valid(data) LIMIT 1`).get()) db.run(`UPDATE turns SET role = json_extract(data, '$.role') WHERE role IS NULL AND json_valid(data)`);
|
|
225
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_turns_session_role ON turns(session_id, role, seq)");
|
|
226
|
+
if ((db.query("PRAGMA user_version").get()?.user_version ?? 0) !== SCHEMA_VERSION) db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`);
|
|
203
227
|
}
|
|
204
228
|
/**
|
|
205
229
|
* Pre-migration safety net for v3 → v4: copy the source DB file to
|
|
@@ -294,6 +318,37 @@ function backfillV3Blobs(db) {
|
|
|
294
318
|
}
|
|
295
319
|
}
|
|
296
320
|
/**
|
|
321
|
+
* Compose the WHERE / LIMIT fragments shared by `list` and `listMeta`.
|
|
322
|
+
*
|
|
323
|
+
* `projectRoot: string` → `WHERE project_root = ?` (excludes untagged).
|
|
324
|
+
* `projectRoot: null` → `WHERE project_root IS NULL` (untagged only).
|
|
325
|
+
* `projectRoot: undefined` → axis omitted (untagged + tagged).
|
|
326
|
+
*
|
|
327
|
+
* The `null` case lets a future "show legacy" debug toggle query pre-v3
|
|
328
|
+
* sessions explicitly without leaking them into normal per-project lists.
|
|
329
|
+
*/
|
|
330
|
+
function buildListFilter(filter) {
|
|
331
|
+
const conditions = [];
|
|
332
|
+
const params = [];
|
|
333
|
+
if (filter?.agentId) {
|
|
334
|
+
conditions.push("agent_id = ?");
|
|
335
|
+
params.push(filter.agentId);
|
|
336
|
+
}
|
|
337
|
+
if ("projectRoot" in (filter ?? {})) {
|
|
338
|
+
const v = filter.projectRoot;
|
|
339
|
+
if (v === null) conditions.push("project_root IS NULL");
|
|
340
|
+
else if (typeof v === "string") {
|
|
341
|
+
conditions.push("project_root = ?");
|
|
342
|
+
params.push(v);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return {
|
|
346
|
+
where: conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "",
|
|
347
|
+
limit: typeof filter?.limit === "number" && filter.limit > 0 ? `LIMIT ${filter.limit}` : "",
|
|
348
|
+
params
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
297
352
|
* Guarded per-row parse for `turns.data` / `runs.data`. One corrupt row
|
|
298
353
|
* (truncated write, hand-edited DB, disk bitflip) must not make the whole
|
|
299
354
|
* session unloadable — log + skip it instead, mirroring the migration's
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.js","names":[],"sources":["../../src/session/sqlite.ts"],"sourcesContent":["/**\n * SQLite session store using Bun's built-in bun:sqlite.\n *\n * Schema v4 — normalized\n * ----------------------\n *\n * Three tables: `sessions` (one row per session, holds the header fields),\n * `turns` (one row per turn, ordered by `(session_id, seq)`), and `runs`\n * (one row per run, keyed by `(session_id, run_id)`). Replaces the v3\n * \"fat blob\" shape where the entire `SessionData` — including every turn\n * and every run — lived in a single TEXT column.\n *\n * The normalization removes a write-amplification anti-pattern that bit\n * long sessions hard: every `appendTurns` previously re-read the full\n * document, mutated the parsed object in memory, and serialized the\n * whole thing back. At turn N the per-call work was O(N) bytes; a 5000-\n * turn session paid multi-MB JSON.stringify on every assistant turn.\n * The new shape makes:\n *\n * - `appendTurns` a pure `INSERT INTO turns` per turn (O(1) per row,\n * plus one `MAX(seq)` lookup at the start of the call).\n * - `updateRun` an `INSERT OR UPDATE ON CONFLICT` against `runs` —\n * the upsert semantic the v3 code carefully simulated in JS is now\n * the row PK's natural behavior.\n * - `updateStatus` a single-column `UPDATE` against the sessions row\n * instead of a full read-mutate-write cycle.\n * - `getTurns(from, limit)` an indexed `LIMIT/OFFSET` range scan\n * instead of \"parse full doc, slice\".\n *\n * Concurrency model\n * -----------------\n * Mutations still run inside `BEGIN IMMEDIATE` transactions via\n * `db.transaction(fn).immediate(...)` — IMMEDIATE acquires the database-\n * level write lock at `BEGIN`, so two concurrent writers serialize on\n * the transaction boundary. WAL mode (set on connection open) lets\n * readers see committed data without blocking the writer.\n *\n * `delete(sessionId)` relies on `PRAGMA foreign_keys = ON` to cascade\n * `sessions` → `turns` / `runs` via ON DELETE CASCADE. The pragma is\n * per-connection; it's set at connection open.\n *\n * Schema versioning\n * -----------------\n * `PRAGMA user_version` tracks the current shape:\n *\n * 1 — initial schema (sessions table, no version pragma)\n * 2 — `parentRunId` / `depth` on runs; cache-aware `totalUsage` fields\n * 3 — `project_root` column + index\n * 4 — normalized layout (this file). `data` blob column dropped,\n * header fields promoted (`status`, `metadata`), turns + runs\n * split into dedicated tables. v3→v4 migration runs in-place at\n * connection open: existing blobs are parsed and fanned out, then\n * the legacy `data` column is dropped (SQLite 3.35+).\n *\n * Safety net for v3 → v4\n * ----------------------\n * Before the first destructive change (column drop, data fan-out), the\n * migration copies the source DB file to `<path>.zidane-pre-v4.bak` and\n * checkpoints WAL so the snapshot is point-in-time consistent. A user\n * who hits a regression can restore by copying that file back over\n * `sessions.db` (with the old `zidane` version) without any data loss.\n * The backup is created once and never overwritten — re-runs of the\n * migration (idempotent path) reuse the existing snapshot.\n *\n * Per-row backfill failures (corrupt JSON inside one session's blob)\n * are logged + skipped rather than aborting the whole DB; the .bak\n * file remains the recovery path for those individual rows.\n *\n * Forward-only migrations: we never roll back. Hosts pinning an older\n * `zidane` against a v4 db would fail to read the (now-missing) `data`\n * column — same forward-compat policy as the rest of the project. The\n * `.zidane-pre-v4.bak` snapshot is the explicit escape hatch for that\n * downgrade case.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\nimport { copyFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { Database } from 'bun:sqlite'\nimport { errorMessage } from '../errors'\n\nconst SCHEMA_VERSION = 4\n\nexport interface SqliteStoreOptions {\n /** Path to the SQLite database file */\n path: string\n}\n\nexport function createSqliteStore(options: SqliteStoreOptions): SessionStore {\n const db = new Database(options.path)\n\n // `busy_timeout` BEFORE any other PRAGMA so the very first DDL /\n // mode-change tolerates a brief lock held by another writer rather\n // than throwing \"database is locked\" instantly. Real scenarios this\n // covers:\n //\n // - `bun --watch` dev loops where the prior process hasn't fully\n // released the WAL / -shm sidecars at the moment the restart\n // re-opens the file.\n // - A second zidane TUI booted before the first one finished\n // shutting down (rare, but `bun:sqlite` won't retry on its own).\n // - The v3→v4 migration's `wal_checkpoint(TRUNCATE)` racing a\n // stale background connection.\n //\n // 5s is generous enough that an actual zombie process is obvious to\n // the operator (they can Ctrl+C) while still erring on the side of\n // \"just work\" for the dev-loop case.\n db.run('PRAGMA busy_timeout = 5000')\n\n // WAL gives concurrent reads while a writer holds the lock; `BEGIN\n // IMMEDIATE` below still serializes writers among themselves.\n db.run('PRAGMA journal_mode = WAL')\n // Required for the ON DELETE CASCADE from `sessions` to `turns` / `runs`.\n // Per-connection setting; cheap idempotent call at open.\n db.run('PRAGMA foreign_keys = ON')\n\n // ------------------------------------------------------------------\n // Schema (v4 shape). `CREATE TABLE IF NOT EXISTS` is a no-op on\n // pre-existing v3 databases; the migrate() call below brings them\n // forward via `ALTER TABLE ADD COLUMN` + data backfill.\n // ------------------------------------------------------------------\n db.run(`\n CREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n agent_id TEXT,\n project_root TEXT,\n status TEXT NOT NULL DEFAULT 'idle',\n metadata TEXT NOT NULL DEFAULT '{}',\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )\n `)\n db.run(`CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id)`)\n db.run(`CREATE INDEX IF NOT EXISTS idx_sessions_project_root ON sessions(project_root)`)\n\n // Per-turn rows. `(session_id, seq)` PK + `ORDER BY seq` reads give\n // O(log n) ordered access and O(1) appends. Cascade so `delete()` on\n // sessions clears these rows in one statement.\n db.run(`\n CREATE TABLE IF NOT EXISTS turns (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n data TEXT NOT NULL,\n PRIMARY KEY (session_id, seq),\n FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE\n )\n `)\n\n // Per-run rows. `(session_id, run_id)` PK gives natural upsert via\n // `ON CONFLICT(session_id, run_id) DO UPDATE`. `started_at` lifted to\n // a column so reads can `ORDER BY` it cheaply (the wall-clock order of\n // run creation is the order the agent registered them, which is what\n // `eventsFromTurns` expects when reconstructing the run tree).\n db.run(`\n CREATE TABLE IF NOT EXISTS runs (\n session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n data TEXT NOT NULL,\n PRIMARY KEY (session_id, run_id),\n FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE\n )\n `)\n\n migrate(db, options.path)\n\n // ------------------------------------------------------------------\n // Prepared statements (hot-path queries).\n // ------------------------------------------------------------------\n const stmtLoadHeader = db.prepare(`\n SELECT id, agent_id, project_root, status, metadata, created_at, updated_at\n FROM sessions WHERE id = ?\n `)\n const stmtLoadTurns = db.prepare('SELECT data FROM turns WHERE session_id = ? ORDER BY seq')\n const stmtLoadTurnsRange = db.prepare('SELECT data FROM turns WHERE session_id = ? ORDER BY seq LIMIT ? OFFSET ?')\n const stmtLoadRuns = db.prepare('SELECT data FROM runs WHERE session_id = ? ORDER BY started_at, run_id')\n\n const stmtUpsertHeader = db.prepare(`\n INSERT INTO sessions (id, agent_id, project_root, status, metadata, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n agent_id = excluded.agent_id,\n project_root = excluded.project_root,\n status = excluded.status,\n metadata = excluded.metadata,\n updated_at = excluded.updated_at\n `)\n const stmtDelete = db.prepare('DELETE FROM sessions WHERE id = ?')\n const stmtDeleteTurnsForSession = db.prepare('DELETE FROM turns WHERE session_id = ?')\n const stmtDeleteRunsForSession = db.prepare('DELETE FROM runs WHERE session_id = ?')\n const stmtInsertTurn = db.prepare('INSERT INTO turns (session_id, seq, data) VALUES (?, ?, ?)')\n const stmtUpsertRun = db.prepare(`\n INSERT INTO runs (session_id, run_id, started_at, data) VALUES (?, ?, ?, ?)\n ON CONFLICT(session_id, run_id) DO UPDATE SET\n data = excluded.data,\n started_at = excluded.started_at\n `)\n const stmtMaxSeq = db.prepare('SELECT MAX(seq) as m FROM turns WHERE session_id = ?')\n const stmtTouch = db.prepare('UPDATE sessions SET updated_at = ? WHERE id = ?')\n const stmtUpdateStatus = db.prepare('UPDATE sessions SET status = ?, updated_at = ? WHERE id = ?')\n\n // ------------------------------------------------------------------\n // Sync helpers used inside transactions. bun:sqlite's `db.transaction(fn)`\n // requires `fn` to be sync; wrapping these as standalone helpers keeps\n // the transactional and non-transactional code paths sharing one\n // implementation.\n // ------------------------------------------------------------------\n interface HeaderRow {\n id: string\n agent_id: string | null\n project_root: string | null\n status: string\n metadata: string\n created_at: number\n updated_at: number\n }\n\n const loadSync = (sessionId: string): SessionData | null => {\n const header = stmtLoadHeader.get(sessionId) as HeaderRow | null\n if (!header)\n return null\n\n const turnRows = stmtLoadTurns.all(sessionId) as { data: string }[]\n const runRows = stmtLoadRuns.all(sessionId) as { data: string }[]\n\n return {\n id: header.id,\n ...(header.agent_id ? { agentId: header.agent_id } : {}),\n ...(header.project_root ? { projectRoot: header.project_root } : {}),\n turns: turnRows\n .map(r => safeParseRow<SessionTurn>(r.data, header.id, 'turn'))\n .filter(t => t !== null),\n runs: runRows\n .map(r => safeParseRow<SessionRun>(r.data, header.id, 'run'))\n .filter(r => r !== null),\n status: header.status as SessionData['status'],\n metadata: safeParseRecord(header.metadata),\n createdAt: header.created_at,\n updatedAt: header.updated_at,\n }\n }\n\n // ------------------------------------------------------------------\n // Mutation transactions. `.immediate(...)` acquires the write lock at\n // `BEGIN IMMEDIATE` time so two concurrent writers serialize on the\n // transaction boundary, not on the (already-too-late) save call.\n // ------------------------------------------------------------------\n const txnSave = db.transaction((session: SessionData) => {\n // Header upsert. `status` + `metadata` are now first-class columns\n // instead of nested fields in a blob; the JSON.stringify on\n // `metadata` is the only serialization we still do at this level.\n stmtUpsertHeader.run(\n session.id,\n session.agentId ?? null,\n session.projectRoot ?? null,\n session.status,\n JSON.stringify(session.metadata ?? {}),\n session.createdAt,\n session.updatedAt,\n )\n // `save()` is the bulk-overwrite path (used by compact / fork /\n // explicit consumer save). Wipe and re-insert turns + runs so the\n // on-disk state mirrors the caller's view exactly — matches the\n // v3 semantic where the whole `data` blob was replaced.\n stmtDeleteTurnsForSession.run(session.id)\n stmtDeleteRunsForSession.run(session.id)\n session.turns.forEach((t, i) => stmtInsertTurn.run(session.id, i, JSON.stringify(t)))\n for (const run of session.runs) {\n stmtUpsertRun.run(session.id, run.id, run.startedAt, JSON.stringify(run))\n }\n })\n\n // Auto-create a minimal session header when turns arrive for an id the\n // store has never seen. Mirrors the file-map store: `createSession({store})`\n // + `agent.run()` writes turns via `appendTurns` without an explicit\n // `save()` first — silently dropping those writes loses the run's history.\n // Deliberately scoped to `appendTurns` only: a late `updateRun`/\n // `updateStatus` racing a `delete()` must stay a no-op rather than\n // resurrect a ghost header row.\n const ensureHeaderSync = (sessionId: string) => {\n const header = stmtLoadHeader.get(sessionId)\n if (header)\n return\n const now = Date.now()\n stmtUpsertHeader.run(sessionId, null, null, 'idle', '{}', now, now)\n }\n\n const txnAppendTurns = db.transaction((sessionId: string, turns: SessionTurn[]) => {\n ensureHeaderSync(sessionId)\n\n const max = (stmtMaxSeq.get(sessionId) as { m: number | null }).m\n let nextSeq = (max ?? -1) + 1\n for (const turn of turns) {\n stmtInsertTurn.run(sessionId, nextSeq, JSON.stringify(turn))\n nextSeq += 1\n }\n stmtTouch.run(Date.now(), sessionId)\n })\n\n const txnUpdateRun = db.transaction((sessionId: string, run: SessionRun) => {\n // No auto-create here (see ensureHeaderSync) — unknown id is a no-op.\n const header = stmtLoadHeader.get(sessionId)\n if (!header)\n return\n // True upsert via PK constraint — the v3 code had a careful comment\n // explaining why a find-then-update would silently lose run records;\n // that whole class of bug is structurally impossible here. New ids\n // get inserted, existing ids get their JSON + started_at refreshed.\n stmtUpsertRun.run(sessionId, run.id, run.startedAt, JSON.stringify(run))\n stmtTouch.run(Date.now(), sessionId)\n })\n\n const txnUpdateStatus = db.transaction((sessionId: string, status: SessionData['status']) => {\n // UPDATE on an unknown id is naturally a no-op — no auto-create here.\n stmtUpdateStatus.run(status, Date.now(), sessionId)\n })\n\n const store: SessionStore = {\n async load(sessionId: string) {\n return loadSync(sessionId)\n },\n\n async save(session: SessionData) {\n txnSave.immediate(session)\n },\n\n async delete(sessionId: string) {\n // FK CASCADE on `turns.session_id` / `runs.session_id` clears the\n // dependent rows. Single statement, single round-trip.\n stmtDelete.run(sessionId)\n },\n\n async list(filter) {\n // Build the SQL on the fly so the filter axes compose cleanly —\n // four prepared statements collapsed into one dynamic query. The\n // shape is always `SELECT id FROM sessions [WHERE …] ORDER BY\n // updated_at DESC [LIMIT N]`; only the WHERE varies.\n //\n // `projectRoot: string` → `WHERE project_root = ?` (excludes untagged).\n // `projectRoot: null` → `WHERE project_root IS NULL` (untagged only).\n // `projectRoot: undefined` → axis omitted (untagged + tagged).\n //\n // The `null` case lets a future \"show legacy\" debug toggle query\n // pre-v3 sessions explicitly without leaking them into normal\n // per-project lists.\n const conditions: string[] = []\n const params: string[] = []\n if (filter?.agentId) {\n conditions.push('agent_id = ?')\n params.push(filter.agentId)\n }\n if ('projectRoot' in (filter ?? {})) {\n const v = filter!.projectRoot\n if (v === null) {\n conditions.push('project_root IS NULL')\n }\n else if (typeof v === 'string') {\n conditions.push('project_root = ?')\n params.push(v)\n }\n }\n const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''\n const limit = typeof filter?.limit === 'number' && filter.limit > 0 ? `LIMIT ${filter.limit}` : ''\n const sql = `SELECT id FROM sessions ${where} ORDER BY updated_at DESC ${limit}`.replace(/\\s+/g, ' ').trim()\n const rows = db.query(sql).all(...params) as { id: string }[]\n return rows.map(r => r.id)\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]) {\n txnAppendTurns.immediate(sessionId, turns)\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number) {\n // `LIMIT -1` in SQLite means \"no limit\". Use that as the sentinel\n // for `limit === undefined` so the same prepared statement covers\n // both paged and full-range reads without a second SQL.\n const lim = typeof limit === 'number' ? limit : -1\n const rows = stmtLoadTurnsRange.all(sessionId, lim, from) as { data: string }[]\n return rows\n .map(r => safeParseRow<SessionTurn>(r.data, sessionId, 'turn'))\n .filter(t => t !== null)\n },\n\n async updateRun(sessionId: string, run: SessionRun) {\n txnUpdateRun.immediate(sessionId, run)\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']) {\n txnUpdateStatus.immediate(sessionId, status)\n },\n\n close() {\n // bun:sqlite — `false` skips throwing when statements are still\n // alive; finalizers handle them. Idempotent.\n db.close(false)\n },\n }\n\n return store\n}\n\n// ---------------------------------------------------------------------------\n// Migrations\n// ---------------------------------------------------------------------------\n\n/**\n * Forward-only schema migration runner. Idempotent — every step\n * feature-detects rather than relying on the `PRAGMA user_version`\n * number alone, so a partially-migrated DB (e.g. interrupted v3→v4\n * backfill) is brought to a consistent v4 state on the next open.\n *\n * The legacy `data` column is the v3 sentinel: when present we treat\n * the DB as v3-or-older and run the backfill. Before any destructive\n * change we copy the entire DB file to `<path>.zidane-pre-v4.bak` (see\n * {@link backupBeforeV3Migration}) so the user has a guaranteed\n * recovery path if anything goes sideways.\n *\n * After backfill we attempt to drop the column (SQLite 3.35+; Bun\n * ships ≥ 3.43 so this always succeeds in practice). If it does fail,\n * we throw rather than limp along — leaving the column with `NOT NULL`\n * while the new write paths omit it would silently break every future\n * `INSERT`. The `.bak` file lets the user roll back and report the bug.\n */\nfunction migrate(db: Database, dbPath: string) {\n // Downgrade guard: refuse to open a DB written by a newer zidane. The\n // newer schema may have shapes this build doesn't understand; \"limping\n // along\" risks silently corrupting it. Forward-only policy (see header).\n const onDiskVersion = (db.query('PRAGMA user_version').get() as { user_version: number } | null)?.user_version ?? 0\n if (onDiskVersion > SCHEMA_VERSION) {\n throw new Error(\n `[zidane/sqlite] \"${dbPath}\" has schema version ${onDiskVersion}, but this zidane build only supports up to ${SCHEMA_VERSION}. `\n + `It was written by a newer zidane — upgrade zidane, or point this build at a different sessions DB.`,\n )\n }\n\n const sessionCols = db.query('PRAGMA table_info(sessions)').all() as { name: string }[]\n const hasCol = (n: string) => sessionCols.some(c => c.name === n)\n\n // v1/v2 → v3: project_root column (idempotent on fresh DBs since\n // CREATE TABLE already has it).\n if (!hasCol('project_root'))\n db.run('ALTER TABLE sessions ADD COLUMN project_root TEXT')\n\n // v3 → v4 header promotion. ADD COLUMN ... DEFAULT applies the\n // default to every existing row, so v3 sessions get a synthetic\n // 'idle' status + empty metadata until the backfill loop below\n // overwrites with the real values from the JSON blob.\n if (!hasCol('status'))\n db.run(`ALTER TABLE sessions ADD COLUMN status TEXT NOT NULL DEFAULT 'idle'`)\n if (!hasCol('metadata'))\n db.run(`ALTER TABLE sessions ADD COLUMN metadata TEXT NOT NULL DEFAULT '{}'`)\n\n // v3 → v4 row fan-out. Skip when the legacy column is gone (already\n // migrated, or fresh v4 DB).\n if (hasCol('data')) {\n // Take a point-in-time snapshot BEFORE the destructive changes\n // below. Aborts the whole migration on backup failure so the user's\n // v3 DB is never modified without a recovery path on disk.\n backupBeforeV3Migration(db, dbPath)\n backfillV3Blobs(db)\n // Drop the legacy column. Bun's SQLite is 3.51+ in practice — DROP\n // COLUMN has been supported since 3.35 (2021). If it ever did fail\n // we'd be left with a `NOT NULL data` column that the new INSERT\n // statements don't populate, making the DB unwritable. Throwing\n // here surfaces the failure immediately and points the user at the\n // backup file we just created.\n try {\n db.run('ALTER TABLE sessions DROP COLUMN data')\n }\n catch (err) {\n throw new Error(\n `[zidane/sqlite] v3→v4 migration could not drop legacy \"data\" column: ${errorMessage(err)}. `\n + `Restore from \"${dbPath}.zidane-pre-v4.bak\" with an older zidane build and report this — `\n + `your sessions are intact in the backup file.`,\n )\n }\n }\n\n const currentVersion = (db.query('PRAGMA user_version').get() as { user_version: number } | null)?.user_version ?? 0\n if (currentVersion < SCHEMA_VERSION)\n db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`)\n}\n\n/**\n * Pre-migration safety net for v3 → v4: copy the source DB file to\n * `<path>.zidane-pre-v4.bak` so the user can recover by restoring the\n * snapshot if anything in the migration goes sideways.\n *\n * - Skipped for non-filesystem paths (`:memory:`, empty string) — no\n * file to copy.\n * - Skipped when the file is missing (fresh install, never reached\n * migration territory).\n * - Skipped when the backup already exists — re-runs of the migration\n * (idempotent path) reuse the same snapshot rather than overwrite a\n * potentially-earlier good copy with a later partial state.\n * - WAL is checkpointed first so the .db file contains everything that\n * was committed up to this point (otherwise pending WAL frames would\n * be missing from the snapshot).\n * - On copy failure the whole migration is aborted with a thrown error\n * — we refuse to modify the DB without a recovery path. The user\n * sees a clear diagnostic; their sessions stay intact.\n *\n * Surfaces a one-line stderr message on success so the user knows where\n * the snapshot landed. They can delete it once they've confirmed the\n * post-migration TUI behaves correctly.\n */\nfunction backupBeforeV3Migration(db: Database, dbPath: string) {\n // `:memory:` and similar URI-shaped paths have no filesystem target.\n // bun:sqlite also accepts an empty string as a synonym for in-memory.\n if (dbPath === '' || dbPath === ':memory:' || dbPath.startsWith('file::memory:'))\n return\n\n if (!existsSync(dbPath))\n return\n\n const backupPath = `${dbPath}.zidane-pre-v4.bak`\n // Don't clobber an existing backup. The first interrupted-migration\n // attempt's snapshot is the one closest to the user's pre-zidane-v4\n // state; subsequent retries would only overwrite it with a partial\n // intermediate.\n if (existsSync(backupPath))\n return\n\n // Checkpoint WAL so the .db file contains every committed frame.\n // Without this, a backup of just the .db file would be missing\n // anything sitting in the -wal sidecar. Failure is non-fatal — an\n // empty WAL (the common case for a freshly-opened DB) returns an\n // error from TRUNCATE on some SQLite builds; we still proceed with\n // the file copy.\n let checkpointed = true\n try {\n db.run('PRAGMA wal_checkpoint(TRUNCATE)')\n }\n catch {\n // Best-effort; the copy below still captures whatever's on disk —\n // plus the WAL/SHM sidecars (copied alongside below) so the snapshot\n // stays consistent even with un-checkpointed frames.\n checkpointed = false\n }\n\n try {\n copyFileSync(dbPath, backupPath)\n if (!checkpointed) {\n // Checkpoint failed → committed frames may still live in the -wal\n // sidecar. Copy it (and -shm) next to the backup so a restore of\n // the trio is point-in-time consistent.\n for (const ext of ['-wal', '-shm']) {\n const sidecar = `${dbPath}${ext}`\n if (existsSync(sidecar))\n copyFileSync(sidecar, `${backupPath}${ext}`)\n }\n }\n process.stderr.write(\n `[zidane/sqlite] v3→v4 migration: backed up your sessions DB to \"${backupPath}\".\\n`\n + ` To roll back if anything looks wrong:\\n`\n + ` 1. quit zidane\\n`\n + ` 2. cp \"${backupPath}\" \"${dbPath}\" && rm -f \"${dbPath}-wal\" \"${dbPath}-shm\"\\n`\n + ` 3. pin an older zidane that knows the v3 schema, or upgrade to a fix\\n`\n + ` Delete the .bak once every session loads correctly.\\n`,\n )\n }\n catch (err) {\n throw new Error(\n `[zidane/sqlite] failed to back up \"${dbPath}\" before v3→v4 migration: ${errorMessage(err)}. `\n + `Refusing to modify the DB without a recovery path. Move the file aside or fix the permissions and retry.`,\n )\n }\n}\n\n/**\n * Parse each session's legacy `data` blob and fan its `turns` + `runs`\n * arrays out into the dedicated tables, then overwrite the synthetic\n * `status`/`metadata` defaults with the values from the blob.\n *\n * Skips rows that already have at least one entry in `turns` for them —\n * a previous run of this migration already landed those bytes, and\n * re-inserting them would either duplicate (if seq numbering shifted)\n * or crash on the PK. The \"header already exists, turns table populated\"\n * combination is the idempotency signal.\n *\n * Per-row failures (corrupt JSON, …) log + skip rather than abort the\n * whole migration: one bad row shouldn't prevent the rest of the DB\n * from coming forward to v4.\n */\nfunction backfillV3Blobs(db: Database) {\n // Use a raw SELECT (not a prepared statement) so the legacy column\n // reference doesn't survive in the statement cache after the column\n // is dropped at the end of `migrate()`.\n const rows = db.query('SELECT id, data FROM sessions').all() as { id: string, data: string | null }[]\n if (rows.length === 0)\n return\n\n const insertTurn = db.prepare('INSERT INTO turns (session_id, seq, data) VALUES (?, ?, ?)')\n const upsertRun = db.prepare(`\n INSERT INTO runs (session_id, run_id, started_at, data) VALUES (?, ?, ?, ?)\n ON CONFLICT(session_id, run_id) DO UPDATE SET\n data = excluded.data,\n started_at = excluded.started_at\n `)\n const updateHeader = db.prepare('UPDATE sessions SET status = ?, metadata = ? WHERE id = ?')\n const countTurns = db.prepare('SELECT COUNT(*) as c FROM turns WHERE session_id = ?')\n\n for (const row of rows) {\n if (!row.data)\n continue\n try {\n const data = JSON.parse(row.data) as Partial<SessionData>\n // Skip rows whose turns table already has content — a previous\n // partial migration already fanned this row out.\n const existing = (countTurns.get(row.id) as { c: number }).c\n if (existing > 0)\n continue\n\n const turns = Array.isArray(data.turns) ? data.turns : []\n const runs = Array.isArray(data.runs) ? data.runs : []\n const txn = db.transaction(() => {\n turns.forEach((t, i) => insertTurn.run(row.id, i, JSON.stringify(t)))\n for (const run of runs) {\n // Defensive: a corrupt run record without an id can't go into\n // the (session_id, run_id) PK. Skip rather than crash.\n if (!run || typeof run.id !== 'string')\n continue\n upsertRun.run(row.id, run.id, run.startedAt ?? 0, JSON.stringify(run))\n }\n updateHeader.run(data.status ?? 'idle', JSON.stringify(data.metadata ?? {}), row.id)\n })\n txn.immediate()\n }\n catch (err) {\n process.stderr.write(`[zidane/sqlite] v3→v4 migrate: session \"${row.id}\" skipped: ${errorMessage(err)}\\n`)\n }\n }\n}\n\n/**\n * Guarded per-row parse for `turns.data` / `runs.data`. One corrupt row\n * (truncated write, hand-edited DB, disk bitflip) must not make the whole\n * session unloadable — log + skip it instead, mirroring the migration's\n * per-row backfill policy. The structural check matches the minimal shape\n * both `SessionTurn` and `SessionRun` share (an object with a string `id`).\n */\nfunction safeParseRow<T extends { id: string }>(\n text: string,\n sessionId: string,\n kind: 'turn' | 'run',\n): T | null {\n try {\n const parsed = JSON.parse(text) as unknown\n if (\n !parsed\n || typeof parsed !== 'object'\n || Array.isArray(parsed)\n || typeof (parsed as { id?: unknown }).id !== 'string'\n ) {\n console.error(`[zidane/sqlite] session \"${sessionId}\": skipping malformed ${kind} row (not a ${kind}-shaped object)`)\n return null\n }\n return parsed as T\n }\n catch (err) {\n console.error(`[zidane/sqlite] session \"${sessionId}\": skipping corrupt ${kind} row: ${errorMessage(err)}`)\n return null\n }\n}\n\n/**\n * `JSON.parse` with a fallback to `{}` for the metadata column. v3→v4\n * migration writes well-formed JSON, fresh v4 writes go through\n * `JSON.stringify(metadata ?? {})` — but a hand-edited DB or a botched\n * external migration could leave a row with malformed JSON, and we'd\n * rather surface an empty metadata object than crash the entire load\n * path. Logged under `ZIDANE_DEBUG` so the corruption isn't fully\n * silent.\n */\nfunction safeParseRecord(text: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(text)\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : {}\n }\n catch (err) {\n if (process.env.ZIDANE_DEBUG)\n process.stderr.write(`[zidane/sqlite] metadata JSON parse failed, defaulting to {}: ${errorMessage(err)}\\n`)\n return {}\n }\n}\n\n/**\n * Convenience: open a SQLite store at `dbPath`, creating its parent\n * directory if it doesn't yet exist. Used by the TUI launcher to spin up\n * the default session store at `~/.zidane/sessions.db`.\n *\n * Lives here (and not in `chat/store.ts`) so the renderer-agnostic\n * `zidane/chat` entry stays free of `bun:sqlite` — non-Bun consumers\n * (a future GUI, an SDK) can import `zidane/chat` without pulling in the\n * Bun-only binding.\n */\nexport function createTuiStore(dbPath: string): SessionStore {\n const dir = dirname(dbPath)\n if (!existsSync(dir)) {\n try {\n mkdirSync(dir, { recursive: true })\n }\n catch (err) {\n throw new Error(\n `Could not create TUI storage directory at \"${dir}\". `\n + `Override the location via \\`runTui({ storageDir, prefix })\\` or the `\n + `\\`ZIDANE_STORAGE_DIR\\` env var. Original error: ${errorMessage(err)}`,\n )\n }\n }\n return createSqliteStore({ path: dbPath })\n}\n"],"mappings":";;;;;AAkFA,MAAM,iBAAiB;AAOvB,SAAgB,kBAAkB,SAA2C;CAC3E,MAAM,KAAK,IAAI,SAAS,QAAQ,IAAI;CAkBpC,GAAG,IAAI,4BAA4B;CAInC,GAAG,IAAI,2BAA2B;CAGlC,GAAG,IAAI,0BAA0B;CAOjC,GAAG,IAAI;;;;;;;;;;GAUN;CACD,GAAG,IAAI,wEAAwE;CAC/E,GAAG,IAAI,gFAAgF;CAKvF,GAAG,IAAI;;;;;;;;GAQN;CAOD,GAAG,IAAI;;;;;;;;;GASN;CAED,QAAQ,IAAI,QAAQ,IAAI;CAKxB,MAAM,iBAAiB,GAAG,QAAQ;;;GAGjC;CACD,MAAM,gBAAgB,GAAG,QAAQ,0DAA0D;CAC3F,MAAM,qBAAqB,GAAG,QAAQ,2EAA2E;CACjH,MAAM,eAAe,GAAG,QAAQ,wEAAwE;CAExG,MAAM,mBAAmB,GAAG,QAAQ;;;;;;;;;GASnC;CACD,MAAM,aAAa,GAAG,QAAQ,mCAAmC;CACjE,MAAM,4BAA4B,GAAG,QAAQ,wCAAwC;CACrF,MAAM,2BAA2B,GAAG,QAAQ,uCAAuC;CACnF,MAAM,iBAAiB,GAAG,QAAQ,4DAA4D;CAC9F,MAAM,gBAAgB,GAAG,QAAQ;;;;;GAK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AU,wBAAwB,KAAK,cAAc,KAAK,gBAAgB;GACpH,OAAO;EACT;EACA,OAAO;CACT,SACO,KAAK;EACV,QAAQ,MAAM,4BAA4B,UAAU,sBAAsB,KAAK,QAAQ,aAAa,GAAG,GAAG;EAC1G,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAS,gBAAgB,MAAuC;CAC9D,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;EAC9B,OAAO,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,IAChE,SACA,CAAC;CACP,SACO,KAAK;EACV,IAAI,QAAQ,IAAI,cACd,QAAQ,OAAO,MAAM,iEAAiE,aAAa,GAAG,EAAE,GAAG;EAC7G,OAAO,CAAC;CACV;AACF;;;;;;;;;;;AAYA,SAAgB,eAAe,QAA8B;CAC3D,MAAM,MAAM,QAAQ,MAAM;CAC1B,IAAI,CAAC,WAAW,GAAG,GACjB,IAAI;EACF,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;CACpC,SACO,KAAK;EACV,MAAM,IAAI,MACR,8CAA8C,IAAI,yHAEG,aAAa,GAAG,GACvE;CACF;CAEF,OAAO,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAC3C"}
|
|
1
|
+
{"version":3,"file":"sqlite.js","names":[],"sources":["../../src/session/sqlite.ts"],"sourcesContent":["/**\n * SQLite session store using Bun's built-in bun:sqlite.\n *\n * Schema v4 — normalized\n * ----------------------\n *\n * Three tables: `sessions` (one row per session, holds the header fields),\n * `turns` (one row per turn, ordered by `(session_id, seq)`), and `runs`\n * (one row per run, keyed by `(session_id, run_id)`). Replaces the v3\n * \"fat blob\" shape where the entire `SessionData` — including every turn\n * and every run — lived in a single TEXT column.\n *\n * The normalization removes a write-amplification anti-pattern that bit\n * long sessions hard: every `appendTurns` previously re-read the full\n * document, mutated the parsed object in memory, and serialized the\n * whole thing back. At turn N the per-call work was O(N) bytes; a 5000-\n * turn session paid multi-MB JSON.stringify on every assistant turn.\n * The new shape makes:\n *\n * - `appendTurns` a pure `INSERT INTO turns` per turn (O(1) per row,\n * plus one `MAX(seq)` lookup at the start of the call).\n * - `updateRun` an `INSERT OR UPDATE ON CONFLICT` against `runs` —\n * the upsert semantic the v3 code carefully simulated in JS is now\n * the row PK's natural behavior.\n * - `updateStatus` a single-column `UPDATE` against the sessions row\n * instead of a full read-mutate-write cycle.\n * - `getTurns(from, limit)` an indexed `LIMIT/OFFSET` range scan\n * instead of \"parse full doc, slice\".\n *\n * Concurrency model\n * -----------------\n * Mutations still run inside `BEGIN IMMEDIATE` transactions via\n * `db.transaction(fn).immediate(...)` — IMMEDIATE acquires the database-\n * level write lock at `BEGIN`, so two concurrent writers serialize on\n * the transaction boundary. WAL mode (set on connection open) lets\n * readers see committed data without blocking the writer.\n *\n * `delete(sessionId)` relies on `PRAGMA foreign_keys = ON` to cascade\n * `sessions` → `turns` / `runs` via ON DELETE CASCADE. The pragma is\n * per-connection; it's set at connection open.\n *\n * Schema versioning\n * -----------------\n * `PRAGMA user_version` tracks the current shape:\n *\n * 1 — initial schema (sessions table, no version pragma)\n * 2 — `parentRunId` / `depth` on runs; cache-aware `totalUsage` fields\n * 3 — `project_root` column + index\n * 4 — normalized layout (this file). `data` blob column dropped,\n * header fields promoted (`status`, `metadata`), turns + runs\n * split into dedicated tables. v3→v4 migration runs in-place at\n * connection open: existing blobs are parsed and fanned out, then\n * the legacy `data` column is dropped (SQLite 3.35+).\n *\n * Additive, UNVERSIONED enhancement on top of v4: a denormalized\n * `turns.role` column + `(session_id, role, seq)` index. Lets `listMeta`\n * count user turns and seek the title-source turn from the index alone —\n * without it the summary query has to `json_extract` every turn blob,\n * which benches slower than just loading the sessions outright.\n *\n * Deliberately NOT a version bump. `PRAGMA user_version` stays at 4\n * because plain-v4 builds read and write this DB perfectly well (their\n * explicit-column INSERTs leave `role` NULL; the index maintains itself),\n * and bumping would make them refuse the file outright — which bites\n * anyone flipping between a dev build and a released binary against the\n * same `~/.zidane/sessions.db`. Instead the column is feature-detected at\n * open and NULL roles are repaired opportunistically: a partial index\n * makes \"find un-annotated rows\" O(matching rows), so the repair is a\n * no-op read in steady state and heals whatever an older v4 build wrote\n * since the last open. Version bumps are reserved for changes an older\n * build could actually corrupt or misread.\n *\n * ⚠ Version number 5 is BURNED — the next real schema bump must use 6.\n * Short-lived dev builds (2026-07) stamped this role work as version 5\n * before it was made unversioned; the downgrade guard in `migrate()` now\n * accepts-and-re-stamps 5 as plain v4. If a future schema reused 5, those\n * repaired-DB semantics would mis-accept it.\n *\n * Safety net for v3 → v4\n * ----------------------\n * Before the first destructive change (column drop, data fan-out), the\n * migration copies the source DB file to `<path>.zidane-pre-v4.bak` and\n * checkpoints WAL so the snapshot is point-in-time consistent. A user\n * who hits a regression can restore by copying that file back over\n * `sessions.db` (with the old `zidane` version) without any data loss.\n * The backup is created once and never overwritten — re-runs of the\n * migration (idempotent path) reuse the existing snapshot.\n *\n * Per-row backfill failures (corrupt JSON inside one session's blob)\n * are logged + skipped rather than aborting the whole DB; the .bak\n * file remains the recovery path for those individual rows.\n *\n * Forward-only migrations: we never roll back. Hosts pinning an older\n * `zidane` against a v4 db would fail to read the (now-missing) `data`\n * column — same forward-compat policy as the rest of the project. The\n * `.zidane-pre-v4.bak` snapshot is the explicit escape hatch for that\n * downgrade case.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\nimport { copyFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { Database } from 'bun:sqlite'\nimport { errorMessage } from '../errors'\n\nconst SCHEMA_VERSION = 4\n\nexport interface SqliteStoreOptions {\n /** Path to the SQLite database file */\n path: string\n}\n\nexport function createSqliteStore(options: SqliteStoreOptions): SessionStore {\n const db = new Database(options.path)\n\n // `busy_timeout` BEFORE any other PRAGMA so the very first DDL /\n // mode-change tolerates a brief lock held by another writer rather\n // than throwing \"database is locked\" instantly. Real scenarios this\n // covers:\n //\n // - `bun --watch` dev loops where the prior process hasn't fully\n // released the WAL / -shm sidecars at the moment the restart\n // re-opens the file.\n // - A second zidane TUI booted before the first one finished\n // shutting down (rare, but `bun:sqlite` won't retry on its own).\n // - The v3→v4 migration's `wal_checkpoint(TRUNCATE)` racing a\n // stale background connection.\n //\n // 5s is generous enough that an actual zombie process is obvious to\n // the operator (they can Ctrl+C) while still erring on the side of\n // \"just work\" for the dev-loop case.\n db.run('PRAGMA busy_timeout = 5000')\n\n // WAL gives concurrent reads while a writer holds the lock; `BEGIN\n // IMMEDIATE` below still serializes writers among themselves.\n db.run('PRAGMA journal_mode = WAL')\n // Required for the ON DELETE CASCADE from `sessions` to `turns` / `runs`.\n // Per-connection setting; cheap idempotent call at open.\n db.run('PRAGMA foreign_keys = ON')\n\n // ------------------------------------------------------------------\n // Schema (v4 shape). `CREATE TABLE IF NOT EXISTS` is a no-op on\n // pre-existing v3 databases; the migrate() call below brings them\n // forward via `ALTER TABLE ADD COLUMN` + data backfill.\n // ------------------------------------------------------------------\n db.run(`\n CREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n agent_id TEXT,\n project_root TEXT,\n status TEXT NOT NULL DEFAULT 'idle',\n metadata TEXT NOT NULL DEFAULT '{}',\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )\n `)\n db.run(`CREATE INDEX IF NOT EXISTS idx_sessions_agent_id ON sessions(agent_id)`)\n db.run(`CREATE INDEX IF NOT EXISTS idx_sessions_project_root ON sessions(project_root)`)\n\n // Per-turn rows. `(session_id, seq)` PK + `ORDER BY seq` reads give\n // O(log n) ordered access and O(1) appends. Cascade so `delete()` on\n // sessions clears these rows in one statement.\n db.run(`\n CREATE TABLE IF NOT EXISTS turns (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n role TEXT,\n data TEXT NOT NULL,\n PRIMARY KEY (session_id, seq),\n FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE\n )\n `)\n\n // Per-run rows. `(session_id, run_id)` PK gives natural upsert via\n // `ON CONFLICT(session_id, run_id) DO UPDATE`. `started_at` lifted to\n // a column so reads can `ORDER BY` it cheaply (the wall-clock order of\n // run creation is the order the agent registered them, which is what\n // `eventsFromTurns` expects when reconstructing the run tree).\n db.run(`\n CREATE TABLE IF NOT EXISTS runs (\n session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n data TEXT NOT NULL,\n PRIMARY KEY (session_id, run_id),\n FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE\n )\n `)\n\n migrate(db, options.path)\n\n // ------------------------------------------------------------------\n // Prepared statements (hot-path queries).\n // ------------------------------------------------------------------\n const stmtLoadHeader = db.prepare(`\n SELECT id, agent_id, project_root, status, metadata, created_at, updated_at\n FROM sessions WHERE id = ?\n `)\n const stmtLoadTurns = db.prepare('SELECT data FROM turns WHERE session_id = ? ORDER BY seq')\n const stmtLoadTurnsRange = db.prepare('SELECT data FROM turns WHERE session_id = ? ORDER BY seq LIMIT ? OFFSET ?')\n const stmtLoadRuns = db.prepare('SELECT data FROM runs WHERE session_id = ? ORDER BY started_at, run_id')\n\n const stmtUpsertHeader = db.prepare(`\n INSERT INTO sessions (id, agent_id, project_root, status, metadata, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n agent_id = excluded.agent_id,\n project_root = excluded.project_root,\n status = excluded.status,\n metadata = excluded.metadata,\n updated_at = excluded.updated_at\n `)\n const stmtDelete = db.prepare('DELETE FROM sessions WHERE id = ?')\n const stmtDeleteTurnsForSession = db.prepare('DELETE FROM turns WHERE session_id = ?')\n const stmtDeleteRunsForSession = db.prepare('DELETE FROM runs WHERE session_id = ?')\n const stmtInsertTurn = db.prepare('INSERT INTO turns (session_id, seq, role, data) VALUES (?, ?, ?, ?)')\n const stmtUpsertRun = db.prepare(`\n INSERT INTO runs (session_id, run_id, started_at, data) VALUES (?, ?, ?, ?)\n ON CONFLICT(session_id, run_id) DO UPDATE SET\n data = excluded.data,\n started_at = excluded.started_at\n `)\n const stmtMaxSeq = db.prepare('SELECT MAX(seq) as m FROM turns WHERE session_id = ?')\n const stmtTouch = db.prepare('UPDATE sessions SET updated_at = ? WHERE id = ?')\n const stmtUpdateStatus = db.prepare('UPDATE sessions SET status = ?, updated_at = ? WHERE id = ?')\n\n // ------------------------------------------------------------------\n // Sync helpers used inside transactions. bun:sqlite's `db.transaction(fn)`\n // requires `fn` to be sync; wrapping these as standalone helpers keeps\n // the transactional and non-transactional code paths sharing one\n // implementation.\n // ------------------------------------------------------------------\n interface HeaderRow {\n id: string\n agent_id: string | null\n project_root: string | null\n status: string\n metadata: string\n created_at: number\n updated_at: number\n }\n\n const loadSync = (sessionId: string): SessionData | null => {\n const header = stmtLoadHeader.get(sessionId) as HeaderRow | null\n if (!header)\n return null\n\n const turnRows = stmtLoadTurns.all(sessionId) as { data: string }[]\n const runRows = stmtLoadRuns.all(sessionId) as { data: string }[]\n\n return {\n id: header.id,\n ...(header.agent_id ? { agentId: header.agent_id } : {}),\n ...(header.project_root ? { projectRoot: header.project_root } : {}),\n turns: turnRows\n .map(r => safeParseRow<SessionTurn>(r.data, header.id, 'turn'))\n .filter(t => t !== null),\n runs: runRows\n .map(r => safeParseRow<SessionRun>(r.data, header.id, 'run'))\n .filter(r => r !== null),\n status: header.status as SessionData['status'],\n metadata: safeParseRecord(header.metadata),\n createdAt: header.created_at,\n updatedAt: header.updated_at,\n }\n }\n\n // ------------------------------------------------------------------\n // Mutation transactions. `.immediate(...)` acquires the write lock at\n // `BEGIN IMMEDIATE` time so two concurrent writers serialize on the\n // transaction boundary, not on the (already-too-late) save call.\n // ------------------------------------------------------------------\n const txnSave = db.transaction((session: SessionData) => {\n // Header upsert. `status` + `metadata` are now first-class columns\n // instead of nested fields in a blob; the JSON.stringify on\n // `metadata` is the only serialization we still do at this level.\n stmtUpsertHeader.run(\n session.id,\n session.agentId ?? null,\n session.projectRoot ?? null,\n session.status,\n JSON.stringify(session.metadata ?? {}),\n session.createdAt,\n session.updatedAt,\n )\n // `save()` is the bulk-overwrite path (used by compact / fork /\n // explicit consumer save). Wipe and re-insert turns + runs so the\n // on-disk state mirrors the caller's view exactly — matches the\n // v3 semantic where the whole `data` blob was replaced.\n stmtDeleteTurnsForSession.run(session.id)\n stmtDeleteRunsForSession.run(session.id)\n session.turns.forEach((t, i) => stmtInsertTurn.run(session.id, i, t.role ?? null, JSON.stringify(t)))\n for (const run of session.runs) {\n stmtUpsertRun.run(session.id, run.id, run.startedAt, JSON.stringify(run))\n }\n })\n\n // Auto-create a minimal session header when turns arrive for an id the\n // store has never seen. Mirrors the file-map store: `createSession({store})`\n // + `agent.run()` writes turns via `appendTurns` without an explicit\n // `save()` first — silently dropping those writes loses the run's history.\n // Deliberately scoped to `appendTurns` only: a late `updateRun`/\n // `updateStatus` racing a `delete()` must stay a no-op rather than\n // resurrect a ghost header row.\n const ensureHeaderSync = (sessionId: string) => {\n const header = stmtLoadHeader.get(sessionId)\n if (header)\n return\n const now = Date.now()\n stmtUpsertHeader.run(sessionId, null, null, 'idle', '{}', now, now)\n }\n\n const txnAppendTurns = db.transaction((sessionId: string, turns: SessionTurn[]) => {\n ensureHeaderSync(sessionId)\n\n const max = (stmtMaxSeq.get(sessionId) as { m: number | null }).m\n let nextSeq = (max ?? -1) + 1\n for (const turn of turns) {\n stmtInsertTurn.run(sessionId, nextSeq, turn.role ?? null, JSON.stringify(turn))\n nextSeq += 1\n }\n stmtTouch.run(Date.now(), sessionId)\n })\n\n const txnUpdateRun = db.transaction((sessionId: string, run: SessionRun) => {\n // No auto-create here (see ensureHeaderSync) — unknown id is a no-op.\n const header = stmtLoadHeader.get(sessionId)\n if (!header)\n return\n // True upsert via PK constraint — the v3 code had a careful comment\n // explaining why a find-then-update would silently lose run records;\n // that whole class of bug is structurally impossible here. New ids\n // get inserted, existing ids get their JSON + started_at refreshed.\n stmtUpsertRun.run(sessionId, run.id, run.startedAt, JSON.stringify(run))\n stmtTouch.run(Date.now(), sessionId)\n })\n\n const txnUpdateStatus = db.transaction((sessionId: string, status: SessionData['status']) => {\n // UPDATE on an unknown id is naturally a no-op — no auto-create here.\n stmtUpdateStatus.run(status, Date.now(), sessionId)\n })\n\n const store: SessionStore = {\n async load(sessionId: string) {\n return loadSync(sessionId)\n },\n\n async save(session: SessionData) {\n txnSave.immediate(session)\n },\n\n async delete(sessionId: string) {\n // FK CASCADE on `turns.session_id` / `runs.session_id` clears the\n // dependent rows. Single statement, single round-trip.\n stmtDelete.run(sessionId)\n },\n\n async list(filter) {\n // Build the SQL on the fly so the filter axes compose cleanly —\n // four prepared statements collapsed into one dynamic query. The\n // shape is always `SELECT id FROM sessions [WHERE …] ORDER BY\n // updated_at DESC [LIMIT N]`; only the WHERE varies (see\n // `buildListFilter` for the axis semantics).\n const { where, limit, params } = buildListFilter(filter)\n const sql = `SELECT id FROM sessions ${where} ORDER BY updated_at DESC ${limit}`.replace(/\\s+/g, ' ').trim()\n const rows = db.query(sql).all(...params) as { id: string }[]\n return rows.map(r => r.id)\n },\n\n async listMeta(filter) {\n // Single-query summary path for the sessions picker. The generic\n // fallback (`list()` + `load()` per id) parses every turn of every\n // session in JS just to count rows and find the first user message\n // — O(entire database) and the dominant TUI boot cost on large\n // histories. Here every role-scoped aggregate answers from the\n // denormalized `idx_turns_session_role` index (see the \"additive\n // enhancement\" note in the header) without touching a single turn\n // blob; the only turn payload that crosses into JS is the first\n // user turn, and only for sessions with no stored title.\n // Deliberately NOT `json_extract(t.data, ...)`-based: SQLite would\n // have to parse every multi-KB blob, which benches slower than\n // just loading the sessions in JS.\n //\n // Turns appended by a plain-v4 build WHILE this connection is open\n // carry a NULL role until the next open's repair pass — their\n // sessions briefly under-count user turns in the picker. Cosmetic\n // and self-healing; not worth a per-query repair.\n const { where, limit, params } = buildListFilter(filter)\n const sql = `\n SELECT\n s.id,\n s.project_root,\n s.metadata,\n s.updated_at,\n (SELECT COUNT(*) FROM turns t WHERE t.session_id = s.id) AS turn_count,\n (SELECT COUNT(*) FROM turns t WHERE t.session_id = s.id AND t.role = 'user') AS user_count,\n (SELECT COUNT(*) FROM runs r WHERE r.session_id = s.id) AS run_count,\n CASE WHEN json_valid(s.metadata)\n AND TRIM(COALESCE(json_extract(s.metadata, '$.title'), '')) <> '' THEN NULL\n ELSE (SELECT t.data FROM turns t WHERE t.session_id = s.id AND t.role = 'user'\n ORDER BY t.seq LIMIT 1)\n END AS first_user_turn\n FROM sessions s ${where} ORDER BY s.updated_at DESC ${limit}\n `\n interface MetaQueryRow {\n id: string\n project_root: string | null\n metadata: string\n updated_at: number\n turn_count: number\n user_count: number\n run_count: number\n first_user_turn: string | null\n }\n const rows = db.query(sql).all(...params) as MetaQueryRow[]\n return rows.map((r) => {\n const firstUserTurn = r.first_user_turn\n ? safeParseRow<SessionTurn>(r.first_user_turn, r.id, 'turn')\n : null\n return {\n id: r.id,\n metadata: safeParseRecord(r.metadata),\n ...(r.project_root ? { projectRoot: r.project_root } : {}),\n updatedAt: r.updated_at,\n turnCount: r.turn_count,\n userMessageCount: r.user_count,\n runCount: r.run_count,\n ...(firstUserTurn ? { firstUserTurn } : {}),\n }\n })\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]) {\n txnAppendTurns.immediate(sessionId, turns)\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number) {\n // `LIMIT -1` in SQLite means \"no limit\". Use that as the sentinel\n // for `limit === undefined` so the same prepared statement covers\n // both paged and full-range reads without a second SQL.\n const lim = typeof limit === 'number' ? limit : -1\n const rows = stmtLoadTurnsRange.all(sessionId, lim, from) as { data: string }[]\n return rows\n .map(r => safeParseRow<SessionTurn>(r.data, sessionId, 'turn'))\n .filter(t => t !== null)\n },\n\n async updateRun(sessionId: string, run: SessionRun) {\n txnUpdateRun.immediate(sessionId, run)\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']) {\n txnUpdateStatus.immediate(sessionId, status)\n },\n\n close() {\n // bun:sqlite — `false` skips throwing when statements are still\n // alive; finalizers handle them. Idempotent.\n db.close(false)\n },\n }\n\n return store\n}\n\n// ---------------------------------------------------------------------------\n// Migrations\n// ---------------------------------------------------------------------------\n\n/**\n * Forward-only schema migration runner. Idempotent — every step\n * feature-detects rather than relying on the `PRAGMA user_version`\n * number alone, so a partially-migrated DB (e.g. interrupted v3→v4\n * backfill) is brought to a consistent v4 state on the next open.\n *\n * The legacy `data` column is the v3 sentinel: when present we treat\n * the DB as v3-or-older and run the backfill. Before any destructive\n * change we copy the entire DB file to `<path>.zidane-pre-v4.bak` (see\n * {@link backupBeforeV3Migration}) so the user has a guaranteed\n * recovery path if anything goes sideways.\n *\n * After backfill we attempt to drop the column (SQLite 3.35+; Bun\n * ships ≥ 3.43 so this always succeeds in practice). If it does fail,\n * we throw rather than limp along — leaving the column with `NOT NULL`\n * while the new write paths omit it would silently break every future\n * `INSERT`. The `.bak` file lets the user roll back and report the bug.\n */\nfunction migrate(db: Database, dbPath: string) {\n // Downgrade guard: refuse to open a DB written by a newer zidane. The\n // newer schema may have shapes this build doesn't understand; \"limping\n // along\" risks silently corrupting it. Forward-only policy (see header).\n //\n // Exemption: version 5 was stamped by short-lived dev builds (2026-07)\n // whose only change was the additive `turns.role` column — plain v4\n // shape plus an extra nullable column. This build understands it fully\n // and re-stamps it back to 4 at the end of this function.\n const onDiskVersion = (db.query('PRAGMA user_version').get() as { user_version: number } | null)?.user_version ?? 0\n if (onDiskVersion > SCHEMA_VERSION && onDiskVersion !== 5) {\n throw new Error(\n `[zidane/sqlite] \"${dbPath}\" has schema version ${onDiskVersion}, but this zidane build only supports up to ${SCHEMA_VERSION}. `\n + `It was written by a newer zidane — upgrade zidane, or point this build at a different sessions DB.`,\n )\n }\n\n const sessionCols = db.query('PRAGMA table_info(sessions)').all() as { name: string }[]\n const hasCol = (n: string) => sessionCols.some(c => c.name === n)\n\n // v1/v2 → v3: project_root column (idempotent on fresh DBs since\n // CREATE TABLE already has it).\n if (!hasCol('project_root'))\n db.run('ALTER TABLE sessions ADD COLUMN project_root TEXT')\n\n // v3 → v4 header promotion. ADD COLUMN ... DEFAULT applies the\n // default to every existing row, so v3 sessions get a synthetic\n // 'idle' status + empty metadata until the backfill loop below\n // overwrites with the real values from the JSON blob.\n if (!hasCol('status'))\n db.run(`ALTER TABLE sessions ADD COLUMN status TEXT NOT NULL DEFAULT 'idle'`)\n if (!hasCol('metadata'))\n db.run(`ALTER TABLE sessions ADD COLUMN metadata TEXT NOT NULL DEFAULT '{}'`)\n\n // v3 → v4 row fan-out. Skip when the legacy column is gone (already\n // migrated, or fresh v4 DB).\n if (hasCol('data')) {\n // Take a point-in-time snapshot BEFORE the destructive changes\n // below. Aborts the whole migration on backup failure so the user's\n // v3 DB is never modified without a recovery path on disk.\n backupBeforeV3Migration(db, dbPath)\n backfillV3Blobs(db)\n // Drop the legacy column. Bun's SQLite is 3.51+ in practice — DROP\n // COLUMN has been supported since 3.35 (2021). If it ever did fail\n // we'd be left with a `NOT NULL data` column that the new INSERT\n // statements don't populate, making the DB unwritable. Throwing\n // here surfaces the failure immediately and points the user at the\n // backup file we just created.\n try {\n db.run('ALTER TABLE sessions DROP COLUMN data')\n }\n catch (err) {\n throw new Error(\n `[zidane/sqlite] v3→v4 migration could not drop legacy \"data\" column: ${errorMessage(err)}. `\n + `Restore from \"${dbPath}.zidane-pre-v4.bak\" with an older zidane build and report this — `\n + `your sessions are intact in the backup file.`,\n )\n }\n }\n\n // Additive role denormalization (see the header's \"unversioned\n // enhancement\" note for why this never bumps `user_version`). Runs\n // AFTER the v3→v4 fan-out so the repair sees the fanned-out rows.\n //\n // - ALTER is feature-detected (fresh DBs already have the column\n // from CREATE TABLE).\n // - The NULL-role repair is checked on EVERY open: it heals rows\n // written by plain-v4 builds sharing this DB, interrupted\n // first-time backfills, and the initial migration itself — one\n // code path for all three.\n // - The read-only existence probe (cheap via the partial index)\n // gates the UPDATE so the steady-state open performs no write at\n // all. That matters beyond speed: an UPDATE statement acquires the\n // write lock even when it matches nothing, and `createSqliteStore`\n // is synchronous — an unconditional write at open would stall\n // behind any concurrent writer (the exact `bun --watch` restart\n // race busy_timeout exists for).\n // - Rows with corrupt JSON keep a NULL role and are excluded from\n // role-scoped queries — same skip-bad-rows posture as the load\n // path. The probe shares the UPDATE's `json_valid` predicate, so\n // corrupt-only leftovers don't re-trigger the write every open.\n const turnCols = db.query('PRAGMA table_info(turns)').all() as { name: string }[]\n if (!turnCols.some(c => c.name === 'role'))\n db.run('ALTER TABLE turns ADD COLUMN role TEXT')\n db.run('CREATE INDEX IF NOT EXISTS idx_turns_role_null ON turns(session_id) WHERE role IS NULL')\n const needsRepair = db.query(`SELECT 1 FROM turns WHERE role IS NULL AND json_valid(data) LIMIT 1`).get()\n if (needsRepair)\n db.run(`UPDATE turns SET role = json_extract(data, '$.role') WHERE role IS NULL AND json_valid(data)`)\n db.run('CREATE INDEX IF NOT EXISTS idx_turns_session_role ON turns(session_id, role, seq)')\n\n // Repair a DB stamped by the short-lived v5 dev builds (2026-07) — the\n // role work above was briefly shipped as a version bump, which locked\n // released v4-only binaries out of the file. The shape is identical;\n // only the stamp differs. Safe because nothing else ever wrote 5.\n const currentVersion = (db.query('PRAGMA user_version').get() as { user_version: number } | null)?.user_version ?? 0\n if (currentVersion !== SCHEMA_VERSION)\n db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`)\n}\n\n/**\n * Pre-migration safety net for v3 → v4: copy the source DB file to\n * `<path>.zidane-pre-v4.bak` so the user can recover by restoring the\n * snapshot if anything in the migration goes sideways.\n *\n * - Skipped for non-filesystem paths (`:memory:`, empty string) — no\n * file to copy.\n * - Skipped when the file is missing (fresh install, never reached\n * migration territory).\n * - Skipped when the backup already exists — re-runs of the migration\n * (idempotent path) reuse the same snapshot rather than overwrite a\n * potentially-earlier good copy with a later partial state.\n * - WAL is checkpointed first so the .db file contains everything that\n * was committed up to this point (otherwise pending WAL frames would\n * be missing from the snapshot).\n * - On copy failure the whole migration is aborted with a thrown error\n * — we refuse to modify the DB without a recovery path. The user\n * sees a clear diagnostic; their sessions stay intact.\n *\n * Surfaces a one-line stderr message on success so the user knows where\n * the snapshot landed. They can delete it once they've confirmed the\n * post-migration TUI behaves correctly.\n */\nfunction backupBeforeV3Migration(db: Database, dbPath: string) {\n // `:memory:` and similar URI-shaped paths have no filesystem target.\n // bun:sqlite also accepts an empty string as a synonym for in-memory.\n if (dbPath === '' || dbPath === ':memory:' || dbPath.startsWith('file::memory:'))\n return\n\n if (!existsSync(dbPath))\n return\n\n const backupPath = `${dbPath}.zidane-pre-v4.bak`\n // Don't clobber an existing backup. The first interrupted-migration\n // attempt's snapshot is the one closest to the user's pre-zidane-v4\n // state; subsequent retries would only overwrite it with a partial\n // intermediate.\n if (existsSync(backupPath))\n return\n\n // Checkpoint WAL so the .db file contains every committed frame.\n // Without this, a backup of just the .db file would be missing\n // anything sitting in the -wal sidecar. Failure is non-fatal — an\n // empty WAL (the common case for a freshly-opened DB) returns an\n // error from TRUNCATE on some SQLite builds; we still proceed with\n // the file copy.\n let checkpointed = true\n try {\n db.run('PRAGMA wal_checkpoint(TRUNCATE)')\n }\n catch {\n // Best-effort; the copy below still captures whatever's on disk —\n // plus the WAL/SHM sidecars (copied alongside below) so the snapshot\n // stays consistent even with un-checkpointed frames.\n checkpointed = false\n }\n\n try {\n copyFileSync(dbPath, backupPath)\n if (!checkpointed) {\n // Checkpoint failed → committed frames may still live in the -wal\n // sidecar. Copy it (and -shm) next to the backup so a restore of\n // the trio is point-in-time consistent.\n for (const ext of ['-wal', '-shm']) {\n const sidecar = `${dbPath}${ext}`\n if (existsSync(sidecar))\n copyFileSync(sidecar, `${backupPath}${ext}`)\n }\n }\n process.stderr.write(\n `[zidane/sqlite] v3→v4 migration: backed up your sessions DB to \"${backupPath}\".\\n`\n + ` To roll back if anything looks wrong:\\n`\n + ` 1. quit zidane\\n`\n + ` 2. cp \"${backupPath}\" \"${dbPath}\" && rm -f \"${dbPath}-wal\" \"${dbPath}-shm\"\\n`\n + ` 3. pin an older zidane that knows the v3 schema, or upgrade to a fix\\n`\n + ` Delete the .bak once every session loads correctly.\\n`,\n )\n }\n catch (err) {\n throw new Error(\n `[zidane/sqlite] failed to back up \"${dbPath}\" before v3→v4 migration: ${errorMessage(err)}. `\n + `Refusing to modify the DB without a recovery path. Move the file aside or fix the permissions and retry.`,\n )\n }\n}\n\n/**\n * Parse each session's legacy `data` blob and fan its `turns` + `runs`\n * arrays out into the dedicated tables, then overwrite the synthetic\n * `status`/`metadata` defaults with the values from the blob.\n *\n * Skips rows that already have at least one entry in `turns` for them —\n * a previous run of this migration already landed those bytes, and\n * re-inserting them would either duplicate (if seq numbering shifted)\n * or crash on the PK. The \"header already exists, turns table populated\"\n * combination is the idempotency signal.\n *\n * Per-row failures (corrupt JSON, …) log + skip rather than abort the\n * whole migration: one bad row shouldn't prevent the rest of the DB\n * from coming forward to v4.\n */\nfunction backfillV3Blobs(db: Database) {\n // Use a raw SELECT (not a prepared statement) so the legacy column\n // reference doesn't survive in the statement cache after the column\n // is dropped at the end of `migrate()`.\n const rows = db.query('SELECT id, data FROM sessions').all() as { id: string, data: string | null }[]\n if (rows.length === 0)\n return\n\n const insertTurn = db.prepare('INSERT INTO turns (session_id, seq, data) VALUES (?, ?, ?)')\n const upsertRun = db.prepare(`\n INSERT INTO runs (session_id, run_id, started_at, data) VALUES (?, ?, ?, ?)\n ON CONFLICT(session_id, run_id) DO UPDATE SET\n data = excluded.data,\n started_at = excluded.started_at\n `)\n const updateHeader = db.prepare('UPDATE sessions SET status = ?, metadata = ? WHERE id = ?')\n const countTurns = db.prepare('SELECT COUNT(*) as c FROM turns WHERE session_id = ?')\n\n for (const row of rows) {\n if (!row.data)\n continue\n try {\n const data = JSON.parse(row.data) as Partial<SessionData>\n // Skip rows whose turns table already has content — a previous\n // partial migration already fanned this row out.\n const existing = (countTurns.get(row.id) as { c: number }).c\n if (existing > 0)\n continue\n\n const turns = Array.isArray(data.turns) ? data.turns : []\n const runs = Array.isArray(data.runs) ? data.runs : []\n const txn = db.transaction(() => {\n turns.forEach((t, i) => insertTurn.run(row.id, i, JSON.stringify(t)))\n for (const run of runs) {\n // Defensive: a corrupt run record without an id can't go into\n // the (session_id, run_id) PK. Skip rather than crash.\n if (!run || typeof run.id !== 'string')\n continue\n upsertRun.run(row.id, run.id, run.startedAt ?? 0, JSON.stringify(run))\n }\n updateHeader.run(data.status ?? 'idle', JSON.stringify(data.metadata ?? {}), row.id)\n })\n txn.immediate()\n }\n catch (err) {\n process.stderr.write(`[zidane/sqlite] v3→v4 migrate: session \"${row.id}\" skipped: ${errorMessage(err)}\\n`)\n }\n }\n}\n\n/**\n * Compose the WHERE / LIMIT fragments shared by `list` and `listMeta`.\n *\n * `projectRoot: string` → `WHERE project_root = ?` (excludes untagged).\n * `projectRoot: null` → `WHERE project_root IS NULL` (untagged only).\n * `projectRoot: undefined` → axis omitted (untagged + tagged).\n *\n * The `null` case lets a future \"show legacy\" debug toggle query pre-v3\n * sessions explicitly without leaking them into normal per-project lists.\n */\nfunction buildListFilter(\n filter?: { agentId?: string, limit?: number, projectRoot?: string | null },\n): { where: string, limit: string, params: string[] } {\n const conditions: string[] = []\n const params: string[] = []\n if (filter?.agentId) {\n conditions.push('agent_id = ?')\n params.push(filter.agentId)\n }\n if ('projectRoot' in (filter ?? {})) {\n const v = filter!.projectRoot\n if (v === null) {\n conditions.push('project_root IS NULL')\n }\n else if (typeof v === 'string') {\n conditions.push('project_root = ?')\n params.push(v)\n }\n }\n return {\n where: conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '',\n limit: typeof filter?.limit === 'number' && filter.limit > 0 ? `LIMIT ${filter.limit}` : '',\n params,\n }\n}\n\n/**\n * Guarded per-row parse for `turns.data` / `runs.data`. One corrupt row\n * (truncated write, hand-edited DB, disk bitflip) must not make the whole\n * session unloadable — log + skip it instead, mirroring the migration's\n * per-row backfill policy. The structural check matches the minimal shape\n * both `SessionTurn` and `SessionRun` share (an object with a string `id`).\n */\nfunction safeParseRow<T extends { id: string }>(\n text: string,\n sessionId: string,\n kind: 'turn' | 'run',\n): T | null {\n try {\n const parsed = JSON.parse(text) as unknown\n if (\n !parsed\n || typeof parsed !== 'object'\n || Array.isArray(parsed)\n || typeof (parsed as { id?: unknown }).id !== 'string'\n ) {\n console.error(`[zidane/sqlite] session \"${sessionId}\": skipping malformed ${kind} row (not a ${kind}-shaped object)`)\n return null\n }\n return parsed as T\n }\n catch (err) {\n console.error(`[zidane/sqlite] session \"${sessionId}\": skipping corrupt ${kind} row: ${errorMessage(err)}`)\n return null\n }\n}\n\n/**\n * `JSON.parse` with a fallback to `{}` for the metadata column. v3→v4\n * migration writes well-formed JSON, fresh v4 writes go through\n * `JSON.stringify(metadata ?? {})` — but a hand-edited DB or a botched\n * external migration could leave a row with malformed JSON, and we'd\n * rather surface an empty metadata object than crash the entire load\n * path. Logged under `ZIDANE_DEBUG` so the corruption isn't fully\n * silent.\n */\nfunction safeParseRecord(text: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(text)\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : {}\n }\n catch (err) {\n if (process.env.ZIDANE_DEBUG)\n process.stderr.write(`[zidane/sqlite] metadata JSON parse failed, defaulting to {}: ${errorMessage(err)}\\n`)\n return {}\n }\n}\n\n/**\n * Convenience: open a SQLite store at `dbPath`, creating its parent\n * directory if it doesn't yet exist. Used by the TUI launcher to spin up\n * the default session store at `~/.zidane/sessions.db`.\n *\n * Lives here (and not in `chat/store.ts`) so the renderer-agnostic\n * `zidane/chat` entry stays free of `bun:sqlite` — non-Bun consumers\n * (a future GUI, an SDK) can import `zidane/chat` without pulling in the\n * Bun-only binding.\n */\nexport function createTuiStore(dbPath: string): SessionStore {\n const dir = dirname(dbPath)\n if (!existsSync(dir)) {\n try {\n mkdirSync(dir, { recursive: true })\n }\n catch (err) {\n throw new Error(\n `Could not create TUI storage directory at \"${dir}\". `\n + `Override the location via \\`runTui({ storageDir, prefix })\\` or the `\n + `\\`ZID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;AACF;;;;;;;;;;;AAYA,SAAgB,eAAe,QAA8B;CAC3D,MAAM,MAAM,QAAQ,MAAM;CAC1B,IAAI,CAAC,WAAW,GAAG,GACjB,IAAI;EACF,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;CACpC,SACO,KAAK;EACV,MAAM,IAAI,MACR,8CAA8C,IAAI,yHAEG,aAAa,GAAG,GACvE;CACF;CAEF,OAAO,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAC3C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { h as toWireMessages } from "./messages-
|
|
1
|
+
import { h as toWireMessages } from "./messages-C5BDOjUG.js";
|
|
2
2
|
import { Buffer } from "node:buffer";
|
|
3
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
4
|
//#region src/session/file-map.ts
|
|
@@ -345,7 +345,7 @@ function createRemoteStore(options) {
|
|
|
345
345
|
const EXTENSION_SESSION_METADATA_KEY = "extensions";
|
|
346
346
|
const EXTENSION_SESSION_ITEM_MAX_BYTES = 16384;
|
|
347
347
|
const EXTENSION_SESSION_TOTAL_MAX_BYTES = 65536;
|
|
348
|
-
const DANGEROUS_RECORD_KEYS = new Set([
|
|
348
|
+
const DANGEROUS_RECORD_KEYS = /* @__PURE__ */ new Set([
|
|
349
349
|
"__proto__",
|
|
350
350
|
"prototype",
|
|
351
351
|
"constructor"
|
|
@@ -645,4 +645,4 @@ function assertJsonBounded(value, maxBytes, label) {
|
|
|
645
645
|
//#endregion
|
|
646
646
|
export { getExtensionSessionState as a, withExtensionSession as c, createFileMapStore as d, demoteStaleRunningStatus as i, createRemoteStore as l, currentExtensionSession as n, loadSession as o, deleteExtensionSessionState as r, setExtensionSessionState as s, createSession as t, createMemoryStore as u };
|
|
647
647
|
|
|
648
|
-
//# sourceMappingURL=session-
|
|
648
|
+
//# sourceMappingURL=session-CsKzK8-P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-CsKzK8-P.js","names":[],"sources":["../src/session/file-map.ts","../src/session/memory.ts","../src/session/remote.ts","../src/session/index.ts"],"sourcesContent":["/**\n * File-map session store.\n *\n * Wraps a narrow 3-method adapter (`get` / `save` / `delete`) that exchanges a flat\n * map of filename → string content. Useful for embedding zidane sessions inside\n * host-provided session backends that only speak in file maps (not zidane's native\n * `SessionStore` shape).\n *\n * Serialization format:\n * - `turns.jsonl` — one `SessionTurn` per line.\n * - `meta.json` — session metadata (id, agentId, status, runs, metadata, timestamps).\n *\n * JSONL for turns keeps history inspectable with tools like `jq` and resilient to\n * partial corruption — parse up to the first bad line and you still have a valid\n * prefix. Metadata lives in its own file so large turn logs don't bloat the\n * metadata path.\n *\n * Scope: each `createFileMapStore` handles a **single session** — the adapter's\n * file map holds at most one zidane session at a time. This matches how host SDKs\n * scope their session stores per conversation.\n *\n * Divergences from the built-in memory / sqlite stores:\n * - `appendTurns` / `updateStatus` / `updateRun` auto-create a minimal `SessionData`\n * record on first write, instead of silently no-oping when the session hasn't been\n * explicitly `save()`-ed. This matches the host-SDK integration path where\n * `createSession(...)` → `agent.run(...)` directly without an explicit `save()` call.\n * - `updateRun` inserts the run if not found in the cached record (rather than\n * silently dropping). Run records therefore always reach the adapter.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\n\n/**\n * Host-provided file-map adapter. Three methods exchanging `Record<string, string>`\n * payloads — the whole persistence surface the wrapper needs.\n */\nexport interface FileMapAdapter {\n /** Load the current file map. Returns an empty `files` record when nothing is persisted. */\n get: () => Promise<{ files: Record<string, string> }>\n /** Replace the persisted file map. Full-rewrite semantics. */\n save: (files: Record<string, string>) => Promise<void>\n /** Delete all persisted state. */\n delete: () => Promise<void>\n}\n\nexport interface FileMapStoreOptions {\n /** Filename for the JSONL turns log. Default: `turns.jsonl`. */\n turnsFile?: string\n /** Filename for the metadata JSON. Default: `meta.json`. */\n metaFile?: string\n}\n\ninterface MetaShape {\n id: string\n agentId?: string\n /** Optional — absent on files written before projectRoot persistence. */\n projectRoot?: string\n runs: SessionRun[]\n status: SessionData['status']\n metadata: Record<string, unknown>\n createdAt: number\n updatedAt: number\n}\n\nfunction toMeta(data: SessionData): MetaShape {\n return {\n id: data.id,\n agentId: data.agentId,\n projectRoot: data.projectRoot,\n runs: data.runs,\n status: data.status,\n metadata: data.metadata,\n createdAt: data.createdAt,\n updatedAt: data.updatedAt,\n }\n}\n\nfunction toData(meta: MetaShape, turns: SessionTurn[]): SessionData {\n return {\n id: meta.id,\n agentId: meta.agentId,\n ...(typeof meta.projectRoot === 'string' ? { projectRoot: meta.projectRoot } : {}),\n turns,\n runs: meta.runs,\n status: meta.status,\n metadata: meta.metadata,\n createdAt: meta.createdAt,\n updatedAt: meta.updatedAt,\n }\n}\n\nfunction parseTurnsJsonl(jsonl: string): SessionTurn[] {\n if (!jsonl)\n return []\n const turns: SessionTurn[] = []\n for (const line of jsonl.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed)\n continue\n try {\n turns.push(JSON.parse(trimmed) as SessionTurn)\n }\n catch {\n // Skip malformed lines — preserves the valid prefix on partial corruption.\n }\n }\n return turns\n}\n\nfunction serializeTurnsJsonl(turns: SessionTurn[]): string {\n if (turns.length === 0)\n return ''\n return `${turns.map(t => JSON.stringify(t)).join('\\n')}\\n`\n}\n\n/**\n * Create a single-session `SessionStore` backed by a file-map adapter.\n *\n * @example\n * ```ts\n * const session = await createSession({\n * store: createFileMapStore(hostSessionStore),\n * })\n * ```\n */\nexport function createFileMapStore(\n adapter: FileMapAdapter,\n options: FileMapStoreOptions = {},\n): SessionStore {\n const turnsFile = options.turnsFile ?? 'turns.jsonl'\n const metaFile = options.metaFile ?? 'meta.json'\n\n // Cached view of the persisted session. Populated lazily on first access so the\n // factory itself doesn't do I/O.\n let cached: SessionData | null = null\n let hydrated = false\n // In-flight hydrate memo: concurrent first calls share one adapter.get()\n // instead of racing two reads (the loser's view would clobber the winner's\n // subsequent writes — a lost-update race).\n let hydrating: Promise<void> | null = null\n // Turns salvaged from turns.jsonl when meta.json was present but corrupt.\n // We can't trust the (unparseable) meta for the session id, so we hold the\n // turns aside and re-attach them when the next write establishes an id —\n // the alternative (treating the session as missing) would let that write\n // overwrite an intact turns.jsonl with an empty one.\n let recoveredTurns: SessionTurn[] | null = null\n\n async function hydrate(): Promise<void> {\n if (hydrated)\n return\n if (!hydrating) {\n hydrating = (async () => {\n const { files } = await adapter.get()\n const metaRaw = files[metaFile]\n if (metaRaw) {\n let meta: MetaShape | null = null\n try {\n meta = JSON.parse(metaRaw) as MetaShape\n }\n catch {\n meta = null\n }\n if (meta) {\n cached = toData(meta, parseTurnsJsonl(files[turnsFile] ?? ''))\n }\n else {\n recoveredTurns = parseTurnsJsonl(files[turnsFile] ?? '')\n console.error(`[zidane/file-map] ${metaFile} exists but is not valid JSON — preserving ${recoveredTurns.length} turn(s) from ${turnsFile} for the next write instead of treating the session as missing`)\n }\n }\n hydrated = true\n })().finally(() => {\n hydrating = null\n })\n }\n return hydrating\n }\n\n async function persist(data: SessionData): Promise<void> {\n const meta = toMeta(data)\n await adapter.save({\n [metaFile]: JSON.stringify(meta, null, 2),\n [turnsFile]: serializeTurnsJsonl(data.turns),\n })\n }\n\n // Ensure `cached` exists for `sessionId`, creating a minimal record when first written.\n // Returns false when `cached` already holds a different sessionId (request ignored).\n async function ensureCachedFor(sessionId: string): Promise<boolean> {\n await hydrate()\n if (cached) {\n return cached.id === sessionId\n }\n const now = Date.now()\n cached = {\n id: sessionId,\n // Re-attach turns salvaged from a corrupt-meta hydrate so the next\n // persist() doesn't destroy an intact turns.jsonl.\n turns: recoveredTurns ?? [],\n runs: [],\n status: 'idle',\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }\n recoveredTurns = null\n hydrated = true\n return true\n }\n\n return {\n async load(sessionId: string): Promise<SessionData | null> {\n await hydrate()\n if (!cached || cached.id !== sessionId)\n return null\n return structuredClone(cached)\n },\n\n async save(data: SessionData): Promise<void> {\n cached = structuredClone(data)\n hydrated = true\n await persist(cached)\n },\n\n async delete(sessionId: string): Promise<void> {\n await hydrate()\n if (cached && cached.id !== sessionId)\n return\n cached = null\n await adapter.delete()\n },\n\n async list(filter): Promise<string[]> {\n await hydrate()\n if (!cached)\n return []\n if (filter?.agentId && cached.agentId !== filter.agentId)\n return []\n // file-map stores exactly one session, so the projectRoot filter\n // either keeps it (match / axis off) or drops it entirely.\n if (filter && 'projectRoot' in filter) {\n const v = filter.projectRoot\n if (v === null && cached.projectRoot != null)\n return []\n if (typeof v === 'string' && cached.projectRoot !== v)\n return []\n }\n return [cached.id]\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]): Promise<void> {\n const ok = await ensureCachedFor(sessionId)\n if (!ok)\n return\n cached!.turns.push(...structuredClone(turns))\n cached!.updatedAt = Date.now()\n await persist(cached!)\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number): Promise<SessionTurn[]> {\n await hydrate()\n if (!cached || cached.id !== sessionId)\n return []\n const slice = cached.turns.slice(from, limit !== undefined ? from + limit : undefined)\n return structuredClone(slice) as SessionTurn[]\n },\n\n async updateRun(sessionId: string, run: SessionRun): Promise<void> {\n const ok = await ensureCachedFor(sessionId)\n if (!ok)\n return\n const idx = cached!.runs.findIndex(r => r.id === run.id)\n if (idx >= 0)\n cached!.runs[idx] = structuredClone(run)\n else\n cached!.runs.push(structuredClone(run))\n cached!.updatedAt = Date.now()\n await persist(cached!)\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']): Promise<void> {\n const ok = await ensureCachedFor(sessionId)\n if (!ok)\n return\n cached!.status = status\n cached!.updatedAt = Date.now()\n await persist(cached!)\n },\n }\n}\n","/**\n * In-memory session store.\n * Useful for development and testing. Data is lost when the process exits.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\n\nexport function createMemoryStore(): SessionStore {\n const sessions = new Map<string, SessionData>()\n\n // Auto-create a minimal record when turns arrive for an unknown id. Mirrors\n // the file-map store: `createSession({store})` + `agent.run()` appends\n // turns without an explicit `save()` first — a get-or-no-op `appendTurns`\n // would silently lose that history. Deliberately scoped to `appendTurns`\n // only: a late `updateRun`/`updateStatus` racing a `delete()` must stay a\n // no-op rather than resurrect a deleted session.\n function ensureSession(sessionId: string): SessionData {\n let data = sessions.get(sessionId)\n if (!data) {\n const now = Date.now()\n data = {\n id: sessionId,\n turns: [],\n runs: [],\n status: 'idle',\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }\n sessions.set(sessionId, data)\n }\n return data\n }\n\n return {\n async load(sessionId: string) {\n const data = sessions.get(sessionId)\n return data ? structuredClone(data) : null\n },\n\n async save(session: SessionData) {\n sessions.set(session.id, structuredClone(session))\n },\n\n async delete(sessionId: string) {\n sessions.delete(sessionId)\n },\n\n async list(filter) {\n let ids = Array.from(sessions.keys())\n if (filter?.agentId) {\n ids = ids.filter(id => sessions.get(id)?.agentId === filter.agentId)\n }\n // `projectRoot` mirrors the SQLite store's tri-state contract:\n // string → only sessions tagged with that root\n // null → only UNTAGGED sessions (legacy / pre-v3 rows)\n // undefined → axis ignored (tagged + untagged both returned)\n if (filter && 'projectRoot' in filter) {\n const v = filter.projectRoot\n if (v === null)\n ids = ids.filter(id => sessions.get(id)?.projectRoot == null)\n else if (typeof v === 'string')\n ids = ids.filter(id => sessions.get(id)?.projectRoot === v)\n }\n if (filter?.limit) {\n ids = ids.slice(0, filter.limit)\n }\n return ids\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]) {\n const data = ensureSession(sessionId)\n data.turns.push(...structuredClone(turns))\n data.updatedAt = Date.now()\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number) {\n const data = sessions.get(sessionId)\n if (!data)\n return []\n const sliced = data.turns.slice(from, limit !== undefined ? from + limit : undefined)\n return structuredClone(sliced) as SessionTurn[]\n },\n\n async updateRun(sessionId: string, run: SessionRun) {\n const data = sessions.get(sessionId)\n if (!data)\n return\n // Upsert — see the matching comment in sqlite.ts's\n // `txnUpdateRun` for the failure mode. tl;dr: the agent's\n // `startRun()` only updates in-memory state; the store first\n // sees the run via `updateRun()` at finalize time, so an\n // update-only impl silently drops every new run.\n const idx = data.runs.findIndex(r => r.id === run.id)\n if (idx >= 0)\n data.runs[idx] = structuredClone(run)\n else\n data.runs.push(structuredClone(run))\n data.updatedAt = Date.now()\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']) {\n const data = sessions.get(sessionId)\n if (!data)\n return\n data.status = status\n data.updatedAt = Date.now()\n },\n }\n}\n","/**\n * Remote session store via HTTP API.\n *\n * Expects a REST API with:\n * GET {url}/sessions/{id} -> SessionData | 404\n * PUT {url}/sessions/{id} -> save SessionData\n * DELETE {url}/sessions/{id} -> delete\n * GET {url}/sessions?agentId=&limit=&projectRoot= -> { ids: string[] }\n * `projectRoot=__null__` is the wire encoding for \"untagged only\".\n * POST {url}/sessions/{id}/turns -> append turns\n * GET {url}/sessions/{id}/turns?from=&limit= -> SessionTurn[]\n * PUT {url}/sessions/{id}/runs/{runId} -> update run\n * PATCH {url}/sessions/{id} -> { status }\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\n\nexport interface RemoteStoreOptions {\n /** Base URL of the session API */\n url: string\n /** Optional headers (e.g. for authentication) */\n headers?: Record<string, string>\n /** Per-request timeout in ms. Default 30s — bounds a hung backend. */\n timeoutMs?: number\n}\n\nconst TRAILING_SLASH = /\\/$/\nconst DEFAULT_TIMEOUT_MS = 30_000\n\nexport function createRemoteStore(options: RemoteStoreOptions): SessionStore {\n const baseUrl = options.url.replace(TRAILING_SLASH, '')\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const defaultHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...options.headers,\n }\n\n async function request(path: string, init?: RequestInit): Promise<Response> {\n const url = `${baseUrl}${path}`\n // Bound every call so a hung backend can't wedge the caller forever.\n const res = await fetch(url, {\n ...init,\n headers: { ...defaultHeaders, ...init?.headers },\n signal: init?.signal ?? AbortSignal.timeout(timeoutMs),\n })\n return res\n }\n\n /**\n * Parse a JSON response body, rethrowing parse failures with URL/status\n * context so a malformed backend reply produces a diagnosable error\n * instead of an opaque `Unexpected token` from deep in `res.json()`.\n */\n async function parseJson<T>(res: Response, path: string): Promise<T> {\n try {\n return await res.json() as T\n }\n catch (cause) {\n throw new Error(\n `Remote session: malformed JSON from ${path} (${res.status} ${res.statusText})`,\n { cause },\n )\n }\n }\n\n return {\n async load(sessionId: string) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}`)\n if (!res.ok) {\n if (res.status === 404)\n return null\n throw new Error(`Remote session load failed: ${res.status} ${res.statusText}`)\n }\n return await parseJson<SessionData>(res, `/sessions/${sessionId}`)\n },\n\n async save(session: SessionData) {\n const res = await request(`/sessions/${encodeURIComponent(session.id)}`, {\n method: 'PUT',\n body: JSON.stringify(session),\n })\n if (!res.ok) {\n throw new Error(`Remote session save failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async delete(sessionId: string) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}`, {\n method: 'DELETE',\n })\n if (!res.ok && res.status !== 404) {\n throw new Error(`Remote session delete failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async list(filter) {\n const params = new URLSearchParams()\n if (filter?.agentId)\n params.set('agentId', filter.agentId)\n if (filter?.limit)\n params.set('limit', String(filter.limit))\n if (filter && 'projectRoot' in filter) {\n const v = filter.projectRoot\n if (v === null)\n params.set('projectRoot', '__null__')\n else if (typeof v === 'string')\n params.set('projectRoot', v)\n }\n\n const query = params.toString()\n const path = query ? `/sessions?${query}` : '/sessions'\n const res = await request(path)\n\n if (!res.ok) {\n throw new Error(`Remote session list failed: ${res.status} ${res.statusText}`)\n }\n\n const body = await parseJson<{ ids: string[] }>(res, path)\n if (!Array.isArray(body?.ids)) {\n throw new TypeError(`Remote session list: expected { ids: string[] } from ${path}, got ${typeof body?.ids}`)\n }\n return body.ids\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}/turns`, {\n method: 'POST',\n body: JSON.stringify(turns),\n })\n if (!res.ok) {\n throw new Error(`Remote appendTurns failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number) {\n const params = new URLSearchParams()\n if (from)\n params.set('from', String(from))\n if (limit !== undefined)\n params.set('limit', String(limit))\n\n const query = params.toString()\n const path = `/sessions/${encodeURIComponent(sessionId)}/turns${query ? `?${query}` : ''}`\n const res = await request(path)\n\n if (!res.ok) {\n throw new Error(`Remote getTurns failed: ${res.status} ${res.statusText}`)\n }\n\n const turns = await parseJson<SessionTurn[]>(res, path)\n if (!Array.isArray(turns)) {\n throw new TypeError(`Remote getTurns: expected SessionTurn[] from ${path}, got ${typeof turns}`)\n }\n return turns\n },\n\n async updateRun(sessionId: string, run: SessionRun) {\n const res = await request(\n `/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(run.id)}`,\n {\n method: 'PUT',\n body: JSON.stringify(run),\n },\n )\n if (!res.ok) {\n throw new Error(`Remote updateRun failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}`, {\n method: 'PATCH',\n body: JSON.stringify({ status }),\n })\n if (!res.ok) {\n throw new Error(`Remote updateStatus failed: ${res.status} ${res.statusText}`)\n }\n },\n }\n}\n","/**\n * Session management for agents.\n *\n * A session tracks identity, turn history, and run metadata.\n * Plug in any storage backend by implementing the SessionStore interface,\n * or use one of the built-in stores: memory, sqlite, remote.\n */\n\nimport type { JsonValue, SessionMessage, SessionTurn, TurnUsage } from '../types'\nimport type { ToWireMessagesOptions } from './messages'\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport { Buffer } from 'node:buffer'\nimport { toWireMessages } from './messages'\n\nexport type { SessionContentBlock, SessionMessage, SessionTurn } from '../types'\nexport { createFileMapStore } from './file-map'\n\nconst EXTENSION_SESSION_METADATA_KEY = 'extensions'\nconst EXTENSION_SESSION_ITEM_MAX_BYTES = 16_384\nconst EXTENSION_SESSION_TOTAL_MAX_BYTES = 65_536\nconst DANGEROUS_RECORD_KEYS = new Set(['__proto__', 'prototype', 'constructor'])\nconst extensionSessionStorage = new AsyncLocalStorage<Session>()\n\n/**\n * Run `fn` with `session` bound as the active extension session for the\n * duration of the call (and every async continuation it spawns). Uses\n * `AsyncLocalStorage.run` rather than `enterWith` so concurrent agents in the\n * same process (e.g. the GUI's multi-session host) never observe each other's\n * session through `currentExtensionSession()`.\n */\nexport function withExtensionSession<T>(session: Session | undefined, fn: () => T): T {\n if (!session)\n return fn()\n return extensionSessionStorage.run(session, fn)\n}\n\nexport function currentExtensionSession(): Session | undefined {\n return extensionSessionStorage.getStore()\n}\n\nexport function getExtensionSessionState<T = JsonValue>(\n session: Session | undefined,\n extensionName: string,\n key: string,\n): T | undefined {\n if (!session || !isSafeExtensionStateKey(extensionName) || !isSafeExtensionStateKey(key))\n return undefined\n const root = session.metadata[EXTENSION_SESSION_METADATA_KEY]\n if (!root || typeof root !== 'object' || Array.isArray(root))\n return undefined\n const byExtension = (root as Record<string, unknown>)[extensionName]\n if (!byExtension || typeof byExtension !== 'object' || Array.isArray(byExtension))\n return undefined\n const stored = (byExtension as Record<string, unknown>)[key]\n if (stored === undefined)\n return undefined\n // Hand back a copy so a caller mutating the result can't reach into the live\n // session metadata behind `setMeta`/`save`.\n return jsonClone(stored as JsonValue) as T\n}\n\nexport async function setExtensionSessionState(\n session: Session | undefined,\n extensionName: string,\n key: string,\n value: JsonValue,\n): Promise<void> {\n if (!session)\n return\n assertSafeExtensionStateKey(extensionName, 'extensionName')\n assertSafeExtensionStateKey(key, 'key')\n assertJsonBounded(value, EXTENSION_SESSION_ITEM_MAX_BYTES, `extension session state \"${extensionName}.${key}\"`)\n\n const root = cloneExtensionStateRoot(session.metadata[EXTENSION_SESSION_METADATA_KEY])\n const byExtension = clonePlainRecord(root[extensionName])\n // Deep-copy on write so later mutations to the caller's object don't bleed\n // into persisted state.\n byExtension[key] = jsonClone(value)\n root[extensionName] = byExtension\n assertJsonBounded(root as JsonValue, EXTENSION_SESSION_TOTAL_MAX_BYTES, 'extension session state')\n session.setMeta(EXTENSION_SESSION_METADATA_KEY, root)\n if (session.store)\n await session.save()\n}\n\nexport async function deleteExtensionSessionState(\n session: Session | undefined,\n extensionName: string,\n key: string,\n): Promise<void> {\n if (!session || !isSafeExtensionStateKey(extensionName) || !isSafeExtensionStateKey(key))\n return\n const root = cloneExtensionStateRoot(session.metadata[EXTENSION_SESSION_METADATA_KEY])\n const byExtension = clonePlainRecord(root[extensionName])\n if (!(key in byExtension))\n return\n delete byExtension[key]\n if (Object.keys(byExtension).length > 0)\n root[extensionName] = byExtension\n else\n delete root[extensionName]\n session.setMeta(EXTENSION_SESSION_METADATA_KEY, root)\n if (session.store)\n await session.save()\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface SessionRun {\n id: string\n startedAt: number\n endedAt?: number\n prompt: string\n status: 'running' | 'completed' | 'aborted' | 'error'\n turns?: number\n tokensIn?: number\n tokensOut?: number\n error?: string\n /** Per-turn usage breakdown */\n turnUsage?: TurnUsage[]\n /** Total usage across all turns */\n totalUsage?: TurnUsage\n /** Estimated cost in USD */\n cost?: number\n /**\n * The run that spawned this one, when the agent is a subagent sharing its\n * parent's session. Undefined on top-level `agent.run()`. Consumers can walk\n * `runs` by `parentRunId` to reconstruct the subagent tree.\n */\n parentRunId?: string\n /**\n * Zero-based subagent depth. 0 = top-level run, 1 = direct child, …\n * Recorded here so hosts can query/filter by level without walking the tree.\n */\n depth?: number\n /**\n * How this run was initiated when not a plain user prompt. `command` marks\n * a sub-run driven from a `/` command's `ctx.runAgent`; `display` is the\n * short line the transcript shows instead of the full injected prompt\n * (which often embeds bulky material like a diff). Presentation-only —\n * the wire/model payload is unaffected. Absent on normal runs.\n */\n origin?: { kind: 'command', display?: string }\n}\n\nexport interface SessionData {\n id: string\n agentId?: string\n /**\n * Absolute path of the project this session belongs to — typically\n * the git root resolved from `cwd` at creation time, falling back to\n * `cwd` itself when not in a git repo. Set ONCE on creation and never\n * mutated thereafter (the session \"belongs\" to that project forever).\n *\n * Used by the TUI's sessions list to filter rows by current project,\n * so the user only sees conversations relevant to where they are\n * working — without needing one `.{prefix}/` directory per project.\n *\n * `undefined` on pre-tagging legacy sessions; the chat layer treats\n * those as \"untagged\" and hides them unless `Settings.showAllProjects`\n * is on.\n */\n projectRoot?: string\n turns: SessionTurn[]\n runs: SessionRun[]\n status: 'idle' | 'running' | 'completed' | 'error'\n metadata: Record<string, unknown>\n createdAt: number\n updatedAt: number\n}\n\n/**\n * Compact per-session summary returned by {@link SessionStore.listMeta}.\n * Raw facts only — presentation (title derivation, fallback strings)\n * stays in the chat layer (`listSessionMeta` / `deriveSessionTitle`).\n */\nexport interface SessionMetaRow {\n id: string\n /** Header metadata (may carry a stored `title`). */\n metadata: Record<string, unknown>\n /** Absent for untagged (legacy) sessions. */\n projectRoot?: string\n updatedAt: number\n turnCount: number\n /** Count of `role: 'user'` turns. */\n userMessageCount: number\n runCount: number\n /**\n * First `role: 'user'` turn — the title-derivation source. Stores may\n * omit it when `metadata.title` is already set (no derivation needed).\n */\n firstUserTurn?: SessionTurn\n}\n\n// ---------------------------------------------------------------------------\n// SessionStore interface (pluggable backend)\n// ---------------------------------------------------------------------------\n\nexport interface SessionStore {\n /** Optional: generate a session ID server-side (e.g. a database-issued UUID). */\n generateSessionId?: () => string | Promise<string>\n\n /**\n * Optional: generate a turn ID server-side for session-managed user turns.\n *\n * Provider-loop assistant and tool-result turns use AgentClock.randomUUID()\n * instead, so durable-execution adapters can keep those IDs replay-stable.\n */\n generateTurnId?: () => string | Promise<string>\n\n /** Load a session by ID. Returns null if not found. */\n load: (sessionId: string) => Promise<SessionData | null>\n\n /** Save a session (create or update, full document). */\n save: (session: SessionData) => Promise<void>\n\n /** Delete a session. */\n delete: (sessionId: string) => Promise<void>\n\n /**\n * List session IDs, optionally filtered. `projectRoot` restricts to\n * sessions whose `SessionData.projectRoot` matches exactly — untagged\n * (legacy) sessions are NOT returned under that filter; pass `null`\n * explicitly to ask for untagged ones, or omit the field to ignore\n * the axis entirely. `agentId` filters by recorded agent; the two\n * conditions AND together when both are set.\n */\n list: (filter?: { agentId?: string, limit?: number, projectRoot?: string | null }) => Promise<string[]>\n\n /**\n * Optional: list session summaries without materializing full sessions.\n *\n * The generic fallback (`listSessionMeta` in `zidane/chat`) is `list()`\n * + `load()` per id — O(every turn in the store) because each `load`\n * parses the full turn history just to count rows and derive a title.\n * Stores that can answer from an index (SQL aggregates, a denormalized\n * header) should implement this; the sqlite store turns a multi-hundred-\n * ms TUI boot cost into a single query.\n *\n * Same filter contract and ordering (most recently updated first) as\n * {@link list}.\n */\n listMeta?: (filter?: { agentId?: string, limit?: number, projectRoot?: string | null }) => Promise<SessionMetaRow[]>\n\n /** Append new turns to a session (incremental, avoids full re-save). */\n appendTurns: (sessionId: string, turns: SessionTurn[]) => Promise<void>\n\n /** Return a slice of turns for a session. */\n getTurns: (sessionId: string, from?: number, limit?: number) => Promise<SessionTurn[]>\n\n /**\n * Persist a run record (called after completeRun / abortRun / errorRun).\n *\n * **Upsert semantics required.** The agent's run lifecycle calls\n * `session.startRun()` to register a new run in IN-MEMORY state and\n * then `updateRun()` at finalize. The store doesn't see the run any\n * earlier — `appendTurns` is the only intermediate call, and it\n * persists turns but not runs. An update-only implementation would\n * silently drop every newly-created run record at finalize, leaving\n * the on-disk `runs[]` missing entries that the persisted turns\n * reference (which `eventsFromTurns` then mis-classifies via\n * `ancestryOf` → broken depth, broken `child-N` labels, broken\n * `userPrompts` history).\n *\n * Implementations MUST insert when the id doesn't exist and update\n * when it does. The bundled `sqlite` / `memory` / `file-map` stores\n * all follow this contract; remote stores using HTTP PUT get upsert\n * for free via REST semantics.\n */\n updateRun: (sessionId: string, run: SessionRun) => Promise<void>\n\n /** Update the top-level status of a session. */\n updateStatus: (sessionId: string, status: SessionData['status']) => Promise<void>\n\n /**\n * Optional: release backend resources (e.g. close the SQLite handle).\n * Hosts should call this on teardown when present; stores backed by\n * memory or remote HTTP have nothing to release and may omit it.\n */\n close?: () => void\n}\n\n// ---------------------------------------------------------------------------\n// Session (live instance wrapping a SessionData)\n// ---------------------------------------------------------------------------\n\nexport interface Session {\n /** Session ID */\n readonly id: string\n\n /** Agent ID (optional label) */\n readonly agentId?: string\n\n /**\n * Project this session was created under — see {@link SessionData.projectRoot}.\n * Set once on creation; surfaces here for read-only inspection.\n */\n readonly projectRoot?: string\n\n /**\n * Raw persisted turn history — kept pristine for fidelity (the model's\n * reasoning chain stays intact across reloads).\n *\n * **DO NOT pass this directly to a provider request.** Mid-pair\n * persistence (interrupted runs, partial-result writes, compaction\n * boundaries) leaves orphan `tool_use` / `tool_result` blocks here that\n * every provider 400s on (`tool_result must be preceded by a tool_call\n * with the same toolCallId`). The agent's own loop repairs these\n * just-in-time at wire-send time and never writes the repair back to\n * `turns`.\n *\n * For provider requests built outside `agent.run()`, use\n * {@link Session.toMessages} — it applies the same defensive pairing\n * repair and resolves to a guaranteed-safe `SessionMessage[]`.\n */\n readonly turns: SessionTurn[]\n\n /**\n * True when this session has no turns yet.\n *\n * Use this as a first-prompt signal when setting up a run — e.g. writing initial\n * configuration only on fresh sessions. Equivalent to `turns.length === 0`.\n */\n readonly isEmpty: boolean\n\n /** Top-level session status */\n readonly status: SessionData['status']\n\n /** All runs in this session */\n readonly runs: SessionRun[]\n\n /** Arbitrary metadata */\n readonly metadata: Record<string, unknown>\n\n /**\n * Start tracking a new run. `extras.parentRunId` + `extras.depth` are\n * populated by the spawn tool when a child agent shares its parent's\n * session; regular top-level `agent.run()` calls omit them.\n */\n startRun: (runId: string, prompt?: string, extras?: { parentRunId?: string, depth?: number }) => void\n\n /** Mark a run as completed */\n completeRun: (runId: string, stats: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) => void\n\n /** Mark a run as aborted */\n /**\n * Optional `stats` lets the agent backfill the run's token totals when\n * the abort happened *after* the loop accumulated meaningful usage —\n * common when the user presses esc mid-streaming. Without it, the run\n * record reads `0 in / 0 out` on reload regardless of how much was\n * spent before the abort. Same shape as `completeRun`'s stats so the\n * persisted `totalUsage` aggregate stays consistent across paths.\n */\n abortRun: (runId: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) => void\n\n /** Mark a run as errored */\n /** Optional `stats` — same rationale as `abortRun.stats`. */\n errorRun: (runId: string, error: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) => void\n\n /** Append turns to in-memory history AND persist via store.appendTurns (if store present) */\n appendTurns: (turns: SessionTurn[]) => Promise<void>\n\n /** Replace all turns in-memory (does not persist — use save() for that) */\n setTurns: (turns: SessionTurn[]) => void\n\n /**\n * Replace all runs in-memory (does not persist — use save() for that).\n * Mirrors {@link setTurns} for the fork / restore case: callers that\n * bootstrap a session from an externally-derived snapshot (e.g.\n * `onForkTurn` copying parent runs into a child session) need this so\n * the cloned runs land in `data.runs` before the first `save()`.\n * Production agent runs continue to mutate runs via `startRun` /\n * `completeRun` / `updateRun`; this is the bulk-replace escape hatch.\n */\n setRuns: (runs: SessionRun[]) => void\n\n /** Update the session status in memory AND via store.updateStatus (if store present) */\n updateStatus: (status: SessionData['status']) => Promise<void>\n\n /** Persist an updated run record via store.updateRun (if store present) */\n updateRun: (run: SessionRun) => Promise<void>\n\n /** Generate a session-managed turn ID using store.generateTurnId if available, else crypto.randomUUID() */\n generateTurnId: () => string | Promise<string>\n\n /** Set metadata key */\n setMeta: (key: string, value: unknown) => void\n\n /** Persist the full session document to the store */\n save: () => Promise<void>\n\n /**\n * Project the session's persisted turns into wire-ready messages safe to\n * hand to any provider.\n *\n * The canonical answer to \"I need to send these turns to Anthropic /\n * OpenAI from outside `agent.run()`\" (sub-agent classifier, side-channel\n * summarizer, replay worker, …). Runs the same defensive pairing repair\n * the agent loop applies just-in-time at wire-send time\n * ({@link ensureToolResultPairing}), so orphan `tool_use` blocks and\n * dangling `tool_result`s never reach the provider as the 400\n * \"tool_result must be preceded by a tool_call with the same toolCallId\".\n *\n * Pass `provider` to also enforce the user-tail invariant\n * ({@link ensureEndsWithUserMessage}) — required for opus 4.7 / o-series\n * style models that reject assistant-prefill.\n *\n * Pure + idempotent. Resolves content refs only in the returned messages\n * and does NOT mutate `session.turns`. **Do not write the result back via\n * `setTurns` / `appendTurns`** — synthetic placeholders or resolved\n * payloads will contaminate persisted history.\n */\n toMessages: (options?: ToWireMessagesOptions) => Promise<SessionMessage[]>\n\n /** Serialize to SessionData */\n toJSON: () => SessionData\n\n /**\n * The backing store, when one was provided. Exposed so hosts can call\n * its optional `close()` on teardown (e.g. release the SQLite handle).\n */\n readonly store?: SessionStore\n}\n\n// ---------------------------------------------------------------------------\n// createSession\n// ---------------------------------------------------------------------------\n\nexport interface CreateSessionOptions {\n /** Session ID. If omitted and store provides generateSessionId, that is used. */\n id?: string\n /** Agent ID label */\n agentId?: string\n /**\n * Project tag — see {@link SessionData.projectRoot}. Stamped once on\n * creation; ignored when `_data` is set (restoring an existing\n * session preserves whatever was already persisted there). The TUI\n * resolves this from `findGitRoot(cwd) ?? cwd` so sessions started\n * from the same repo (no matter which subdir) share one tag.\n */\n projectRoot?: string\n /** Initial metadata */\n metadata?: Record<string, unknown>\n /** Storage backend (optional, enables save/load) */\n store?: SessionStore\n // @internal: restore from existing data (bypasses id/agentId/metadata options)\n _data?: SessionData\n}\n\n/**\n * Create a new session.\n * Async so stores that generate IDs server-side (e.g. a database) can be supported.\n */\nexport async function createSession(options: CreateSessionOptions = {}): Promise<Session> {\n const store = options.store\n const now = Date.now()\n\n let sessionId = options.id\n if (!sessionId && store?.generateSessionId) {\n sessionId = await store.generateSessionId()\n }\n if (!sessionId) {\n sessionId = generateId()\n }\n\n const data: SessionData = options._data ?? {\n id: sessionId,\n agentId: options.agentId,\n // Stamp the project tag at creation only — restored sessions (the\n // `_data` branch above) keep whatever was already persisted, even\n // if `options.projectRoot` differs. A session's project identity\n // is sticky for its lifetime; loading the same session from a\n // different cwd doesn't re-home it.\n ...(options.projectRoot ? { projectRoot: options.projectRoot } : {}),\n turns: [],\n runs: [],\n status: 'idle',\n metadata: options.metadata ?? {},\n createdAt: now,\n updatedAt: now,\n }\n\n function touch() {\n data.updatedAt = Date.now()\n }\n\n function findRun(runId: string): SessionRun | undefined {\n return data.runs.find(r => r.id === runId)\n }\n\n /**\n * Apply per-run usage stats onto a SessionRun. Shared by `completeRun`,\n * `abortRun`, and `errorRun` so the on-disk shape stays consistent across\n * exit paths — historically only `completeRun` filled these in, and\n * aborted/errored runs rendered `0 in / 0 out` on reload regardless of\n * how much was actually consumed.\n */\n function applyRunStats(run: SessionRun, stats: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n run.turns = stats.turns\n run.tokensIn = stats.tokensIn\n run.tokensOut = stats.tokensOut\n if (stats.turnUsage) {\n run.turnUsage = stats.turnUsage\n const total = stats.turnUsage.reduce((acc, t) => ({\n input: acc.input + t.input,\n output: acc.output + t.output,\n cacheCreation: (acc.cacheCreation ?? 0) + (t.cacheCreation ?? 0),\n cacheRead: (acc.cacheRead ?? 0) + (t.cacheRead ?? 0),\n thinking: (acc.thinking ?? 0) + (t.thinking ?? 0),\n }), { input: 0, output: 0, cacheCreation: 0, cacheRead: 0, thinking: 0 })\n run.totalUsage = {\n input: total.input,\n output: total.output,\n ...(total.cacheCreation ? { cacheCreation: total.cacheCreation } : {}),\n ...(total.cacheRead ? { cacheRead: total.cacheRead } : {}),\n ...(total.thinking ? { thinking: total.thinking } : {}),\n }\n }\n if (stats.cost !== undefined)\n run.cost = stats.cost\n }\n\n const session: Session = {\n ...(store ? { store } : {}),\n get id() { return data.id },\n get agentId() { return data.agentId },\n get projectRoot() { return data.projectRoot },\n get turns() { return data.turns },\n get isEmpty() { return data.turns.length === 0 },\n get status() { return data.status },\n get runs() { return data.runs },\n get metadata() { return data.metadata },\n\n startRun(runId: string, prompt?: string, extras?: { parentRunId?: string, depth?: number }) {\n data.runs.push({\n id: runId,\n startedAt: Date.now(),\n prompt: prompt ?? '',\n status: 'running',\n ...(extras?.parentRunId ? { parentRunId: extras.parentRunId } : {}),\n ...(typeof extras?.depth === 'number' ? { depth: extras.depth } : {}),\n })\n touch()\n },\n\n completeRun(runId: string, stats: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n const run = findRun(runId)\n if (run) {\n run.status = 'completed'\n run.endedAt = Date.now()\n applyRunStats(run, stats)\n }\n touch()\n },\n\n abortRun(runId: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n const run = findRun(runId)\n if (run) {\n run.status = 'aborted'\n run.endedAt = Date.now()\n // Backfill tokens when available so an aborted run's session\n // ledger reflects actual consumption rather than `0 in / 0 out`.\n if (stats)\n applyRunStats(run, stats)\n }\n touch()\n },\n\n errorRun(runId: string, error: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n const run = findRun(runId)\n if (run) {\n run.status = 'error'\n run.endedAt = Date.now()\n run.error = error\n if (stats)\n applyRunStats(run, stats)\n }\n touch()\n },\n\n async appendTurns(turns: SessionTurn[]) {\n data.turns.push(...turns)\n touch()\n if (store) {\n await store.appendTurns(data.id, turns)\n }\n },\n\n setTurns(turns: SessionTurn[]) {\n data.turns = turns\n touch()\n },\n\n setRuns(runs: SessionRun[]) {\n data.runs = runs\n touch()\n },\n\n async updateStatus(status: SessionData['status']) {\n data.status = status\n touch()\n if (store) {\n await store.updateStatus(data.id, status)\n }\n },\n\n async updateRun(run: SessionRun) {\n if (store) {\n await store.updateRun(data.id, run)\n }\n },\n\n generateTurnId() {\n if (store?.generateTurnId) {\n return store.generateTurnId()\n }\n return crypto.randomUUID()\n },\n\n setMeta(key: string, value: unknown) {\n data.metadata[key] = value\n touch()\n },\n\n async save() {\n if (!store) {\n throw new Error('No SessionStore configured. Pass a store to createSession() to enable persistence.')\n }\n await store.save(data)\n },\n\n toMessages(options?: ToWireMessagesOptions) {\n return toWireMessages(data.turns, options)\n },\n\n toJSON() {\n return structuredClone(data)\n },\n }\n\n return session\n}\n\n/**\n * Demote a persisted `'running'` status to `'idle'` (in place) and return the\n * data. A persisted `'running'` is necessarily stale: the run that set it lived\n * in another process (crash, kill -9, power loss) and cannot still be executing\n * in a freshly-loaded session. Call this on the result of a raw `store.load()`\n * so consumers don't render a ghost in-progress state or refuse a new run.\n * `loadSession` applies it automatically; direct `store.load()` callers (e.g.\n * the TUI) should run loaded data through this.\n *\n * Run RECORDS get the same treatment: the agent persists each record at\n * run start with `status: 'running'` (crash durability — see the\n * `SessionStore.updateRun` contract), so a freshly-loaded session may\n * carry `'running'` runs that died with their process. They demote to\n * `'aborted'` so replay renders a truthful \"aborted\" state instead of a\n * perpetually-in-flight run.\n */\nexport function demoteStaleRunningStatus(data: SessionData): SessionData {\n if (data.status === 'running')\n data.status = 'idle'\n for (const run of data.runs) {\n if (run.status === 'running') {\n run.status = 'aborted'\n run.endedAt ??= run.startedAt\n }\n }\n return data\n}\n\n/**\n * Load an existing session from a store.\n */\nexport async function loadSession(store: SessionStore, sessionId: string): Promise<Session | null> {\n const loaded = await store.load(sessionId)\n if (!loaded)\n return null\n\n demoteStaleRunningStatus(loaded)\n\n return createSession({ store, _data: loaded })\n}\n\n// ---------------------------------------------------------------------------\n// Re-export stores\n// ---------------------------------------------------------------------------\n\nexport type { FileMapAdapter, FileMapStoreOptions } from './file-map'\nexport { createMemoryStore } from './memory'\nexport { autoDetectAndConvert, fromAnthropic, fromOpenAI, toAnthropic, toOpenAI, toWireMessages } from './messages'\nexport type { ToWireMessagesOptions } from './messages'\nexport { createRemoteStore } from './remote'\nexport type { RemoteStoreOptions } from './remote'\n\n// NOTE: `createSqliteStore` is intentionally NOT re-exported here. It lives behind\n// the dedicated `zidane/session/sqlite` subpath so that non-Bun consumers don't\n// transitively evaluate `bun:sqlite` when they import from `zidane/session`.\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction generateId(): string {\n return `ses_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`\n}\n\nfunction isSafeExtensionStateKey(key: string): boolean {\n return typeof key === 'string' && key.length > 0 && !DANGEROUS_RECORD_KEYS.has(key)\n}\n\nfunction jsonClone<T extends JsonValue>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nfunction assertSafeExtensionStateKey(key: string, label: string): void {\n if (!isSafeExtensionStateKey(key))\n throw new Error(`Invalid extension session state ${label}.`)\n}\n\nfunction cloneExtensionStateRoot(value: unknown): Record<string, Record<string, JsonValue>> {\n return clonePlainRecord(value) as Record<string, Record<string, JsonValue>>\n}\n\nfunction clonePlainRecord(value: unknown): Record<string, JsonValue> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return {}\n const out: Record<string, JsonValue> = {}\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n if (!isSafeExtensionStateKey(key))\n continue\n if (isJsonValue(child))\n out[key] = child\n }\n return out\n}\n\nfunction isJsonValue(value: unknown, depth = 0): value is JsonValue {\n if (value === null)\n return true\n if (typeof value === 'string' || typeof value === 'boolean')\n return true\n if (typeof value === 'number')\n return Number.isFinite(value)\n if (typeof value !== 'object')\n return false\n if (depth >= 8)\n return false\n if (Array.isArray(value))\n return value.every(item => isJsonValue(item, depth + 1))\n return Object.entries(value).every(([key, child]) =>\n isSafeExtensionStateKey(key) && isJsonValue(child, depth + 1),\n )\n}\n\nfunction assertJsonBounded(value: JsonValue, maxBytes: number, label: string): void {\n const json = JSON.stringify(value)\n if (json === undefined)\n throw new Error(`${label} must be JSON serializable.`)\n if (Buffer.byteLength(json) > maxBytes)\n throw new Error(`${label} exceeds ${maxBytes} bytes.`)\n}\n"],"mappings":";;;;AAiEA,SAAS,OAAO,MAA8B;CA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AAI,UAC5B,MAAM,IAAI,MAAM,GAAG,MAAM,WAAW,SAAS,QAAQ;AACzD"}
|
package/dist/session.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { CreateSessionOptions, type FileMapAdapter, type FileMapStoreOptions, type RemoteStoreOptions, Session, type SessionContentBlock, SessionData, type SessionMessage, SessionRun, SessionStore, type SessionTurn, type ToWireMessagesOptions, autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
|
|
1
|
+
import { $f as getExtensionSessionState, Cp as fromAnthropic, Dp as toOpenAI, Ep as toAnthropic, Gf as SessionData, Jf as SessionStore, Kf as SessionMetaRow, Op as toWireMessages, Qf as demoteStaleRunningStatus, Uf as CreateSessionOptions, Wf as Session, Xf as currentExtensionSession, Yf as createSession, Zf as deleteExtensionSessionState, ap as createMemoryStore, cp as createFileMapStore, ef as SessionContentBlock, ep as loadSession, gp as ToWireMessagesOptions, if as SessionTurn, ip as createRemoteStore, np as withExtensionSession, op as FileMapAdapter, qf as SessionRun, rf as SessionMessage, rp as RemoteStoreOptions, sp as FileMapStoreOptions, tp as setExtensionSessionState, vp as autoDetectAndConvert, wp as fromOpenAI } from "./index-BGpM2YaU.js";
|
|
2
|
+
export { CreateSessionOptions, type FileMapAdapter, type FileMapStoreOptions, type RemoteStoreOptions, Session, type SessionContentBlock, SessionData, type SessionMessage, SessionMetaRow, SessionRun, SessionStore, type SessionTurn, type ToWireMessagesOptions, autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
|
package/dist/session.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { h as toWireMessages, i as autoDetectAndConvert, l as fromAnthropic, m as toOpenAI, p as toAnthropic, u as fromOpenAI } from "./messages-
|
|
2
|
-
import { a as getExtensionSessionState, c as withExtensionSession, d as createFileMapStore, i as demoteStaleRunningStatus, l as createRemoteStore, n as currentExtensionSession, o as loadSession, r as deleteExtensionSessionState, s as setExtensionSessionState, t as createSession, u as createMemoryStore } from "./session-
|
|
1
|
+
import { h as toWireMessages, i as autoDetectAndConvert, l as fromAnthropic, m as toOpenAI, p as toAnthropic, u as fromOpenAI } from "./messages-C5BDOjUG.js";
|
|
2
|
+
import { a as getExtensionSessionState, c as withExtensionSession, d as createFileMapStore, i as demoteStaleRunningStatus, l as createRemoteStore, n as currentExtensionSession, o as loadSession, r as deleteExtensionSessionState, s as setExtensionSessionState, t as createSession, u as createMemoryStore } from "./session-CsKzK8-P.js";
|
|
3
3
|
export { autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { l as errorMessage } from "./errors-DJUxZg9b.js";
|
|
2
|
-
import { A as validateSkillName, _ as lastLine, b as resolveSubdirRoot, c as parseSkillFile, g as fetchInstallSource, h as defaultWhich, j as projectUserPaths, k as validateSkillForWrite, m as defaultExec, p as InstallSourceError, v as parseInstallSource } from "./resolve-
|
|
2
|
+
import { A as validateSkillName, _ as lastLine, b as resolveSubdirRoot, c as parseSkillFile, g as fetchInstallSource, h as defaultWhich, j as projectUserPaths, k as validateSkillForWrite, m as defaultExec, p as InstallSourceError, v as parseInstallSource } from "./resolve-CC8Lmwcj.js";
|
|
3
3
|
import { basename, join, resolve } from "node:path";
|
|
4
4
|
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -292,4 +292,4 @@ function defineSkill(config) {
|
|
|
292
292
|
//#endregion
|
|
293
293
|
export { listSkillCandidates as a, installSkillFromSpec as i, SKILL_PROVENANCE_FILE as n, parseSkillInstallSpec as o, SkillInstallError as r, readSkillProvenance as s, defineSkill as t };
|
|
294
294
|
|
|
295
|
-
//# sourceMappingURL=skills-
|
|
295
|
+
//# sourceMappingURL=skills-BjeXSRlQ.js.map
|