@bastani/atomic 0.9.38-alpha.7 → 0.9.38-alpha.9
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/CHANGELOG.md +16 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +6 -0
- package/dist/builtin/subagents/README.md +9 -4
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +23 -13
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +6 -0
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/durable/journal/legacy-journal-tables.d.ts +42 -0
- package/dist/builtin/workflows/src/durable/journal/sql-run-journal.d.ts +3 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +204 -51
- package/dist/builtin/workflows/src/index.js +170 -17
- package/dist/core/session-manager-storage.d.ts +1 -1
- package/dist/core/session-manager-storage.d.ts.map +1 -1
- package/dist/core/session-manager-storage.js +2 -3
- package/dist/core/session-manager-storage.js.map +1 -1
- package/dist/core/session-storage.d.ts.map +1 -1
- package/dist/core/session-storage.js +20 -4
- package/dist/core/session-storage.js.map +1 -1
- package/dist/core/storage/session/jsonl-session-store.d.ts +7 -1
- package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/jsonl-session-store.js +29 -20
- package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
- package/dist/core/storage/session/legacy-format.d.ts +2 -0
- package/dist/core/storage/session/legacy-format.d.ts.map +1 -1
- package/dist/core/storage/session/legacy-format.js +55 -29
- package/dist/core/storage/session/legacy-format.js.map +1 -1
- package/dist/core/storage/session/legacy-session-store.d.ts +63 -0
- package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -0
- package/dist/core/storage/session/legacy-session-store.js +239 -0
- package/dist/core/storage/session/legacy-session-store.js.map +1 -0
- package/dist/core/storage/session/legacy-session-summary.d.ts +11 -0
- package/dist/core/storage/session/legacy-session-summary.d.ts.map +1 -0
- package/dist/core/storage/session/legacy-session-summary.js +103 -0
- package/dist/core/storage/session/legacy-session-summary.js.map +1 -0
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-session.js +4 -1
- package/dist/main-session.js.map +1 -1
- package/docs/docs.json +5 -2
- package/docs/llama-cpp.md +94 -1
- package/docs/session-format.md +1 -1
- package/docs/sessions.md +4 -2
- package/docs/subagents.md +19 -6
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
- package/docs/nvidia-rtx-llama-cpp.md +0 -101
|
@@ -1083,10 +1083,89 @@ import {
|
|
|
1083
1083
|
// dist/builtin/workflows/src/durable/journal/sql-run-journal.ts
|
|
1084
1084
|
import {
|
|
1085
1085
|
assertStorageSchemaVersion,
|
|
1086
|
-
renderStorageIdentifiers,
|
|
1086
|
+
renderStorageIdentifiers as renderStorageIdentifiers2,
|
|
1087
1087
|
StorageSchemaVersionError as StorageSchemaVersionError2,
|
|
1088
1088
|
StorageUnavailableError as StorageUnavailableError2
|
|
1089
1089
|
} from "@bastani/atomic/storage";
|
|
1090
|
+
|
|
1091
|
+
// dist/builtin/workflows/src/durable/journal/legacy-journal-tables.ts
|
|
1092
|
+
import {
|
|
1093
|
+
renderStorageIdentifiers
|
|
1094
|
+
} from "@bastani/atomic/storage";
|
|
1095
|
+
var CURRENT = renderStorageIdentifiers("journal", {
|
|
1096
|
+
...JOURNAL_TABLES,
|
|
1097
|
+
legacyDeleted: "legacy_deleted",
|
|
1098
|
+
migrations: "migrations"
|
|
1099
|
+
});
|
|
1100
|
+
var COPIED_ALL_MARKER = "unprefixed-journal-tables";
|
|
1101
|
+
var LEGACY_COLUMNS = {
|
|
1102
|
+
meta: [JOURNAL_COLUMNS.schemaVersion],
|
|
1103
|
+
runs: [JOURNAL_COLUMNS.runId, JOURNAL_COLUMNS.name, JOURNAL_COLUMNS.cwd, JOURNAL_COLUMNS.createdAt, JOURNAL_COLUMNS.status, JOURNAL_COLUMNS.headerJson],
|
|
1104
|
+
events: [JOURNAL_COLUMNS.runId, JOURNAL_COLUMNS.seq, JOURNAL_COLUMNS.epoch, JOURNAL_COLUMNS.key, JOURNAL_COLUMNS.type, JOURNAL_COLUMNS.payload, JOURNAL_COLUMNS.at],
|
|
1105
|
+
leases: [JOURNAL_COLUMNS.runId, JOURNAL_COLUMNS.holderId, JOURNAL_COLUMNS.epoch, JOURNAL_COLUMNS.renewedAt]
|
|
1106
|
+
};
|
|
1107
|
+
var PENDING_LEGACY_RUNS = `SELECT ${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.headerJson}, ${JOURNAL_COLUMNS.status} FROM ${JOURNAL_TABLES.runs}
|
|
1108
|
+
WHERE ${JOURNAL_COLUMNS.runId} NOT IN (SELECT ${JOURNAL_COLUMNS.runId} FROM ${CURRENT.runs})
|
|
1109
|
+
AND ${JOURNAL_COLUMNS.runId} NOT IN (SELECT ${JOURNAL_COLUMNS.runId} FROM ${CURRENT.legacyDeleted})`;
|
|
1110
|
+
async function hasLegacyTable(tx, table) {
|
|
1111
|
+
const columns = await tx.all("SELECT name FROM pragma_table_info(?)", JOURNAL_TABLES[table]);
|
|
1112
|
+
const names = new Set(columns.map((column) => column.name));
|
|
1113
|
+
return columns.length === LEGACY_COLUMNS[table].length && LEGACY_COLUMNS[table].every((name) => names.has(name));
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
class LegacyJournalRuns {
|
|
1117
|
+
static async open(database) {
|
|
1118
|
+
try {
|
|
1119
|
+
return await database.transaction(async (tx) => {
|
|
1120
|
+
for (const table of ["meta", "runs", "events"]) {
|
|
1121
|
+
if (!await hasLegacyTable(tx, table))
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
const versions = await tx.all(`SELECT ${JOURNAL_COLUMNS.schemaVersion} FROM ${JOURNAL_TABLES.meta}`);
|
|
1125
|
+
if (versions.length !== 1 || Number(versions[0][JOURNAL_COLUMNS.schemaVersion]) !== JOURNAL_SCHEMA_VERSION)
|
|
1126
|
+
return;
|
|
1127
|
+
const copiedAll = await tx.get(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`, CURRENT.migrations) !== undefined && await tx.get(`SELECT name FROM ${CURRENT.migrations} WHERE name = ?`, COPIED_ALL_MARKER) !== undefined;
|
|
1128
|
+
if (copiedAll)
|
|
1129
|
+
return;
|
|
1130
|
+
await tx.exec(`CREATE TABLE IF NOT EXISTS ${CURRENT.legacyDeleted}(${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY, deleted_at INTEGER NOT NULL)`);
|
|
1131
|
+
return new LegacyJournalRuns;
|
|
1132
|
+
});
|
|
1133
|
+
} catch {
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
async pending(executor, filter) {
|
|
1138
|
+
return executor.all(`${PENDING_LEGACY_RUNS}${filter?.cwd === undefined ? "" : ` AND ${JOURNAL_COLUMNS.cwd} = ?`}`, ...filter?.cwd === undefined ? [] : [filter.cwd]);
|
|
1139
|
+
}
|
|
1140
|
+
async find(executor, runId) {
|
|
1141
|
+
return executor.get(`${PENDING_LEGACY_RUNS} AND ${JOURNAL_COLUMNS.runId} = ?`, runId);
|
|
1142
|
+
}
|
|
1143
|
+
async events(executor, runId, fromSeq, limit) {
|
|
1144
|
+
return executor.all(`SELECT ${LEGACY_COLUMNS.events.join(", ")} FROM ${JOURNAL_TABLES.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.seq} >= ? ORDER BY ${JOURNAL_COLUMNS.seq} LIMIT ?`, runId, fromSeq, limit);
|
|
1145
|
+
}
|
|
1146
|
+
async eventByKey(executor, runId, key) {
|
|
1147
|
+
return executor.get(`SELECT ${LEGACY_COLUMNS.events.join(", ")} FROM ${JOURNAL_TABLES.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.key} = ?`, runId, key);
|
|
1148
|
+
}
|
|
1149
|
+
async convert(tx, runId) {
|
|
1150
|
+
if (await this.find(tx, runId) === undefined)
|
|
1151
|
+
return false;
|
|
1152
|
+
const eventColumns = LEGACY_COLUMNS.events.join(", ");
|
|
1153
|
+
await tx.run(`INSERT OR IGNORE INTO ${CURRENT.events}(${eventColumns}) SELECT ${eventColumns} FROM ${JOURNAL_TABLES.events} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
|
|
1154
|
+
if (await hasLegacyTable(tx, "leases")) {
|
|
1155
|
+
await tx.run(`INSERT OR IGNORE INTO ${CURRENT.leases}(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.holderId}, ${JOURNAL_COLUMNS.epoch}, ${JOURNAL_COLUMNS.renewedAt}) SELECT ${JOURNAL_COLUMNS.runId}, NULL, ${JOURNAL_COLUMNS.epoch}, ${JOURNAL_COLUMNS.renewedAt} FROM ${JOURNAL_TABLES.leases} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
|
|
1156
|
+
}
|
|
1157
|
+
const runColumns = LEGACY_COLUMNS.runs.join(", ");
|
|
1158
|
+
await tx.run(`INSERT INTO ${CURRENT.runs}(${runColumns}) SELECT ${runColumns} FROM ${JOURNAL_TABLES.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
|
|
1159
|
+
return true;
|
|
1160
|
+
}
|
|
1161
|
+
async markDeleted(tx, runId) {
|
|
1162
|
+
if (await tx.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${JOURNAL_TABLES.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId) === undefined)
|
|
1163
|
+
return;
|
|
1164
|
+
await tx.run(`INSERT OR IGNORE INTO ${CURRENT.legacyDeleted} VALUES (?, ?)`, runId, Date.now());
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
// dist/builtin/workflows/src/durable/journal/sql-run-journal.ts
|
|
1090
1169
|
var STORE_NOW = "CAST(unixepoch('subsec') * 1000 AS INTEGER)";
|
|
1091
1170
|
function entryFromRow(row) {
|
|
1092
1171
|
const key = row[JOURNAL_COLUMNS.key];
|
|
@@ -1106,12 +1185,14 @@ class SqlRunJournal {
|
|
|
1106
1185
|
closePromise;
|
|
1107
1186
|
database;
|
|
1108
1187
|
tables;
|
|
1109
|
-
|
|
1188
|
+
legacy;
|
|
1189
|
+
constructor(database, tables, legacy) {
|
|
1110
1190
|
this.database = database;
|
|
1111
1191
|
this.tables = tables;
|
|
1192
|
+
this.legacy = legacy;
|
|
1112
1193
|
}
|
|
1113
1194
|
static async open(database, options = {}) {
|
|
1114
|
-
const t =
|
|
1195
|
+
const t = renderStorageIdentifiers2("journal", JOURNAL_TABLES, options.prefix);
|
|
1115
1196
|
await database.transaction(async (tx) => {
|
|
1116
1197
|
await tx.exec(`CREATE TABLE IF NOT EXISTS ${t.meta}(${JOURNAL_COLUMNS.schemaVersion} INTEGER NOT NULL)`);
|
|
1117
1198
|
const versions = await tx.all(`SELECT ${JOURNAL_COLUMNS.schemaVersion} FROM ${t.meta}`);
|
|
@@ -1145,7 +1226,8 @@ class SqlRunJournal {
|
|
|
1145
1226
|
);
|
|
1146
1227
|
`);
|
|
1147
1228
|
});
|
|
1148
|
-
|
|
1229
|
+
const legacy = options.prefix ? undefined : await LegacyJournalRuns.open(database);
|
|
1230
|
+
return new SqlRunJournal(database, t, legacy);
|
|
1149
1231
|
}
|
|
1150
1232
|
get descriptor() {
|
|
1151
1233
|
return { ...this.database.descriptor };
|
|
@@ -1181,6 +1263,8 @@ class SqlRunJournal {
|
|
|
1181
1263
|
throw json;
|
|
1182
1264
|
const { runs } = this.tables;
|
|
1183
1265
|
return this.operation(async () => {
|
|
1266
|
+
if (await this.legacy?.find(this.database, header.runId))
|
|
1267
|
+
return "exists";
|
|
1184
1268
|
const result = await this.database.run(`INSERT INTO ${runs} VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(${JOURNAL_COLUMNS.runId}) DO NOTHING`, header.runId, header.name, header.cwd, header.createdAt, header.status, json);
|
|
1185
1269
|
return result.changes === 1 ? "created" : "exists";
|
|
1186
1270
|
});
|
|
@@ -1190,7 +1274,8 @@ class SqlRunJournal {
|
|
|
1190
1274
|
validateText("runId", runId);
|
|
1191
1275
|
return this.operation(async () => {
|
|
1192
1276
|
const row = await this.database.get(`SELECT ${JOURNAL_COLUMNS.headerJson}, ${JOURNAL_COLUMNS.status} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
|
|
1193
|
-
|
|
1277
|
+
const found = row ?? await this.legacy?.find(this.database, runId);
|
|
1278
|
+
return found ? { ...JSON.parse(found[JOURNAL_COLUMNS.headerJson]), status: found[JOURNAL_COLUMNS.status] } : undefined;
|
|
1194
1279
|
});
|
|
1195
1280
|
}
|
|
1196
1281
|
async listRuns(filter) {
|
|
@@ -1199,13 +1284,23 @@ class SqlRunJournal {
|
|
|
1199
1284
|
validateText("cwd", filter.cwd);
|
|
1200
1285
|
return this.operation(async () => {
|
|
1201
1286
|
const rows = await this.database.all(`SELECT ${JOURNAL_COLUMNS.headerJson}, ${JOURNAL_COLUMNS.status} FROM ${this.tables.runs} ${filter?.cwd === undefined ? "" : `WHERE ${JOURNAL_COLUMNS.cwd} = ?`} ORDER BY ${JOURNAL_COLUMNS.runId}`, ...filter?.cwd === undefined ? [] : [filter.cwd]);
|
|
1202
|
-
|
|
1287
|
+
const legacy = await this.legacy?.pending(this.database, filter) ?? [];
|
|
1288
|
+
return [...rows, ...legacy].map((row) => ({ ...JSON.parse(row[JOURNAL_COLUMNS.headerJson]), status: row[JOURNAL_COLUMNS.status] })).sort((left, right) => left.runId < right.runId ? -1 : left.runId > right.runId ? 1 : 0);
|
|
1203
1289
|
});
|
|
1204
1290
|
}
|
|
1205
1291
|
async requireRun(tx, runId) {
|
|
1206
|
-
if (
|
|
1292
|
+
if (await tx.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId))
|
|
1293
|
+
return;
|
|
1294
|
+
if (!await this.legacy?.convert(tx, runId))
|
|
1207
1295
|
throw new RunNotFoundError(runId);
|
|
1208
1296
|
}
|
|
1297
|
+
async isUnconvertedLegacyRun(runId) {
|
|
1298
|
+
if (this.legacy === undefined)
|
|
1299
|
+
return false;
|
|
1300
|
+
if (await this.database.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId))
|
|
1301
|
+
return false;
|
|
1302
|
+
return await this.legacy.find(this.database, runId) !== undefined;
|
|
1303
|
+
}
|
|
1209
1304
|
async leaseRow(tx, runId) {
|
|
1210
1305
|
const row = await tx.get(`SELECT * FROM ${this.tables.leases} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
|
|
1211
1306
|
return row ? { ...row, [JOURNAL_COLUMNS.epoch]: journalCounter(runId, "epoch", row[JOURNAL_COLUMNS.epoch]) } : undefined;
|
|
@@ -1345,9 +1440,11 @@ class SqlRunJournal {
|
|
|
1345
1440
|
this.assertOpen();
|
|
1346
1441
|
validateText("runId", runId);
|
|
1347
1442
|
let nextSeq = fromSeq;
|
|
1443
|
+
const legacy = this.legacy;
|
|
1444
|
+
const readsLegacy = legacy !== undefined && await this.operation(() => this.isUnconvertedLegacyRun(runId));
|
|
1348
1445
|
for (;; ) {
|
|
1349
1446
|
const page = await this.operation(async () => {
|
|
1350
|
-
const rows = await this.database.all(`SELECT * FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.seq} >= ? ORDER BY ${JOURNAL_COLUMNS.seq} LIMIT ?`, runId, nextSeq, JOURNAL_READ_PAGE_SIZE);
|
|
1447
|
+
const rows = readsLegacy ? await legacy.events(this.database, runId, nextSeq, JOURNAL_READ_PAGE_SIZE) : await this.database.all(`SELECT * FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.seq} >= ? ORDER BY ${JOURNAL_COLUMNS.seq} LIMIT ?`, runId, nextSeq, JOURNAL_READ_PAGE_SIZE);
|
|
1351
1448
|
return rows.map(entryFromRow);
|
|
1352
1449
|
});
|
|
1353
1450
|
for (const entry of page) {
|
|
@@ -1366,7 +1463,7 @@ class SqlRunJournal {
|
|
|
1366
1463
|
validateText("runId", runId);
|
|
1367
1464
|
validateText("key", key);
|
|
1368
1465
|
return this.operation(async () => {
|
|
1369
|
-
const row = await this.database.get(`SELECT * FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.key} = ?`, runId, key);
|
|
1466
|
+
const row = this.legacy !== undefined && await this.isUnconvertedLegacyRun(runId) ? await this.legacy.eventByKey(this.database, runId, key) : await this.database.get(`SELECT * FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.key} = ?`, runId, key);
|
|
1370
1467
|
return row ? entryFromRow(row) : undefined;
|
|
1371
1468
|
});
|
|
1372
1469
|
}
|
|
@@ -1391,6 +1488,7 @@ class SqlRunJournal {
|
|
|
1391
1488
|
}));
|
|
1392
1489
|
}
|
|
1393
1490
|
async deleteRunData(tx, runId) {
|
|
1491
|
+
await this.legacy?.markDeleted(tx, runId);
|
|
1394
1492
|
await this.leaseRow(tx, runId);
|
|
1395
1493
|
await tx.run(`UPDATE ${this.tables.leases} SET ${JOURNAL_COLUMNS.holderId} = ? WHERE ${JOURNAL_COLUMNS.runId} = ?`, JOURNAL_LEASE.unheld, runId);
|
|
1396
1494
|
await tx.run(`DELETE FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
|
|
@@ -6349,6 +6447,9 @@ ${formatValidationErrors(errors)}`);
|
|
|
6349
6447
|
}
|
|
6350
6448
|
return resolved;
|
|
6351
6449
|
}
|
|
6450
|
+
// dist/builtin/workflows/src/durable/backend.ts
|
|
6451
|
+
import { closeSync, openSync, readSync } from "node:fs";
|
|
6452
|
+
|
|
6352
6453
|
// dist/builtin/workflows/src/durable/resume-eligibility.ts
|
|
6353
6454
|
function isDurableWorkflowResumable(candidate) {
|
|
6354
6455
|
const isRoot = candidate.rootWorkflowId === undefined || candidate.rootWorkflowId === candidate.workflowId;
|
|
@@ -6384,6 +6485,33 @@ function canonicalJsonString(value) {
|
|
|
6384
6485
|
}
|
|
6385
6486
|
|
|
6386
6487
|
// dist/builtin/workflows/src/durable/backend.ts
|
|
6488
|
+
var SESSION_HEADER_READ_LIMIT_BYTES = 64 * 1024;
|
|
6489
|
+
function readSessionHeaderId(sessionFile) {
|
|
6490
|
+
let fd;
|
|
6491
|
+
try {
|
|
6492
|
+
fd = openSync(sessionFile, "r");
|
|
6493
|
+
} catch {
|
|
6494
|
+
return;
|
|
6495
|
+
}
|
|
6496
|
+
try {
|
|
6497
|
+
const buffer = Buffer.alloc(SESSION_HEADER_READ_LIMIT_BYTES);
|
|
6498
|
+
const bytesRead = readSync(fd, buffer, 0, buffer.length, 0);
|
|
6499
|
+
const firstLine = buffer.subarray(0, bytesRead).toString("utf8").replace(/^\uFEFF/, "").split(`
|
|
6500
|
+
`)[0];
|
|
6501
|
+
const header = JSON.parse(firstLine ?? "");
|
|
6502
|
+
return header.type === "session" && typeof header.id === "string" ? header.id : undefined;
|
|
6503
|
+
} catch {
|
|
6504
|
+
return;
|
|
6505
|
+
} finally {
|
|
6506
|
+
closeSync(fd);
|
|
6507
|
+
}
|
|
6508
|
+
}
|
|
6509
|
+
function migrateStageSessionCheckpoint(checkpoint) {
|
|
6510
|
+
if (checkpoint.sessionId !== undefined || checkpoint.sessionFile === undefined)
|
|
6511
|
+
return checkpoint;
|
|
6512
|
+
const sessionId = readSessionHeaderId(checkpoint.sessionFile);
|
|
6513
|
+
return sessionId === undefined ? checkpoint : { ...checkpoint, sessionId };
|
|
6514
|
+
}
|
|
6387
6515
|
function replacePendingStageMessagesForRun(existing, logicalRunId, messages) {
|
|
6388
6516
|
if (messages.some((entry) => entry.runId !== logicalRunId)) {
|
|
6389
6517
|
throw new Error(`atomic-workflows: pending-stage persistence mixed logical run ${logicalRunId}`);
|
|
@@ -6518,7 +6646,8 @@ class JournalProjection {
|
|
|
6518
6646
|
return this.stickyReceipts.get(workflowId)?.has(name) ?? false;
|
|
6519
6647
|
});
|
|
6520
6648
|
}
|
|
6521
|
-
recordCheckpoint(
|
|
6649
|
+
recordCheckpoint(recorded) {
|
|
6650
|
+
const checkpoint = recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded;
|
|
6522
6651
|
const currentCheckpoint = checkpoint.kind === "stage" && checkpoint.topology === undefined ? {
|
|
6523
6652
|
...checkpoint,
|
|
6524
6653
|
topology: {
|
|
@@ -8552,6 +8681,7 @@ function createDurableStagePrimitive(input) {
|
|
|
8552
8681
|
...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
|
|
8553
8682
|
...isMidSessionResume ? {
|
|
8554
8683
|
resumeFromSessionId: session.sessionId,
|
|
8684
|
+
...session.sessionFile !== undefined ? { resumeFromLegacySessionFile: session.sessionFile } : {},
|
|
8555
8685
|
routerSelection: session.routerSelection,
|
|
8556
8686
|
durableAccumulatedDurationMs: session.durationMs ?? 0
|
|
8557
8687
|
} : {}
|
|
@@ -8611,6 +8741,7 @@ function createDurableTaskPrimitive(input) {
|
|
|
8611
8741
|
...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
|
|
8612
8742
|
...session?.sessionId !== undefined ? {
|
|
8613
8743
|
resumeFromSessionId: session.sessionId,
|
|
8744
|
+
...session.sessionFile !== undefined ? { resumeFromLegacySessionFile: session.sessionFile } : {},
|
|
8614
8745
|
routerSelection: session.routerSelection,
|
|
8615
8746
|
durableAccumulatedDurationMs: session.durationMs ?? 0
|
|
8616
8747
|
} : {}
|
|
@@ -15338,6 +15469,7 @@ function createDurableStageSessionRecorder(input) {
|
|
|
15338
15469
|
|
|
15339
15470
|
// dist/builtin/workflows/src/shared/stage-session-store.ts
|
|
15340
15471
|
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
15472
|
+
import { dirname as dirname9, resolve as resolve9 } from "node:path";
|
|
15341
15473
|
import {
|
|
15342
15474
|
JsonlSessionStore,
|
|
15343
15475
|
resolveSessionStore,
|
|
@@ -15370,6 +15502,24 @@ async function forkStageSession(store, sessionId, cwd, options, destination = st
|
|
|
15370
15502
|
}, source.entries);
|
|
15371
15503
|
return SessionManager.open(destination, id, cwd);
|
|
15372
15504
|
}
|
|
15505
|
+
async function migrateLegacyStageSession(store, sessionId, sessionFile) {
|
|
15506
|
+
if (sessionFile === undefined || await store.readHeader(sessionId) !== undefined)
|
|
15507
|
+
return;
|
|
15508
|
+
const location = resolve9(sessionFile);
|
|
15509
|
+
const legacy = await JsonlSessionStore.open(dirname9(location), { exactDirectory: true, scanExisting: false });
|
|
15510
|
+
try {
|
|
15511
|
+
for await (const file of legacy.scanFiles()) {
|
|
15512
|
+
if (resolve9(file.location) !== location || file.header.id !== sessionId)
|
|
15513
|
+
continue;
|
|
15514
|
+
const snapshot = await file.read();
|
|
15515
|
+
if (await store.readHeader(sessionId) === undefined)
|
|
15516
|
+
await store.create(snapshot.header, snapshot.entries);
|
|
15517
|
+
return;
|
|
15518
|
+
}
|
|
15519
|
+
} finally {
|
|
15520
|
+
await legacy.close();
|
|
15521
|
+
}
|
|
15522
|
+
}
|
|
15373
15523
|
|
|
15374
15524
|
// dist/builtin/workflows/src/durable/completed-catalog-stage-groups.ts
|
|
15375
15525
|
function validBoundaryRecordSet(checkpoints, strict) {
|
|
@@ -19129,6 +19279,7 @@ async function stripWorkflowOnlyOptions2(options, defaultSessionDir, meta, pendi
|
|
|
19129
19279
|
context,
|
|
19130
19280
|
forkFromSessionId,
|
|
19131
19281
|
resumeFromSessionId,
|
|
19282
|
+
resumeFromLegacySessionFile,
|
|
19132
19283
|
sessionStore,
|
|
19133
19284
|
durableReplayKey: _durableReplayKey,
|
|
19134
19285
|
durableAccumulatedDurationMs: _durableAccumulatedDurationMs,
|
|
@@ -19143,7 +19294,9 @@ async function stripWorkflowOnlyOptions2(options, defaultSessionDir, meta, pendi
|
|
|
19143
19294
|
} = options;
|
|
19144
19295
|
const cwd = sessionOptions.cwd ?? process.cwd();
|
|
19145
19296
|
if (resumeFromSessionId !== undefined) {
|
|
19146
|
-
|
|
19297
|
+
const store = await stageSessionStore(options, defaultSessionDir);
|
|
19298
|
+
await migrateLegacyStageSession(store, resumeFromSessionId, resumeFromLegacySessionFile);
|
|
19299
|
+
sessionOptions.sessionManager = await SessionManager2.open(store, resumeFromSessionId, cwd);
|
|
19147
19300
|
} else if (context === "fork" && forkFromSessionId !== undefined) {
|
|
19148
19301
|
sessionOptions.sessionManager = await forkStageSession(await stageSessionStore(options, defaultSessionDir), forkFromSessionId, cwd, classification);
|
|
19149
19302
|
} else if (sessionOptions.sessionManager === undefined) {
|
|
@@ -21113,7 +21266,7 @@ class StageSessionController {
|
|
|
21113
21266
|
// dist/builtin/workflows/src/runs/foreground/stage-runner-output.ts
|
|
21114
21267
|
import { createHash as createHash3 } from "node:crypto";
|
|
21115
21268
|
import { mkdir as mkdir2, writeFile } from "node:fs/promises";
|
|
21116
|
-
import { basename as basename5, dirname as
|
|
21269
|
+
import { basename as basename5, dirname as dirname10, isAbsolute as isAbsolute9, join as join12, resolve as resolve10 } from "node:path";
|
|
21117
21270
|
var DEFAULT_MAX_OUTPUT_BYTES = 200 * 1024;
|
|
21118
21271
|
var DEFAULT_MAX_OUTPUT_LINES = 5000;
|
|
21119
21272
|
function normalizeMaxOutput2(maxOutput) {
|
|
@@ -21223,7 +21376,7 @@ function renderTranscript(messages, fallbackOutput) {
|
|
|
21223
21376
|
`);
|
|
21224
21377
|
}
|
|
21225
21378
|
function savedOutputReference(outputPath, fullOutput, transcriptPathValue, transcriptText, transcriptAvailable, warning) {
|
|
21226
|
-
const absolutePath =
|
|
21379
|
+
const absolutePath = resolve10(outputPath);
|
|
21227
21380
|
const bytes = Buffer.byteLength(fullOutput, "utf8");
|
|
21228
21381
|
const lines = countLines(fullOutput);
|
|
21229
21382
|
const transcriptBytes = Buffer.byteLength(transcriptText, "utf8");
|
|
@@ -21238,8 +21391,8 @@ function resolveOutputPath(output, runtimeCwd, requestedCwd) {
|
|
|
21238
21391
|
return;
|
|
21239
21392
|
if (isAbsolute9(output))
|
|
21240
21393
|
return output;
|
|
21241
|
-
const baseCwd = requestedCwd === undefined ? runtimeCwd : isAbsolute9(requestedCwd) ? requestedCwd :
|
|
21242
|
-
return
|
|
21394
|
+
const baseCwd = requestedCwd === undefined ? runtimeCwd : isAbsolute9(requestedCwd) ? requestedCwd : resolve10(runtimeCwd, requestedCwd);
|
|
21395
|
+
return resolve10(baseCwd, output);
|
|
21243
21396
|
}
|
|
21244
21397
|
function degenerateWarning(fullOutput) {
|
|
21245
21398
|
return fullOutput.trim().length === 0 ? "WARNING: the stage artifact is empty; search the companion transcript for this stage's work." : undefined;
|
|
@@ -21298,7 +21451,7 @@ async function finalizePromptOutput(fullOutput, outputOptions, runtimeCwd, runId
|
|
|
21298
21451
|
const transcriptFile = transcriptPath(runId, outputPath);
|
|
21299
21452
|
const transcript = renderTranscript(messages, fullOutput);
|
|
21300
21453
|
try {
|
|
21301
|
-
await mkdir2(
|
|
21454
|
+
await mkdir2(dirname10(outputPath), { recursive: true });
|
|
21302
21455
|
await writeFile(outputPath, fullOutput, "utf8");
|
|
21303
21456
|
} catch (err) {
|
|
21304
21457
|
return `${displayOutput}
|
|
@@ -21310,7 +21463,7 @@ ${err instanceof Error ? err.message : String(err)}`;
|
|
|
21310
21463
|
let transcriptError;
|
|
21311
21464
|
try {
|
|
21312
21465
|
await ensureWorkflowArtifactRunDirectory(runId);
|
|
21313
|
-
await mkdir2(
|
|
21466
|
+
await mkdir2(dirname10(transcriptFile), { recursive: true });
|
|
21314
21467
|
await writeFile(transcriptFile, transcript, "utf8");
|
|
21315
21468
|
transcriptAvailable = true;
|
|
21316
21469
|
} catch (err) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { FileEntry, SessionHeader } from "./session-manager-types.ts";
|
|
2
2
|
export declare function parseStoredSessionEntries(content: string): FileEntry[];
|
|
3
3
|
export declare function upgradeStoredSessionEntries(entries: FileEntry[], path: string): FileEntry[];
|
|
4
4
|
/** Exported for testing */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-manager-storage.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-storage.ts"],"names":[],"mappings":"AAKA,OAAO,
|
|
1
|
+
{"version":3,"file":"session-manager-storage.d.ts","sourceRoot":"","sources":["../../src/core/session-manager-storage.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAgB,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAiCzF,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,CAOtE;AAED,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,SAAS,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,CAS3F;AAED,2BAA2B;AAC3B,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,CAsCjE;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,CAOhE;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,aAAa,GAAG,IAAI,CA0CxE;AAED,2FAA2F;AAC3F,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAElF;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM,GAAG,SAAS,CAG7E;AAED,2BAA2B;AAC3B,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,EAAE,eAAe,UAAQ,GAAG,MAAM,GAAG,IAAI,CA6B9G;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,MAAM,CAEpE;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,OAAO,CAKpE;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAIjD"}
|
|
@@ -3,10 +3,9 @@ import { join } from "path";
|
|
|
3
3
|
import { StringDecoder } from "string_decoder";
|
|
4
4
|
import { createSessionCwdMatcher, normalizePath, resolvePath } from "../utils/paths.js";
|
|
5
5
|
import { isClassifiedWorkflowSession } from "./session-manager-classification.js";
|
|
6
|
-
import { CURRENT_SESSION_VERSION, } from "./session-manager-types.js";
|
|
7
6
|
import { validateSessionFileEntries } from "./session-manager-validation.js";
|
|
8
7
|
import { StorageUnavailableError } from "./storage/session/errors.js";
|
|
9
|
-
import { upgradeLegacySessionEntries } from "./storage/session/legacy-format.js";
|
|
8
|
+
import { isCurrentSessionHeader, upgradeLegacySessionEntries, } from "./storage/session/legacy-format.js";
|
|
10
9
|
const SESSION_READ_BUFFER_SIZE = 1024 * 1024;
|
|
11
10
|
/**
|
|
12
11
|
* Dedicated small read chunk for header-only reads. Session headers are small
|
|
@@ -41,7 +40,7 @@ export function parseStoredSessionEntries(content) {
|
|
|
41
40
|
}
|
|
42
41
|
export function upgradeStoredSessionEntries(entries, path) {
|
|
43
42
|
const header = entries[0];
|
|
44
|
-
if (header?.type !== "session" || header
|
|
43
|
+
if (header?.type !== "session" || isCurrentSessionHeader(header))
|
|
45
44
|
return entries;
|
|
46
45
|
const upgraded = upgradeLegacySessionEntries(header, entries.slice(1), path);
|
|
47
46
|
return [upgraded.header, ...upgraded.entries];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-manager-storage.js","sourceRoot":"","sources":["../../src/core/session-manager-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,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iD;YAClD,CAAC;QACF,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAC;IACb,CAAC;AACF,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,OAAoB;IAC3D,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AACxE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,OAAoB;IAC1D,OAAO,OAAO,CAAC,IAAI,CAClB,CAAC,KAAK,EAAyB,EAAE,CAChC,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW,CAAC,CAClG,CAAC;AACH,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,GAAW;IAC1C,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QACtB,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACrC,CAAC;AACF,CAAC","sourcesContent":["import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readSync, statSync } from \"fs\";\nimport { join } from \"path\";\nimport { StringDecoder } from \"string_decoder\";\nimport { createSessionCwdMatcher, normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport { isClassifiedWorkflowSession } from \"./session-manager-classification.ts\";\nimport {\n\tCURRENT_SESSION_VERSION,\n\ttype FileEntry,\n\ttype SessionEntry,\n\ttype SessionHeader,\n} from \"./session-manager-types.ts\";\nimport { validateSessionFileEntries } from \"./session-manager-validation.ts\";\n\nimport { StorageUnavailableError } from \"./storage/session/errors.js\";\nimport { type StoredSessionHeader, upgradeLegacySessionEntries } from \"./storage/session/legacy-format.js\";\n\nconst SESSION_READ_BUFFER_SIZE = 1024 * 1024;\n/**\n * Dedicated small read chunk for header-only reads. Session headers are small\n * (typically a few KB), so reading in 64KB chunks avoids allocating/transferring\n * the full 1MiB transcript buffer just to inspect the first line during listing\n * and resume-history prefiltering.\n */\nconst HEADER_READ_BUFFER_SIZE = 64 * 1024;\n\nfunction parseSessionEntryLine(line: string, path: string, validateHeader = true): FileEntry | undefined {\n\tif (!line.trim()) return undefined;\n\tlet entry: FileEntry;\n\ttry {\n\t\tentry = JSON.parse(line) as FileEntry;\n\t} catch (cause) {\n\t\tthrow new StorageUnavailableError({ adapter: \"jsonl\", location: path }, cause as Error);\n\t}\n\tif (validateHeader && entry?.type === \"session\") {\n\t\tvalidateSessionFileEntries([entry], path);\n\t}\n\treturn entry;\n}\n\nexport function parseStoredSessionEntries(content: string): FileEntry[] {\n\tconst entries: FileEntry[] = [];\n\tfor (const line of content.trim().split(\"\\n\")) {\n\t\tconst entry = parseSessionEntryLine(line, \"session content\", false);\n\t\tif (entry !== undefined) entries.push(entry);\n\t}\n\treturn entries;\n}\n\nexport function upgradeStoredSessionEntries(entries: FileEntry[], path: string): FileEntry[] {\n\tconst header = entries[0];\n\tif (header?.type !== \"session\" || header.version === CURRENT_SESSION_VERSION) return entries;\n\tconst upgraded = upgradeLegacySessionEntries(\n\t\theader as StoredSessionHeader,\n\t\tentries.slice(1) as SessionEntry[],\n\t\tpath,\n\t);\n\treturn [upgraded.header, ...upgraded.entries];\n}\n\n/** Exported for testing */\nexport function loadEntriesFromFile(filePath: string): FileEntry[] {\n\tconst resolvedFilePath = normalizePath(filePath);\n\tif (!existsSync(resolvedFilePath)) return [];\n\n\tconst entries: FileEntry[] = [];\n\tlet pending = \"\";\n\tconst fd = openSync(resolvedFilePath, \"r\");\n\ttry {\n\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\tconst buffer = Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);\n\n\t\twhile (true) {\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, buffer.length, null);\n\t\t\tif (bytesRead === 0) break;\n\n\t\t\tpending += decoder.write(buffer.subarray(0, bytesRead));\n\t\t\tlet lineStart = 0;\n\t\t\tlet newlineIndex = pending.indexOf(\"\\n\", lineStart);\n\t\t\twhile (newlineIndex !== -1) {\n\t\t\t\tconst entry = parseSessionEntryLine(pending.slice(lineStart, newlineIndex), resolvedFilePath);\n\t\t\t\tif (entry !== undefined) entries.push(entry);\n\t\t\t\tlineStart = newlineIndex + 1;\n\t\t\t\tnewlineIndex = pending.indexOf(\"\\n\", lineStart);\n\t\t\t}\n\t\t\tpending = pending.slice(lineStart);\n\t\t}\n\n\t\tpending += decoder.end();\n\t\tconst finalEntry = parseSessionEntryLine(pending, resolvedFilePath);\n\t\tif (finalEntry !== undefined) entries.push(finalEntry);\n\t} finally {\n\t\tcloseSync(fd);\n\t}\n\n\tif (entries.length === 0) return entries;\n\tvalidateSessionFileEntries(entries, resolvedFilePath);\n\n\treturn entries;\n}\n\nexport function parseSessionEntries(content: string): FileEntry[] {\n\tconst entries: FileEntry[] = [];\n\tfor (const line of content.trim().split(\"\\n\")) {\n\t\tconst entry = parseSessionEntryLine(line, \"session content\");\n\t\tif (entry !== undefined) entries.push(entry);\n\t}\n\treturn entries;\n}\n\nexport function readSessionHeader(filePath: string): SessionHeader | null {\n\ttry {\n\t\tconst fd = openSync(filePath, \"r\");\n\t\ttry {\n\t\t\t// Read the full first line rather than a fixed 512-byte window so very\n\t\t\t// long headers (e.g. internal workflow headers carrying stage metadata)\n\t\t\t// are not truncated and dropped from listing/resume filtering.\n\t\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\t\t// Use a small dedicated header buffer instead of the 1MiB transcript\n\t\t\t// buffer so prefiltering internal sessions during listing stays cheap.\n\t\t\t// The loop still reads in chunks until the first newline (or EOF) so\n\t\t\t// headers larger than one chunk are handled correctly.\n\t\t\tconst buffer = Buffer.allocUnsafe(HEADER_READ_BUFFER_SIZE);\n\t\t\tlet pending = \"\";\n\t\t\tlet foundNewline = false;\n\t\t\twhile (true) {\n\t\t\t\tconst bytesRead = readSync(fd, buffer, 0, buffer.length, null);\n\t\t\t\tif (bytesRead === 0) break;\n\t\t\t\tpending += decoder.write(buffer.subarray(0, bytesRead));\n\t\t\t\tconst newlineIndex = pending.indexOf(\"\\n\");\n\t\t\t\tif (newlineIndex !== -1) {\n\t\t\t\t\tpending = pending.slice(0, newlineIndex);\n\t\t\t\t\tfoundNewline = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Only flush the decoder when we hit EOF without a newline. Once a\n\t\t\t// newline was found, any remaining decoder bytes belong to data after\n\t\t\t// the header line; flushing them would corrupt the parsed header.\n\t\t\tif (!foundNewline) {\n\t\t\t\tpending += decoder.end();\n\t\t\t}\n\t\t\tconst firstLine = pending.split(\"\\n\")[0];\n\t\t\tif (!firstLine) return null;\n\t\t\tconst header = JSON.parse(firstLine) as SessionHeader;\n\t\t\treturn validateSessionFileEntries(upgradeStoredSessionEntries([header], filePath), filePath);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Returns true only for workflow-owned sessions with a complete classification marker. */\nexport function isInternalHeader(header: SessionHeader | null | undefined): boolean {\n\treturn isClassifiedWorkflowSession(header);\n}\n\nexport function getSessionHeaderCwd(header: SessionHeader): string | undefined {\n\tconst cwd = (header as { cwd?: unknown }).cwd;\n\treturn typeof cwd === \"string\" ? cwd : undefined;\n}\n\n/** Exported for testing */\nexport function findMostRecentSession(sessionDir: string, cwd?: string, includeInternal = false): string | null {\n\tconst resolvedSessionDir = normalizePath(sessionDir);\n\tconst matchesCwd = cwd ? createSessionCwdMatcher(resolvePath(cwd)) : undefined;\n\ttry {\n\t\tconst files = readdirSync(resolvedSessionDir)\n\t\t\t.filter((f) => f.endsWith(\".jsonl\"))\n\t\t\t.map((f) => join(resolvedSessionDir, f))\n\t\t\t.map((path) => ({ path, mtime: statSync(path).mtimeMs }))\n\t\t\t.sort((a, b) => b.mtime - a.mtime);\n\n\t\tfor (const { path } of files) {\n\t\t\ttry {\n\t\t\t\tconst header = readSessionHeader(path);\n\t\t\t\tconst headerCwd = header ? getSessionHeaderCwd(header) : undefined;\n\t\t\t\tif (\n\t\t\t\t\t!header ||\n\t\t\t\t\t(matchesCwd && (!headerCwd || !matchesCwd(resolvePath(headerCwd)))) ||\n\t\t\t\t\t(!includeInternal && isInternalHeader(header))\n\t\t\t\t)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (loadEntriesFromFile(path).length > 0) return path;\n\t\t\t} catch {\n\t\t\t\t// Unloadable sessions are not resume candidates.\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function serializeSessionEntries(entries: FileEntry[]): string {\n\treturn `${entries.map((entry) => JSON.stringify(entry)).join(\"\\n\")}\\n`;\n}\n\n/**\n * A new session file is created only once the session contains a user or assistant message.\n * Setup entries alone (model, thinking level) stay in memory, so opening and closing without\n * chatting leaves no file behind. Starting at the user message (not the first assistant reply)\n * keeps the prompt on disk if the first turn never completes.\n */\nexport function hasConversationMessage(entries: FileEntry[]): boolean {\n\treturn entries.some(\n\t\t(entry): entry is SessionEntry =>\n\t\t\tentry.type === \"message\" && (entry.message.role === \"user\" || entry.message.role === \"assistant\"),\n\t);\n}\n\nexport function ensureDirectory(dir: string): void {\n\tif (!existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true });\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-manager-storage.js","sourceRoot":"","sources":["../../src/core/session-manager-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACjG,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,aAAa,EAA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G,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AACxE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,OAAoB;IAC1D,OAAO,OAAO,CAAC,IAAI,CAClB,CAAC,KAAK,EAAyB,EAAE,CAChC,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW,CAAC,CAClG,CAAC;AACH,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,GAAW;IAC1C,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QACtB,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACrC,CAAC;AACF,CAAC","sourcesContent":["import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readSync, statSync } from \"fs\";\nimport { join } from \"path\";\nimport { StringDecoder } from \"string_decoder\";\nimport { createSessionCwdMatcher, normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport { isClassifiedWorkflowSession } from \"./session-manager-classification.ts\";\nimport type { FileEntry, SessionEntry, SessionHeader } from \"./session-manager-types.ts\";\nimport { validateSessionFileEntries } from \"./session-manager-validation.ts\";\n\nimport { StorageUnavailableError } from \"./storage/session/errors.js\";\nimport {\n\tisCurrentSessionHeader,\n\ttype StoredSessionHeader,\n\tupgradeLegacySessionEntries,\n} from \"./storage/session/legacy-format.js\";\n\nconst SESSION_READ_BUFFER_SIZE = 1024 * 1024;\n/**\n * Dedicated small read chunk for header-only reads. Session headers are small\n * (typically a few KB), so reading in 64KB chunks avoids allocating/transferring\n * the full 1MiB transcript buffer just to inspect the first line during listing\n * and resume-history prefiltering.\n */\nconst HEADER_READ_BUFFER_SIZE = 64 * 1024;\n\nfunction parseSessionEntryLine(line: string, path: string, validateHeader = true): FileEntry | undefined {\n\tif (!line.trim()) return undefined;\n\tlet entry: FileEntry;\n\ttry {\n\t\tentry = JSON.parse(line) as FileEntry;\n\t} catch (cause) {\n\t\tthrow new StorageUnavailableError({ adapter: \"jsonl\", location: path }, cause as Error);\n\t}\n\tif (validateHeader && entry?.type === \"session\") {\n\t\tvalidateSessionFileEntries([entry], path);\n\t}\n\treturn entry;\n}\n\nexport function parseStoredSessionEntries(content: string): FileEntry[] {\n\tconst entries: FileEntry[] = [];\n\tfor (const line of content.trim().split(\"\\n\")) {\n\t\tconst entry = parseSessionEntryLine(line, \"session content\", false);\n\t\tif (entry !== undefined) entries.push(entry);\n\t}\n\treturn entries;\n}\n\nexport function upgradeStoredSessionEntries(entries: FileEntry[], path: string): FileEntry[] {\n\tconst header = entries[0];\n\tif (header?.type !== \"session\" || isCurrentSessionHeader(header as StoredSessionHeader)) return entries;\n\tconst upgraded = upgradeLegacySessionEntries(\n\t\theader as StoredSessionHeader,\n\t\tentries.slice(1) as SessionEntry[],\n\t\tpath,\n\t);\n\treturn [upgraded.header, ...upgraded.entries];\n}\n\n/** Exported for testing */\nexport function loadEntriesFromFile(filePath: string): FileEntry[] {\n\tconst resolvedFilePath = normalizePath(filePath);\n\tif (!existsSync(resolvedFilePath)) return [];\n\n\tconst entries: FileEntry[] = [];\n\tlet pending = \"\";\n\tconst fd = openSync(resolvedFilePath, \"r\");\n\ttry {\n\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\tconst buffer = Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);\n\n\t\twhile (true) {\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, buffer.length, null);\n\t\t\tif (bytesRead === 0) break;\n\n\t\t\tpending += decoder.write(buffer.subarray(0, bytesRead));\n\t\t\tlet lineStart = 0;\n\t\t\tlet newlineIndex = pending.indexOf(\"\\n\", lineStart);\n\t\t\twhile (newlineIndex !== -1) {\n\t\t\t\tconst entry = parseSessionEntryLine(pending.slice(lineStart, newlineIndex), resolvedFilePath);\n\t\t\t\tif (entry !== undefined) entries.push(entry);\n\t\t\t\tlineStart = newlineIndex + 1;\n\t\t\t\tnewlineIndex = pending.indexOf(\"\\n\", lineStart);\n\t\t\t}\n\t\t\tpending = pending.slice(lineStart);\n\t\t}\n\n\t\tpending += decoder.end();\n\t\tconst finalEntry = parseSessionEntryLine(pending, resolvedFilePath);\n\t\tif (finalEntry !== undefined) entries.push(finalEntry);\n\t} finally {\n\t\tcloseSync(fd);\n\t}\n\n\tif (entries.length === 0) return entries;\n\tvalidateSessionFileEntries(entries, resolvedFilePath);\n\n\treturn entries;\n}\n\nexport function parseSessionEntries(content: string): FileEntry[] {\n\tconst entries: FileEntry[] = [];\n\tfor (const line of content.trim().split(\"\\n\")) {\n\t\tconst entry = parseSessionEntryLine(line, \"session content\");\n\t\tif (entry !== undefined) entries.push(entry);\n\t}\n\treturn entries;\n}\n\nexport function readSessionHeader(filePath: string): SessionHeader | null {\n\ttry {\n\t\tconst fd = openSync(filePath, \"r\");\n\t\ttry {\n\t\t\t// Read the full first line rather than a fixed 512-byte window so very\n\t\t\t// long headers (e.g. internal workflow headers carrying stage metadata)\n\t\t\t// are not truncated and dropped from listing/resume filtering.\n\t\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\t\t// Use a small dedicated header buffer instead of the 1MiB transcript\n\t\t\t// buffer so prefiltering internal sessions during listing stays cheap.\n\t\t\t// The loop still reads in chunks until the first newline (or EOF) so\n\t\t\t// headers larger than one chunk are handled correctly.\n\t\t\tconst buffer = Buffer.allocUnsafe(HEADER_READ_BUFFER_SIZE);\n\t\t\tlet pending = \"\";\n\t\t\tlet foundNewline = false;\n\t\t\twhile (true) {\n\t\t\t\tconst bytesRead = readSync(fd, buffer, 0, buffer.length, null);\n\t\t\t\tif (bytesRead === 0) break;\n\t\t\t\tpending += decoder.write(buffer.subarray(0, bytesRead));\n\t\t\t\tconst newlineIndex = pending.indexOf(\"\\n\");\n\t\t\t\tif (newlineIndex !== -1) {\n\t\t\t\t\tpending = pending.slice(0, newlineIndex);\n\t\t\t\t\tfoundNewline = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Only flush the decoder when we hit EOF without a newline. Once a\n\t\t\t// newline was found, any remaining decoder bytes belong to data after\n\t\t\t// the header line; flushing them would corrupt the parsed header.\n\t\t\tif (!foundNewline) {\n\t\t\t\tpending += decoder.end();\n\t\t\t}\n\t\t\tconst firstLine = pending.split(\"\\n\")[0];\n\t\t\tif (!firstLine) return null;\n\t\t\tconst header = JSON.parse(firstLine) as SessionHeader;\n\t\t\treturn validateSessionFileEntries(upgradeStoredSessionEntries([header], filePath), filePath);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Returns true only for workflow-owned sessions with a complete classification marker. */\nexport function isInternalHeader(header: SessionHeader | null | undefined): boolean {\n\treturn isClassifiedWorkflowSession(header);\n}\n\nexport function getSessionHeaderCwd(header: SessionHeader): string | undefined {\n\tconst cwd = (header as { cwd?: unknown }).cwd;\n\treturn typeof cwd === \"string\" ? cwd : undefined;\n}\n\n/** Exported for testing */\nexport function findMostRecentSession(sessionDir: string, cwd?: string, includeInternal = false): string | null {\n\tconst resolvedSessionDir = normalizePath(sessionDir);\n\tconst matchesCwd = cwd ? createSessionCwdMatcher(resolvePath(cwd)) : undefined;\n\ttry {\n\t\tconst files = readdirSync(resolvedSessionDir)\n\t\t\t.filter((f) => f.endsWith(\".jsonl\"))\n\t\t\t.map((f) => join(resolvedSessionDir, f))\n\t\t\t.map((path) => ({ path, mtime: statSync(path).mtimeMs }))\n\t\t\t.sort((a, b) => b.mtime - a.mtime);\n\n\t\tfor (const { path } of files) {\n\t\t\ttry {\n\t\t\t\tconst header = readSessionHeader(path);\n\t\t\t\tconst headerCwd = header ? getSessionHeaderCwd(header) : undefined;\n\t\t\t\tif (\n\t\t\t\t\t!header ||\n\t\t\t\t\t(matchesCwd && (!headerCwd || !matchesCwd(resolvePath(headerCwd)))) ||\n\t\t\t\t\t(!includeInternal && isInternalHeader(header))\n\t\t\t\t)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (loadEntriesFromFile(path).length > 0) return path;\n\t\t\t} catch {\n\t\t\t\t// Unloadable sessions are not resume candidates.\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function serializeSessionEntries(entries: FileEntry[]): string {\n\treturn `${entries.map((entry) => JSON.stringify(entry)).join(\"\\n\")}\\n`;\n}\n\n/**\n * A new session file is created only once the session contains a user or assistant message.\n * Setup entries alone (model, thinking level) stay in memory, so opening and closing without\n * chatting leaves no file behind. Starting at the user message (not the first assistant reply)\n * keeps the prompt on disk if the first turn never completes.\n */\nexport function hasConversationMessage(entries: FileEntry[]): boolean {\n\treturn entries.some(\n\t\t(entry): entry is SessionEntry =>\n\t\t\tentry.type === \"message\" && (entry.message.role === \"user\" || entry.message.role === \"assistant\"),\n\t);\n}\n\nexport function ensureDirectory(dir: string): void {\n\tif (!existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true });\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-storage.d.ts","sourceRoot":"","sources":["../../src/core/session-storage.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAmB,KAAK,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"session-storage.d.ts","sourceRoot":"","sources":["../../src/core/session-storage.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAmB,KAAK,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAI/E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE/D,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAC7B,QAAQ,CAAC,YAAY,CAAC,EAAE,YAAY,GAAG,gBAAgB,CAAC;IACxD,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CAChC;AAID,KAAK,oBAAoB,GAAG,OAAO,CAAC,gBAAgB,EAAE;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,CAAC,CAAC;AAG1E,eAAO,MAAM,2BAA2B,+BAA+B,CAAC;AAExE,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,YAAY,GAAG,oBAAoB,GAAG,SAAS,CAE7F;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAMnE;AAED,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG;IACrE,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,cAAc,CAAC,EAAE,oBAAoB,CAAC;CACtC,CAoBA;AAUD,wBAAgB,oBAAoB,CACnC,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,qBAA0B,GACjC,YAAY,GAAG,gBAAgB,CA2EjC;AAmBD,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,YAAY,CAAC,CA8BjH"}
|
|
@@ -8,6 +8,7 @@ import { StorageConfigError } from "./storage/errors.js";
|
|
|
8
8
|
import { StorageProvider } from "./storage/provider.js";
|
|
9
9
|
import { selectStorage } from "./storage/selection.js";
|
|
10
10
|
import { JsonlSessionStore } from "./storage/session/jsonl-session-store.js";
|
|
11
|
+
import { LegacySessionStore } from "./storage/session/legacy-session-store.js";
|
|
11
12
|
const provider = new StorageProvider();
|
|
12
13
|
const sources = new WeakMap();
|
|
13
14
|
const engineSelections = new WeakMap();
|
|
@@ -121,15 +122,30 @@ export function selectSessionStorage(cwd, options = {}) {
|
|
|
121
122
|
sources.set(selection, { source: "settings", field });
|
|
122
123
|
return selection;
|
|
123
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* The shared default database, selected directly or handed to the engine child. Sessions saved
|
|
127
|
+
* before it became the default stay readable from the agent directory's JSONL files.
|
|
128
|
+
*/
|
|
129
|
+
function isDefaultDatabase(selection, agentDir) {
|
|
130
|
+
return (selection.kind === "sqlite" &&
|
|
131
|
+
!selection.prefix &&
|
|
132
|
+
selection.path !== "" &&
|
|
133
|
+
selection.path !== ":memory:" &&
|
|
134
|
+
resolve(selection.path) === resolve(join(dirname(agentDir), "workflows", "journal.sqlite")));
|
|
135
|
+
}
|
|
124
136
|
export async function resolveSessionStore(cwd, options = {}) {
|
|
125
137
|
const selection = selectSessionStorage(cwd, options);
|
|
126
138
|
if (selection !== null && typeof selection === "object" && "load" in selection)
|
|
127
139
|
return selection;
|
|
140
|
+
const agentDir = options.agentDir ?? getAgentDir();
|
|
128
141
|
try {
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
142
|
+
const opened = await provider.openSessionStore(selection, { agentDir, domain: "sessions" });
|
|
143
|
+
const store = isDefaultDatabase(selection, agentDir)
|
|
144
|
+
? new LegacySessionStore(opened, {
|
|
145
|
+
legacyDirectory: join(agentDir, "sessions"),
|
|
146
|
+
databasePath: resolve(selection.path),
|
|
147
|
+
})
|
|
148
|
+
: opened;
|
|
133
149
|
if (selection.kind === "sqlite" && selection.path !== "" && selection.path !== ":memory:") {
|
|
134
150
|
engineSelections.set(store, {
|
|
135
151
|
kind: "sqlite",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"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E,IAAI,SAAS,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAC3F,gBAAgB,CAAC,GAAG,CAAC,KAAK,EAAE;gBAC3B,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;gBAC7B,GAAG,CAAC,SAAS,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,CAAC;aACvE,CAAC,CAAC;QACJ,CAAC;aAAM,IAAI,SAAS,CAAC,IAAI,KAAK,OAAO;YAAE,gBAAgB,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACzE,IAAI,SAAS,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,YAAY,KAAK,SAAS,EAAE,CAAC;YAC5F,uBAAuB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;QACD,OAAO,KAAK,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,KAAK,YAAY,kBAAkB,EAAE,CAAC;YACzC,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;YACtC,MAAM,IAAI,kBAAkB,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,EAAE,MAAM,EAAE,KAAK,IAAI,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACtG,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AACF,CAAC","sourcesContent":["import { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { Value } from \"typebox/value\";\nimport { ENV_SESSION_DIR, getAgentDir } from \"../config.js\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { SessionStorageSelectionSchema } from \"./settings-schema.ts\";\nimport type { Settings } from \"./settings-types.ts\";\nimport { StorageConfigError } from \"./storage/errors.js\";\nimport { StorageProvider, type StorageSelection } from \"./storage/provider.js\";\nimport { selectStorage } from \"./storage/selection.js\";\nimport { JsonlSessionStore } from \"./storage/session/jsonl-session-store.js\";\nimport type { SessionStore } from \"./storage/session/types.js\";\n\nexport interface SessionStorageOptions {\n\treadonly agentDir?: string;\n\treadonly settings?: Settings;\n\treadonly sessionStore?: SessionStore | StorageSelection;\n\treadonly noSession?: boolean;\n\treadonly sessionDir?: string;\n\treadonly sessionStorePath?: string;\n\treadonly sessionPrefix?: string;\n}\n\nconst provider = new StorageProvider();\nconst sources = new WeakMap<StorageSelection, { source: \"settings\" | \"cli\" | \"env\"; field: string }>();\ntype EngineSessionStorage = Extract<StorageSelection, { kind: \"sqlite\" }>;\nconst engineSelections = new WeakMap<SessionStore, EngineSessionStorage | null>();\nconst isolatedCliMemoryStores = new WeakSet<SessionStore>();\nexport const ENGINE_SESSION_STORAGE_FLAG = \"--internal-session-storage\";\n\nexport function getEngineSessionStorage(store: SessionStore): EngineSessionStorage | undefined {\n\treturn engineSelections.get(store) ?? undefined;\n}\n\nexport function canIsolateSessionStore(store: SessionStore): boolean {\n\treturn (\n\t\tisolatedCliMemoryStores.has(store) ||\n\t\tgetEngineSessionStorage(store) !== undefined ||\n\t\t(store instanceof JsonlSessionStore && !engineSelections.has(store))\n\t);\n}\n\nexport function takeEngineSessionStorageArg(args: readonly string[]): {\n\targs: string[];\n\tsessionStorage?: EngineSessionStorage;\n} {\n\tconst remaining: string[] = [];\n\tlet sessionStorage: EngineSessionStorage | undefined;\n\tfor (let index = 0; index < args.length; index++) {\n\t\tif (args[index] !== ENGINE_SESSION_STORAGE_FLAG) {\n\t\t\tremaining.push(args[index]!);\n\t\t\tcontinue;\n\t\t}\n\t\tlet parsed: EngineSessionStorage;\n\t\ttry {\n\t\t\tparsed = JSON.parse(args[++index]!) as EngineSessionStorage;\n\t\t} catch {\n\t\t\tthrow new StorageConfigError(\"cli\", ENGINE_SESSION_STORAGE_FLAG, \"invalid-selection\");\n\t\t}\n\t\tif (parsed?.kind !== \"sqlite\" || typeof parsed.path !== \"string\") {\n\t\t\tthrow new StorageConfigError(\"cli\", ENGINE_SESSION_STORAGE_FLAG, \"invalid-selection\");\n\t\t}\n\t\tsessionStorage = parsed;\n\t}\n\treturn { args: remaining, ...(sessionStorage === undefined ? {} : { sessionStorage }) };\n}\n\nfunction resolveStoragePath(path: string, base: string, source: \"cli\" | \"env\" | \"settings\", field: string): string {\n\ttry {\n\t\treturn resolvePath(path, base);\n\t} catch {\n\t\tthrow new StorageConfigError(source, field, \"invalid-path\");\n\t}\n}\n\nexport function selectSessionStorage(\n\tcwd: string,\n\toptions: SessionStorageOptions = {},\n): SessionStore | StorageSelection {\n\tif (options.sessionStore !== undefined) {\n\t\tconst value = options.sessionStore;\n\t\tif (value !== null && typeof value === \"object\" && \"load\" in value) {\n\t\t\tif (\n\t\t\t\t[\n\t\t\t\t\tvalue.create,\n\t\t\t\t\tvalue.append,\n\t\t\t\t\tvalue.replace,\n\t\t\t\t\tvalue.load,\n\t\t\t\t\tvalue.readHeader,\n\t\t\t\t\tvalue.delete,\n\t\t\t\t\tvalue.list,\n\t\t\t\t\tvalue.findMostRecent,\n\t\t\t\t\tvalue.close,\n\t\t\t\t].some((hook) => typeof hook !== \"function\") ||\n\t\t\t\t!value.descriptor ||\n\t\t\t\ttypeof value.descriptor.adapter !== \"string\" ||\n\t\t\t\ttypeof value.descriptor.location !== \"string\"\n\t\t\t)\n\t\t\t\tthrow new StorageConfigError(\"sdk\", \"sessionStore\", \"invalid-session-store\");\n\t\t\treturn value;\n\t\t}\n\t\treturn value;\n\t}\n\tif (options.sessionStorePath !== undefined) {\n\t\tconst selection = {\n\t\t\tkind: \"sqlite\",\n\t\t\tpath: resolveStoragePath(options.sessionStorePath, cwd, \"cli\", \"--session-store\"),\n\t\t\t...(options.sessionPrefix === undefined ? {} : { prefix: options.sessionPrefix }),\n\t\t} as const;\n\t\tsources.set(selection, { source: \"cli\", field: \"--session-store\" });\n\t\treturn selection;\n\t}\n\tif (options.noSession) return { kind: \"memory\" };\n\tconst directory = options.sessionDir !== undefined ? options.sessionDir : process.env[ENV_SESSION_DIR];\n\tif (options.sessionDir !== undefined || (directory !== undefined && directory.length > 0)) {\n\t\tconst source = options.sessionDir !== undefined ? \"cli\" : \"env\";\n\t\tconst field = source === \"cli\" ? \"--session-dir\" : ENV_SESSION_DIR;\n\t\tif (typeof directory !== \"string\") throw new StorageConfigError(source, field, \"invalid-dir\");\n\t\tconst selection = { kind: \"jsonl\", dir: resolveStoragePath(directory, cwd, source, field) } as const;\n\t\tsources.set(selection, { source, field });\n\t\treturn selection;\n\t}\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst defaultPath = join(dirname(agentDir), \"workflows\", \"journal.sqlite\");\n\tconst settings = options.settings ?? SettingsManager.create(cwd, agentDir).getSettings();\n\tif (\n\t\tsettings.sessions !== undefined &&\n\t\t(settings.sessions === null || typeof settings.sessions !== \"object\" || Array.isArray(settings.sessions))\n\t) {\n\t\tthrow new StorageConfigError(\"settings\", \"sessions\", \"selection-object-required\");\n\t}\n\tconst value = settings.sessions?.storage !== undefined ? settings.sessions.storage : settings.storage;\n\tif (value === undefined) return { kind: \"sqlite\", path: defaultPath };\n\tconst field = settings.sessions?.storage !== undefined ? \"sessions.storage\" : \"storage\";\n\tif (!Value.Check(SessionStorageSelectionSchema, value) || (field === \"storage\" && \"dir\" in value)) {\n\t\tthrow new StorageConfigError(\"settings\", field, \"invalid-selection\");\n\t}\n\tlet selection: StorageSelection;\n\tif (\"dir\" in value)\n\t\tselection = { kind: \"jsonl\", dir: resolveStoragePath(value.dir, dirname(agentDir), \"settings\", field) };\n\telse {\n\t\tselection = selectStorage(\n\t\t\tvalue,\n\t\t\t\"settings\",\n\t\t\tfield,\n\t\t\tfield === \"storage\" ? join(dirname(agentDir), \"storage.sqlite\") : defaultPath,\n\t\t);\n\t\tif (selection.kind === \"sqlite\" && !isAbsolute(selection.path)) {\n\t\t\tselection = { ...selection, path: resolveStoragePath(selection.path, dirname(agentDir), \"settings\", field) };\n\t\t}\n\t}\n\tsources.set(selection, { source: \"settings\", field });\n\treturn selection;\n}\n\nexport async function resolveSessionStore(cwd: string, options: SessionStorageOptions = {}): Promise<SessionStore> {\n\tconst selection = selectSessionStorage(cwd, options);\n\tif (selection !== null && typeof selection === \"object\" && \"load\" in selection) return selection;\n\ttry {\n\t\tconst store = await provider.openSessionStore(selection, {\n\t\t\tagentDir: options.agentDir ?? getAgentDir(),\n\t\t\tdomain: \"sessions\",\n\t\t});\n\t\tif (selection.kind === \"sqlite\" && selection.path !== \"\" && selection.path !== \":memory:\") {\n\t\t\tengineSelections.set(store, {\n\t\t\t\tkind: \"sqlite\",\n\t\t\t\tpath: resolve(selection.path),\n\t\t\t\t...(selection.prefix === undefined ? {} : { prefix: selection.prefix }),\n\t\t\t});\n\t\t} else if (selection.kind !== \"jsonl\") engineSelections.set(store, null);\n\t\tif (selection.kind === \"memory\" && options.noSession && options.sessionStore === undefined) {\n\t\t\tisolatedCliMemoryStores.add(store);\n\t\t}\n\t\treturn store;\n\t} catch (error) {\n\t\tif (error instanceof StorageConfigError) {\n\t\t\tconst origin = sources.get(selection);\n\t\t\tthrow new StorageConfigError(origin?.source ?? \"sdk\", origin?.field ?? \"sessionStore\", error.reason);\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-storage.js","sourceRoot":"","sources":["../../src/core/session-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM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AE,MAAM,IAAI,KAAK,EAAE,MAAM,EAAE,KAAK,IAAI,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACtG,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AACF,CAAC","sourcesContent":["import { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { Value } from \"typebox/value\";\nimport { ENV_SESSION_DIR, getAgentDir } from \"../config.js\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { SessionStorageSelectionSchema } from \"./settings-schema.ts\";\nimport type { Settings } from \"./settings-types.ts\";\nimport { StorageConfigError } from \"./storage/errors.js\";\nimport { StorageProvider, type StorageSelection } from \"./storage/provider.js\";\nimport { selectStorage } from \"./storage/selection.js\";\nimport { JsonlSessionStore } from \"./storage/session/jsonl-session-store.js\";\nimport { LegacySessionStore } from \"./storage/session/legacy-session-store.js\";\nimport type { SessionStore } from \"./storage/session/types.js\";\n\nexport interface SessionStorageOptions {\n\treadonly agentDir?: string;\n\treadonly settings?: Settings;\n\treadonly sessionStore?: SessionStore | StorageSelection;\n\treadonly noSession?: boolean;\n\treadonly sessionDir?: string;\n\treadonly sessionStorePath?: string;\n\treadonly sessionPrefix?: string;\n}\n\nconst provider = new StorageProvider();\nconst sources = new WeakMap<StorageSelection, { source: \"settings\" | \"cli\" | \"env\"; field: string }>();\ntype EngineSessionStorage = Extract<StorageSelection, { kind: \"sqlite\" }>;\nconst engineSelections = new WeakMap<SessionStore, EngineSessionStorage | null>();\nconst isolatedCliMemoryStores = new WeakSet<SessionStore>();\nexport const ENGINE_SESSION_STORAGE_FLAG = \"--internal-session-storage\";\n\nexport function getEngineSessionStorage(store: SessionStore): EngineSessionStorage | undefined {\n\treturn engineSelections.get(store) ?? undefined;\n}\n\nexport function canIsolateSessionStore(store: SessionStore): boolean {\n\treturn (\n\t\tisolatedCliMemoryStores.has(store) ||\n\t\tgetEngineSessionStorage(store) !== undefined ||\n\t\t(store instanceof JsonlSessionStore && !engineSelections.has(store))\n\t);\n}\n\nexport function takeEngineSessionStorageArg(args: readonly string[]): {\n\targs: string[];\n\tsessionStorage?: EngineSessionStorage;\n} {\n\tconst remaining: string[] = [];\n\tlet sessionStorage: EngineSessionStorage | undefined;\n\tfor (let index = 0; index < args.length; index++) {\n\t\tif (args[index] !== ENGINE_SESSION_STORAGE_FLAG) {\n\t\t\tremaining.push(args[index]!);\n\t\t\tcontinue;\n\t\t}\n\t\tlet parsed: EngineSessionStorage;\n\t\ttry {\n\t\t\tparsed = JSON.parse(args[++index]!) as EngineSessionStorage;\n\t\t} catch {\n\t\t\tthrow new StorageConfigError(\"cli\", ENGINE_SESSION_STORAGE_FLAG, \"invalid-selection\");\n\t\t}\n\t\tif (parsed?.kind !== \"sqlite\" || typeof parsed.path !== \"string\") {\n\t\t\tthrow new StorageConfigError(\"cli\", ENGINE_SESSION_STORAGE_FLAG, \"invalid-selection\");\n\t\t}\n\t\tsessionStorage = parsed;\n\t}\n\treturn { args: remaining, ...(sessionStorage === undefined ? {} : { sessionStorage }) };\n}\n\nfunction resolveStoragePath(path: string, base: string, source: \"cli\" | \"env\" | \"settings\", field: string): string {\n\ttry {\n\t\treturn resolvePath(path, base);\n\t} catch {\n\t\tthrow new StorageConfigError(source, field, \"invalid-path\");\n\t}\n}\n\nexport function selectSessionStorage(\n\tcwd: string,\n\toptions: SessionStorageOptions = {},\n): SessionStore | StorageSelection {\n\tif (options.sessionStore !== undefined) {\n\t\tconst value = options.sessionStore;\n\t\tif (value !== null && typeof value === \"object\" && \"load\" in value) {\n\t\t\tif (\n\t\t\t\t[\n\t\t\t\t\tvalue.create,\n\t\t\t\t\tvalue.append,\n\t\t\t\t\tvalue.replace,\n\t\t\t\t\tvalue.load,\n\t\t\t\t\tvalue.readHeader,\n\t\t\t\t\tvalue.delete,\n\t\t\t\t\tvalue.list,\n\t\t\t\t\tvalue.findMostRecent,\n\t\t\t\t\tvalue.close,\n\t\t\t\t].some((hook) => typeof hook !== \"function\") ||\n\t\t\t\t!value.descriptor ||\n\t\t\t\ttypeof value.descriptor.adapter !== \"string\" ||\n\t\t\t\ttypeof value.descriptor.location !== \"string\"\n\t\t\t)\n\t\t\t\tthrow new StorageConfigError(\"sdk\", \"sessionStore\", \"invalid-session-store\");\n\t\t\treturn value;\n\t\t}\n\t\treturn value;\n\t}\n\tif (options.sessionStorePath !== undefined) {\n\t\tconst selection = {\n\t\t\tkind: \"sqlite\",\n\t\t\tpath: resolveStoragePath(options.sessionStorePath, cwd, \"cli\", \"--session-store\"),\n\t\t\t...(options.sessionPrefix === undefined ? {} : { prefix: options.sessionPrefix }),\n\t\t} as const;\n\t\tsources.set(selection, { source: \"cli\", field: \"--session-store\" });\n\t\treturn selection;\n\t}\n\tif (options.noSession) return { kind: \"memory\" };\n\tconst directory = options.sessionDir !== undefined ? options.sessionDir : process.env[ENV_SESSION_DIR];\n\tif (options.sessionDir !== undefined || (directory !== undefined && directory.length > 0)) {\n\t\tconst source = options.sessionDir !== undefined ? \"cli\" : \"env\";\n\t\tconst field = source === \"cli\" ? \"--session-dir\" : ENV_SESSION_DIR;\n\t\tif (typeof directory !== \"string\") throw new StorageConfigError(source, field, \"invalid-dir\");\n\t\tconst selection = { kind: \"jsonl\", dir: resolveStoragePath(directory, cwd, source, field) } as const;\n\t\tsources.set(selection, { source, field });\n\t\treturn selection;\n\t}\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst defaultPath = join(dirname(agentDir), \"workflows\", \"journal.sqlite\");\n\tconst settings = options.settings ?? SettingsManager.create(cwd, agentDir).getSettings();\n\tif (\n\t\tsettings.sessions !== undefined &&\n\t\t(settings.sessions === null || typeof settings.sessions !== \"object\" || Array.isArray(settings.sessions))\n\t) {\n\t\tthrow new StorageConfigError(\"settings\", \"sessions\", \"selection-object-required\");\n\t}\n\tconst value = settings.sessions?.storage !== undefined ? settings.sessions.storage : settings.storage;\n\tif (value === undefined) return { kind: \"sqlite\", path: defaultPath };\n\tconst field = settings.sessions?.storage !== undefined ? \"sessions.storage\" : \"storage\";\n\tif (!Value.Check(SessionStorageSelectionSchema, value) || (field === \"storage\" && \"dir\" in value)) {\n\t\tthrow new StorageConfigError(\"settings\", field, \"invalid-selection\");\n\t}\n\tlet selection: StorageSelection;\n\tif (\"dir\" in value)\n\t\tselection = { kind: \"jsonl\", dir: resolveStoragePath(value.dir, dirname(agentDir), \"settings\", field) };\n\telse {\n\t\tselection = selectStorage(\n\t\t\tvalue,\n\t\t\t\"settings\",\n\t\t\tfield,\n\t\t\tfield === \"storage\" ? join(dirname(agentDir), \"storage.sqlite\") : defaultPath,\n\t\t);\n\t\tif (selection.kind === \"sqlite\" && !isAbsolute(selection.path)) {\n\t\t\tselection = { ...selection, path: resolveStoragePath(selection.path, dirname(agentDir), \"settings\", field) };\n\t\t}\n\t}\n\tsources.set(selection, { source: \"settings\", field });\n\treturn selection;\n}\n\n/**\n * The shared default database, selected directly or handed to the engine child. Sessions saved\n * before it became the default stay readable from the agent directory's JSONL files.\n */\nfunction isDefaultDatabase(\n\tselection: StorageSelection,\n\tagentDir: string,\n): selection is Extract<StorageSelection, { kind: \"sqlite\" }> {\n\treturn (\n\t\tselection.kind === \"sqlite\" &&\n\t\t!selection.prefix &&\n\t\tselection.path !== \"\" &&\n\t\tselection.path !== \":memory:\" &&\n\t\tresolve(selection.path) === resolve(join(dirname(agentDir), \"workflows\", \"journal.sqlite\"))\n\t);\n}\n\nexport async function resolveSessionStore(cwd: string, options: SessionStorageOptions = {}): Promise<SessionStore> {\n\tconst selection = selectSessionStorage(cwd, options);\n\tif (selection !== null && typeof selection === \"object\" && \"load\" in selection) return selection;\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\ttry {\n\t\tconst opened = await provider.openSessionStore(selection, { agentDir, domain: \"sessions\" });\n\t\tconst store = isDefaultDatabase(selection, agentDir)\n\t\t\t? new LegacySessionStore(opened, {\n\t\t\t\t\tlegacyDirectory: join(agentDir, \"sessions\"),\n\t\t\t\t\tdatabasePath: resolve(selection.path),\n\t\t\t\t})\n\t\t\t: opened;\n\t\tif (selection.kind === \"sqlite\" && selection.path !== \"\" && selection.path !== \":memory:\") {\n\t\t\tengineSelections.set(store, {\n\t\t\t\tkind: \"sqlite\",\n\t\t\t\tpath: resolve(selection.path),\n\t\t\t\t...(selection.prefix === undefined ? {} : { prefix: selection.prefix }),\n\t\t\t});\n\t\t} else if (selection.kind !== \"jsonl\") engineSelections.set(store, null);\n\t\tif (selection.kind === \"memory\" && options.noSession && options.sessionStore === undefined) {\n\t\t\tisolatedCliMemoryStores.add(store);\n\t\t}\n\t\treturn store;\n\t} catch (error) {\n\t\tif (error instanceof StorageConfigError) {\n\t\t\tconst origin = sources.get(selection);\n\t\t\tthrow new StorageConfigError(origin?.source ?? \"sdk\", origin?.field ?? \"sessionStore\", error.reason);\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import type { SessionEntry } from "../../session-manager-types.ts";
|
|
2
|
-
import {
|
|
2
|
+
import type { SessionListQuery, SessionRecordHeader, SessionSnapshot, SessionStore, SessionSummary, SessionWriteOptions, StorageDescriptor } from "./types.js";
|
|
3
|
+
export interface JsonlSessionFile {
|
|
4
|
+
readonly location: string;
|
|
5
|
+
readonly header: SessionRecordHeader;
|
|
6
|
+
read(): Promise<SessionSnapshot>;
|
|
7
|
+
}
|
|
3
8
|
export { SessionFormatVersionError } from "./errors.js";
|
|
4
9
|
export declare class JsonlStoragePoisonedError extends Error {
|
|
5
10
|
readonly location: string;
|
|
@@ -38,6 +43,7 @@ export declare class JsonlSessionStore implements SessionStore {
|
|
|
38
43
|
readHeader(sessionId: string): Promise<SessionRecordHeader | undefined>;
|
|
39
44
|
delete(sessionId: string): Promise<void>;
|
|
40
45
|
list(query: SessionListQuery): AsyncIterable<SessionSummary>;
|
|
46
|
+
scanFiles(): AsyncIterable<JsonlSessionFile>;
|
|
41
47
|
findMostRecent(query: {
|
|
42
48
|
readonly cwd: string;
|
|
43
49
|
readonly includeInternal?: boolean;
|