@codelia/storage 0.1.84 → 0.1.86

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/dist/index.cjs CHANGED
@@ -37,6 +37,7 @@ __export(index_exports, {
37
37
  ProjectsPolicyStore: () => ProjectsPolicyStore,
38
38
  RUN_LOG_RETENTION_MS: () => RUN_LOG_RETENTION_MS,
39
39
  RunEventStoreFactoryImpl: () => RunEventStoreFactoryImpl,
40
+ SessionGoalStore: () => SessionGoalStore,
40
41
  SessionStateStoreImpl: () => SessionStateStoreImpl,
41
42
  SessionStoreWriterImpl: () => SessionStoreWriterImpl,
42
43
  StoragePathServiceImpl: () => StoragePathServiceImpl,
@@ -879,16 +880,154 @@ var getProcessIdentity = async (pid, options = {}) => {
879
880
  };
880
881
 
881
882
  // src/projects-store.ts
883
+ var import_node_crypto5 = require("crypto");
882
884
  var import_node_fs5 = require("fs");
885
+ var import_node_os2 = __toESM(require("os"), 1);
883
886
  var import_node_path5 = __toESM(require("path"), 1);
887
+ var import_promises6 = require("timers/promises");
884
888
  var import_shared_types3 = require("@codelia/shared-types");
889
+
890
+ // src/sqlite.ts
891
+ var openSqlite = async (filename) => {
892
+ if (process.versions.bun) {
893
+ const bunSqliteSpecifier = "bun:sqlite";
894
+ const { Database } = await import(bunSqliteSpecifier);
895
+ const db2 = new Database(filename, { create: true });
896
+ return {
897
+ close: () => db2.close(),
898
+ exec: (sql) => {
899
+ db2.exec(sql);
900
+ },
901
+ run: (sql, params = []) => {
902
+ db2.query(sql).run(...params);
903
+ },
904
+ get: (sql, params = []) => {
905
+ const row = db2.query(sql).get(...params);
906
+ return row ?? void 0;
907
+ },
908
+ all: (sql, params = []) => db2.query(sql).all(...params)
909
+ };
910
+ }
911
+ const betterSqliteSpecifier = "better-sqlite3";
912
+ const betterSqliteModule = await import(betterSqliteSpecifier);
913
+ const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
914
+ const db = new BetterSqlite3(filename);
915
+ return {
916
+ close: () => db.close(),
917
+ exec: (sql) => {
918
+ db.exec(sql);
919
+ },
920
+ run: (sql, params = []) => {
921
+ db.prepare(sql).run(...params);
922
+ },
923
+ get: (sql, params = []) => {
924
+ const row = db.prepare(sql).get(...params);
925
+ return row ?? void 0;
926
+ },
927
+ all: (sql, params = []) => db.prepare(sql).all(...params)
928
+ };
929
+ };
930
+
931
+ // src/projects-store.ts
885
932
  var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
886
- var parseApprovalModeField = (fieldPath, value) => {
887
- const parsed = (0, import_shared_types3.parseApprovalMode)(value);
888
- if (!parsed) {
889
- throw new Error(`${fieldPath} is invalid`);
933
+ var within = (root, target) => {
934
+ const relative = import_node_path5.default.relative(root, target);
935
+ return !import_node_path5.default.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${import_node_path5.default.sep}`);
936
+ };
937
+ var missing = (error) => error.code === "ENOENT";
938
+ var lockFileFor = (file) => import_node_path5.default.join(import_node_path5.default.dirname(file), ".projects-policy-lock.sqlite");
939
+ var lstatIfPresent = (file) => import_node_fs5.promises.lstat(file).catch((error) => {
940
+ if (!missing(error)) throw error;
941
+ return void 0;
942
+ });
943
+ var verifyLockFile = async (file) => {
944
+ const info = await lstatIfPresent(file);
945
+ if (info && (!info.isFile() || info.uid !== process.geteuid?.() || info.size === 0 || (info.mode & 18) !== 0))
946
+ throw new Error("unsafe_projects_policy_lock");
947
+ };
948
+ var initializeUpdateLock = async (lockPath) => {
949
+ if (await lstatIfPresent(lockPath)) return;
950
+ const temporary = `${lockPath}.${(0, import_node_crypto5.randomUUID)()}.tmp`;
951
+ try {
952
+ const file = await import_node_fs5.promises.open(temporary, "wx", 384);
953
+ await file.close();
954
+ const db = await openSqlite(temporary);
955
+ try {
956
+ db.exec("PRAGMA user_version = 1");
957
+ } finally {
958
+ db.close();
959
+ }
960
+ try {
961
+ await import_node_fs5.promises.link(temporary, lockPath);
962
+ } catch (error) {
963
+ if (error.code !== "EEXIST") throw error;
964
+ }
965
+ } finally {
966
+ await import_node_fs5.promises.unlink(temporary).catch(() => void 0);
890
967
  }
891
- return parsed;
968
+ };
969
+ var openUpdateLock = async (lockPath) => {
970
+ await initializeUpdateLock(lockPath);
971
+ await verifyLockFile(lockPath);
972
+ const db = await openSqlite(lockPath);
973
+ const deadline = performance.now() + 1e3;
974
+ try {
975
+ db.exec("PRAGMA busy_timeout = 0");
976
+ for (; ; ) {
977
+ try {
978
+ db.exec("BEGIN IMMEDIATE");
979
+ return db;
980
+ } catch (error) {
981
+ if (error.code !== "SQLITE_BUSY" || performance.now() >= deadline)
982
+ throw error;
983
+ await (0, import_promises6.setTimeout)(20);
984
+ }
985
+ }
986
+ } catch (error) {
987
+ db.close();
988
+ throw error;
989
+ }
990
+ };
991
+ var verifyAncestors = async (directory2, uid) => {
992
+ let child = directory2;
993
+ while (child !== import_node_path5.default.dirname(child)) {
994
+ child = import_node_path5.default.dirname(child);
995
+ const info = await import_node_fs5.promises.stat(child);
996
+ if (!info.isDirectory() || info.uid !== 0 && info.uid !== uid || (info.mode & 18) !== 0 && (info.mode & 512) === 0)
997
+ throw new Error("unsafe_projects_policy_ancestor");
998
+ }
999
+ };
1000
+ var normalizeProjectPolicy = (value, field) => {
1001
+ if (!isRecord2(value)) throw new Error(`${field} must be an object`);
1002
+ const { approval_mode, sandbox_mode, protected_paths, trust_project_allows } = value;
1003
+ if (trust_project_allows !== void 0 && typeof trust_project_allows !== "boolean")
1004
+ throw new Error(`${field}.trust_project_allows must be boolean`);
1005
+ const approvalMode = (0, import_shared_types3.parseApprovalMode)(approval_mode);
1006
+ const sandboxMode = (0, import_shared_types3.parseSandboxMode)(sandbox_mode);
1007
+ const toolAllows = value.remembered_tool_allows;
1008
+ if (toolAllows !== void 0 && (!Array.isArray(toolAllows) || toolAllows.some(
1009
+ (rule) => !isRecord2(rule) || Object.keys(rule).length !== 1 || typeof rule.tool !== "string" || !/^[a-z][a-z0-9_]*$/.test(rule.tool)
1010
+ )))
1011
+ throw new Error(
1012
+ `${field}.remembered_tool_allows must contain tool-only rules`
1013
+ );
1014
+ if (approval_mode !== void 0 && !approvalMode)
1015
+ throw new Error(`${field}.approval_mode is invalid`);
1016
+ if (sandbox_mode !== void 0 && !sandboxMode)
1017
+ throw new Error(`${field}.sandbox_mode is invalid`);
1018
+ if (protected_paths !== void 0 && (!Array.isArray(protected_paths) || protected_paths.some(
1019
+ (entry) => typeof entry !== "string" || !import_node_path5.default.isAbsolute(entry) || [...entry].some(
1020
+ (character) => character < " " || character === "\x7F"
1021
+ )
1022
+ )))
1023
+ throw new Error(`${field}.protected_paths must contain absolute paths`);
1024
+ return {
1025
+ ...Array.isArray(toolAllows) ? { remembered_tool_allows: toolAllows.map(({ tool }) => ({ tool })) } : {},
1026
+ ...typeof trust_project_allows === "boolean" ? { trust_project_allows } : {},
1027
+ ...approvalMode ? { approval_mode: approvalMode } : {},
1028
+ ...sandboxMode ? { sandbox_mode: sandboxMode } : {},
1029
+ ...Array.isArray(protected_paths) ? { protected_paths: [...new Set(protected_paths)] } : {}
1030
+ };
892
1031
  };
893
1032
  var normalizeProjectsPolicyFile = (value) => {
894
1033
  if (!isRecord2(value)) {
@@ -898,42 +1037,24 @@ var normalizeProjectsPolicyFile = (value) => {
898
1037
  throw new Error("projects policy version must be 1");
899
1038
  }
900
1039
  const normalized = { version: 1 };
901
- const defaultValue = value.default;
902
- if (defaultValue !== void 0) {
903
- if (!isRecord2(defaultValue)) {
904
- throw new Error("projects policy default must be an object");
905
- }
906
- if (defaultValue.approval_mode !== void 0) {
907
- normalized.default = {
908
- approval_mode: parseApprovalModeField(
909
- "projects policy default.approval_mode",
910
- defaultValue.approval_mode
911
- )
912
- };
913
- }
1040
+ if (value.default !== void 0) {
1041
+ const entry = normalizeProjectPolicy(
1042
+ value.default,
1043
+ "projects policy default"
1044
+ );
1045
+ if (Object.keys(entry).length) normalized.default = entry;
914
1046
  }
915
- const projectsValue = value.projects;
916
- if (projectsValue !== void 0) {
917
- if (!isRecord2(projectsValue)) {
1047
+ if (value.projects !== void 0) {
1048
+ if (!isRecord2(value.projects))
918
1049
  throw new Error("projects policy projects must be an object");
919
- }
920
- const entries2 = {};
921
- for (const [key, projectValue] of Object.entries(projectsValue)) {
922
- if (!isRecord2(projectValue)) {
923
- throw new Error(`projects policy projects['${key}'] must be an object`);
924
- }
925
- if (projectValue.approval_mode !== void 0) {
926
- entries2[key] = {
927
- approval_mode: parseApprovalModeField(
928
- `projects policy projects['${key}'].approval_mode`,
929
- projectValue.approval_mode
930
- )
931
- };
932
- }
933
- }
934
- if (Object.keys(entries2).length > 0) {
935
- normalized.projects = entries2;
936
- }
1050
+ const entries2 = Object.entries(value.projects).flatMap(([key, value2]) => {
1051
+ const entry = normalizeProjectPolicy(
1052
+ value2,
1053
+ `projects policy projects['${key}']`
1054
+ );
1055
+ return Object.keys(entry).length ? [[key, entry]] : [];
1056
+ });
1057
+ if (entries2.length) normalized.projects = Object.fromEntries(entries2);
937
1058
  }
938
1059
  return normalized;
939
1060
  };
@@ -958,10 +1079,223 @@ var ProjectsPolicyStore = class {
958
1079
  getFilePath() {
959
1080
  return this.paths.projectsFile;
960
1081
  }
961
- async load() {
1082
+ async verifyWorkspaceLocation(workspace, configured, file, access, reservedFile = resolveStoragePaths().projectsFile) {
1083
+ if (!within(workspace, configured) && !within(workspace, file)) return;
1084
+ const home = import_node_path5.default.resolve(import_node_os2.default.homedir());
1085
+ const canonicalHome = await import_node_fs5.promises.realpath(home);
1086
+ const apparentHome = within(home, configured) ? home : canonicalHome;
1087
+ if (access === "read" && workspace === canonicalHome && configured === import_node_path5.default.resolve(reservedFile) && within(apparentHome, configured) && file === import_node_path5.default.join(canonicalHome, import_node_path5.default.relative(apparentHome, configured)))
1088
+ return;
1089
+ throw new Error("unsafe_projects_policy_path");
1090
+ }
1091
+ async trustedPath(workspace, access, configured = import_node_path5.default.resolve(this.paths.projectsFile), reservedFile = resolveStoragePaths().projectsFile) {
1092
+ const uid = process.geteuid?.();
1093
+ if (uid === void 0) throw new Error("unsafe_projects_policy_path");
1094
+ const destination = import_node_path5.default.dirname(configured);
1095
+ let ancestor = destination;
1096
+ let canonical;
1097
+ for (; ; ) {
1098
+ try {
1099
+ canonical = await import_node_fs5.promises.realpath(ancestor);
1100
+ break;
1101
+ } catch (error) {
1102
+ if (!missing(error) || ancestor === import_node_path5.default.dirname(ancestor)) throw error;
1103
+ if (await lstatIfPresent(ancestor))
1104
+ throw new Error("unsafe_projects_policy_path");
1105
+ ancestor = import_node_path5.default.dirname(ancestor);
1106
+ }
1107
+ }
1108
+ const directory2 = import_node_path5.default.join(
1109
+ canonical,
1110
+ import_node_path5.default.relative(ancestor, destination)
1111
+ );
1112
+ const file = import_node_path5.default.join(directory2, import_node_path5.default.basename(configured));
1113
+ await this.verifyWorkspaceLocation(
1114
+ workspace,
1115
+ configured,
1116
+ file,
1117
+ access,
1118
+ reservedFile
1119
+ );
1120
+ const owner = await import_node_fs5.promises.stat(canonical);
1121
+ if (!owner.isDirectory() || owner.uid !== uid || (owner.mode & 18) !== 0)
1122
+ throw new Error("unsafe_projects_policy_directory");
1123
+ await verifyAncestors(canonical, uid);
1124
+ if (ancestor !== canonical) await verifyAncestors(ancestor, uid);
1125
+ if (access !== "read")
1126
+ await import_node_fs5.promises.access(canonical, import_node_fs5.constants.W_OK | import_node_fs5.constants.X_OK);
1127
+ if (access === "create" && ancestor !== destination) {
1128
+ await import_node_fs5.promises.mkdir(directory2, { recursive: true, mode: 448 });
1129
+ if (await import_node_fs5.promises.realpath(directory2) !== directory2)
1130
+ throw new Error("unsafe_projects_policy_directory");
1131
+ return this.trustedPath(workspace, "write");
1132
+ }
1133
+ return file;
1134
+ }
1135
+ async readUserFile(file, owner) {
1136
+ const info = await lstatIfPresent(file);
1137
+ if (!info) return void 0;
1138
+ if (!info.isFile() || info.nlink !== 1)
1139
+ throw new Error("unsafe_projects_policy_file");
1140
+ const handle = await import_node_fs5.promises.open(
1141
+ file,
1142
+ import_node_fs5.constants.O_RDONLY | (import_node_fs5.constants.O_NOFOLLOW ?? 0) | (import_node_fs5.constants.O_NONBLOCK ?? 0)
1143
+ );
1144
+ try {
1145
+ const current = await handle.stat();
1146
+ if (!current.isFile() || current.dev !== info.dev || current.ino !== info.ino || current.nlink !== 1 || owner !== null && (current.uid !== owner || (current.mode & 18) !== 0))
1147
+ throw new Error("unsafe_projects_policy_file");
1148
+ return await handle.readFile("utf8");
1149
+ } finally {
1150
+ await handle.close();
1151
+ }
1152
+ }
1153
+ /** Read user-authored permission settings through the same private-file boundary as project trust. */
1154
+ async readUserConfig(workspace, configured) {
1155
+ const uid = process.geteuid?.();
1156
+ if (uid === void 0) throw new Error("unsafe_projects_policy_path");
1157
+ const file = await this.trustedPath(
1158
+ workspace,
1159
+ "read",
1160
+ import_node_path5.default.resolve(configured),
1161
+ this.paths.configFile
1162
+ );
1163
+ return this.readUserFile(file, uid);
1164
+ }
1165
+ async readPolicyFile(file, owner) {
1166
+ const text = await this.readUserFile(file, owner);
1167
+ const raw = text === void 0 ? { version: 1 } : JSON.parse(text);
1168
+ const normalized = normalizeProjectsPolicyFile(raw);
1169
+ return { raw, normalized };
1170
+ }
1171
+ readTrusted(file) {
1172
+ const owner = process.geteuid?.();
1173
+ if (owner === void 0) throw new Error("unsafe_projects_policy_path");
1174
+ return this.readPolicyFile(file, owner);
1175
+ }
1176
+ async hasUnverifiableProtectedPaths(workspace) {
1177
+ const configured = import_node_path5.default.resolve(this.paths.projectsFile);
1178
+ const canonicalParent = await import_node_fs5.promises.realpath(import_node_path5.default.dirname(configured));
1179
+ const file = import_node_path5.default.join(canonicalParent, import_node_path5.default.basename(configured));
1180
+ await this.verifyWorkspaceLocation(workspace, configured, file, "read");
1181
+ const { normalized: policy } = await this.readPolicyFile(file, null);
1182
+ return Boolean(
1183
+ policy.default?.protected_paths?.length || Object.entries(policy.projects ?? {}).some(
1184
+ ([root, entry]) => entry.protected_paths?.length && import_node_path5.default.isAbsolute(root) && import_node_path5.default.relative(workspace, root) === ""
1185
+ )
1186
+ );
1187
+ }
1188
+ async loadUserOwned(workspace, { strict = false } = {}) {
1189
+ let hasUnverifiablePaths;
1190
+ try {
1191
+ if (strict && !await lstatIfPresent(this.paths.projectsFile))
1192
+ return null;
1193
+ if (strict && process.geteuid?.() === void 0) {
1194
+ hasUnverifiablePaths = await this.hasUnverifiableProtectedPaths(workspace);
1195
+ } else {
1196
+ const file = await this.trustedPath(workspace, "read");
1197
+ return (await this.readTrusted(file)).normalized;
1198
+ }
1199
+ } catch (error) {
1200
+ if (strict)
1201
+ throw new Error("untrusted_projects_policy", { cause: error });
1202
+ return null;
1203
+ }
1204
+ if (hasUnverifiablePaths)
1205
+ throw new Error("protected_paths_owner_verification_unavailable");
1206
+ return null;
1207
+ }
1208
+ async verifyProjectModeWritable(workspace) {
1209
+ const file = await this.trustedPath(workspace, "write");
1210
+ await this.readTrusted(file);
1211
+ await verifyLockFile(lockFileFor(file));
1212
+ }
1213
+ /** Merge into a private user policy while other runtimes are excluded. */
1214
+ async writeProjectMode(workspace, mode) {
1215
+ return this.updateProject(workspace, { sandbox_mode: mode });
1216
+ }
1217
+ async writeProjectAllowTrust(workspace, trusted, verify) {
1218
+ return this.updateProject(
1219
+ workspace,
1220
+ { trust_project_allows: trusted },
1221
+ verify
1222
+ );
1223
+ }
1224
+ async updateRememberedTool(workspace, tool, allow, verify) {
1225
+ if (!/^[a-z][a-z0-9_]*$/.test(tool))
1226
+ throw new Error("invalid_remembered_tool");
1227
+ let changed = false;
1228
+ await this.updateProject(
1229
+ workspace,
1230
+ (current) => {
1231
+ const exists = current.remembered_tool_allows?.some((rule) => rule.tool === tool) ?? false;
1232
+ if (exists === allow) return void 0;
1233
+ changed = true;
1234
+ return {
1235
+ remembered_tool_allows: [
1236
+ ...(current.remembered_tool_allows ?? []).filter(
1237
+ (rule) => rule.tool !== tool
1238
+ ),
1239
+ ...allow ? [{ tool }] : []
1240
+ ]
1241
+ };
1242
+ },
1243
+ verify
1244
+ );
1245
+ return changed;
1246
+ }
1247
+ async updateProject(workspace, patch, verify) {
1248
+ const file = await this.trustedPath(workspace, "create");
1249
+ const lock = await openUpdateLock(lockFileFor(file));
1250
+ const temporary = `${file}.${(0, import_node_crypto5.randomUUID)()}.tmp`;
962
1251
  try {
963
- const raw = await import_node_fs5.promises.readFile(this.paths.projectsFile, "utf8");
964
- const parsed = JSON.parse(raw);
1252
+ const { raw: policy } = await this.readTrusted(file);
1253
+ const projects = policy.projects;
1254
+ const changes = typeof patch === "function" ? patch(projects?.[workspace] ?? {}) : patch;
1255
+ if (!changes) {
1256
+ verify?.();
1257
+ return;
1258
+ }
1259
+ const next = {
1260
+ ...policy,
1261
+ projects: {
1262
+ ...projects,
1263
+ [workspace]: { ...projects?.[workspace], ...changes }
1264
+ }
1265
+ };
1266
+ await import_node_fs5.promises.writeFile(temporary, `${JSON.stringify(next, null, 2)}
1267
+ `, {
1268
+ mode: 384,
1269
+ flag: "wx"
1270
+ });
1271
+ await import_node_fs5.promises.chmod(temporary, 384);
1272
+ if (await this.trustedPath(workspace, "write") !== file)
1273
+ throw new Error("unsafe_projects_policy_path");
1274
+ verify?.();
1275
+ await import_node_fs5.promises.rename(temporary, file);
1276
+ } finally {
1277
+ lock.close();
1278
+ await import_node_fs5.promises.unlink(temporary).catch(() => void 0);
1279
+ }
1280
+ }
1281
+ async load(canonicalPath) {
1282
+ try {
1283
+ const handle = await import_node_fs5.promises.open(
1284
+ canonicalPath ?? this.paths.projectsFile,
1285
+ canonicalPath ? import_node_fs5.constants.O_RDONLY | (import_node_fs5.constants.O_NOFOLLOW ?? 0) | (import_node_fs5.constants.O_NONBLOCK ?? 0) : "r"
1286
+ );
1287
+ let parsed;
1288
+ try {
1289
+ if (canonicalPath) {
1290
+ const info = await handle.stat();
1291
+ const uid = process.geteuid?.();
1292
+ if (!info.isFile() || info.nlink !== 1 || uid !== void 0 && (info.uid !== uid || (info.mode & 18) !== 0))
1293
+ return null;
1294
+ }
1295
+ parsed = JSON.parse(await handle.readFile("utf8"));
1296
+ } finally {
1297
+ await handle.close();
1298
+ }
965
1299
  return normalizeProjectsPolicyFile(parsed);
966
1300
  } catch (error) {
967
1301
  if (error.code === "ENOENT") {
@@ -986,7 +1320,7 @@ var import_node_fs8 = require("fs");
986
1320
  var import_node_path8 = __toESM(require("path"), 1);
987
1321
 
988
1322
  // src/run-log-paths.ts
989
- var import_node_crypto5 = require("crypto");
1323
+ var import_node_crypto6 = require("crypto");
990
1324
  var import_node_path6 = __toESM(require("path"), 1);
991
1325
  var runDatePath = (startedAt) => {
992
1326
  const date = new Date(startedAt);
@@ -1002,7 +1336,7 @@ var validateRunLogId = (id2) => {
1002
1336
  var activeRunDirectory = (paths, sessionId) => import_node_path6.default.join(
1003
1337
  paths.sessionsDir,
1004
1338
  "active-runs",
1005
- (0, import_node_crypto5.createHash)("sha256").update(sessionId).digest("hex")
1339
+ (0, import_node_crypto6.createHash)("sha256").update(sessionId).digest("hex")
1006
1340
  );
1007
1341
  var usageLogPath = (paths, datePath, runId) => import_node_path6.default.join(paths.root, "usage", datePath, `${validateRunLogId(runId)}.jsonl`);
1008
1342
 
@@ -1350,9 +1684,13 @@ var import_core2 = require("@codelia/core");
1350
1684
  // src/conversation-archive.ts
1351
1685
  var import_node_fs9 = require("fs");
1352
1686
  var import_core = require("@codelia/core");
1353
- function appendOriginalMessages(file, messages) {
1687
+ function appendOriginalMessages(file, messages, provenance) {
1354
1688
  const data = Buffer.from(
1355
- messages.map((message) => JSON.stringify(message)).join("\n") + (messages.length ? "\n" : "")
1689
+ messages.map(
1690
+ (message, index) => JSON.stringify(
1691
+ provenance?.[index] ? { ...message, approval_provenance: provenance[index] } : message
1692
+ )
1693
+ ).join("\n") + (messages.length ? "\n" : "")
1356
1694
  );
1357
1695
  const fd = (0, import_node_fs9.openSync)(
1358
1696
  file,
@@ -1394,7 +1732,7 @@ var textOf = (message) => {
1394
1732
  return message.role === "assistant" && message.tool_calls?.length ? `${text}
1395
1733
  ${JSON.stringify(message.tool_calls.map((call) => ({ id: call.id, function: call.function })))}` : text;
1396
1734
  };
1397
- async function* entries(file, start) {
1735
+ async function* entries(file, start, maxBytes) {
1398
1736
  const fd = (0, import_node_fs9.openSync)(file, import_node_fs9.constants.O_RDONLY | (import_node_fs9.constants.O_NOFOLLOW ?? 0));
1399
1737
  let stream;
1400
1738
  try {
@@ -1402,6 +1740,8 @@ async function* entries(file, start) {
1402
1740
  if (!stat.isFile()) throw new Error("Invalid conversation archive");
1403
1741
  if (start > stat.size)
1404
1742
  throw new Error("Conversation cursor is beyond the archive");
1743
+ if (maxBytes !== void 0 && stat.size - start > maxBytes)
1744
+ throw new Error("Approval conversation window is too large");
1405
1745
  if (start === stat.size) return;
1406
1746
  if (start > 0) {
1407
1747
  const previous = Buffer.alloc(1);
@@ -1441,6 +1781,8 @@ async function* entries(file, start) {
1441
1781
  position = end;
1442
1782
  }
1443
1783
  }
1784
+ if (maxBytes !== void 0 && length > 0)
1785
+ throw new Error("Incomplete approval conversation window");
1444
1786
  } finally {
1445
1787
  if (!stream) (0, import_node_fs9.closeSync)(fd);
1446
1788
  else if (!stream.closed) {
@@ -1452,6 +1794,47 @@ async function* entries(file, start) {
1452
1794
  }
1453
1795
  }
1454
1796
  }
1797
+ async function readOriginalApprovalContext(file, {
1798
+ userMessageId,
1799
+ proposalMessageId,
1800
+ workspace,
1801
+ cwd,
1802
+ workspaceIdentity,
1803
+ cwdIdentity
1804
+ }, isAppliedSteer) {
1805
+ const first = parseId(proposalMessageId ?? userMessageId);
1806
+ if (proposalMessageId && first >= parseId(userMessageId)) return null;
1807
+ const matchesScope = (scope) => scope.workspace === workspace && scope.cwd === cwd && scope.workspaceIdentity === workspaceIdentity && scope.cwdIdentity === cwdIdentity;
1808
+ let proposal;
1809
+ const userMessages = [];
1810
+ for await (const { id: id2, message } of entries(file, first, 2 * 1024 * 1024)) {
1811
+ const source = message.approval_provenance;
1812
+ if (message.role === "assistant") {
1813
+ if (!proposalMessageId || userMessages.length > 0) continue;
1814
+ const text = (0, import_core.stringifyContent)(message.content, { mode: "display" });
1815
+ if (!text.trim() && !message.refusal) continue;
1816
+ if (id2 !== proposalMessageId || message.tool_calls?.length || message.refusal || source?.source !== "assistant" || !matchesScope(source) || text.length > 1800)
1817
+ return null;
1818
+ proposal = { id: id2, role: "assistant", text, truncated: false };
1819
+ continue;
1820
+ }
1821
+ if (message.role !== "user" || source?.source === "internal_input")
1822
+ continue;
1823
+ if (source?.source !== "user_input" && source?.source !== "user_steer" || !matchesScope(source) || !source.text.trim() || source.text.includes("<shell_result>") || source.text.length > 1800)
1824
+ return null;
1825
+ if (userMessages.length === 0 && id2 !== userMessageId) return null;
1826
+ if (source.source === "user_steer" && !isAppliedSteer(source.runId, source.steerId))
1827
+ return null;
1828
+ userMessages.push({
1829
+ id: id2,
1830
+ role: "user",
1831
+ text: source.text,
1832
+ truncated: false
1833
+ });
1834
+ if (userMessages.length > 8) return null;
1835
+ }
1836
+ return userMessages.length && (!proposalMessageId || proposal) ? { userMessages, proposal } : null;
1837
+ }
1455
1838
  async function searchOriginalMessages(file, options) {
1456
1839
  const query = options.query.trim().toLowerCase();
1457
1840
  if (!query || query.length > 200)
@@ -1499,6 +1882,75 @@ async function readOriginalMessage(file, options) {
1499
1882
  return null;
1500
1883
  }
1501
1884
 
1885
+ // src/session-goals.ts
1886
+ function initSessionGoals(db) {
1887
+ db.exec(`
1888
+ CREATE TABLE IF NOT EXISTS session_goals (
1889
+ session_id TEXT PRIMARY KEY,
1890
+ payload TEXT NOT NULL
1891
+ );
1892
+ CREATE TABLE IF NOT EXISTS goal_continuations (
1893
+ continuation_id TEXT PRIMARY KEY,
1894
+ session_id TEXT NOT NULL,
1895
+ goal_id TEXT NOT NULL,
1896
+ run_id TEXT NOT NULL
1897
+ );
1898
+ CREATE INDEX IF NOT EXISTS goal_continuations_session ON goal_continuations (session_id);
1899
+ `);
1900
+ }
1901
+ var SessionGoalStore = class {
1902
+ constructor(getDb) {
1903
+ this.getDb = getDb;
1904
+ }
1905
+ getDb;
1906
+ load(db, sessionId) {
1907
+ const row = db.get(
1908
+ "SELECT payload FROM session_goals WHERE session_id = ?",
1909
+ [sessionId]
1910
+ );
1911
+ return row ? JSON.parse(row.payload) : null;
1912
+ }
1913
+ async read(sessionId, continuationId) {
1914
+ const db = await this.getDb();
1915
+ const entry = this.load(db, sessionId);
1916
+ const acceptedRunId = continuationId && entry ? db.get(
1917
+ "SELECT run_id FROM goal_continuations WHERE session_id = ? AND goal_id = ? AND continuation_id = ?",
1918
+ [sessionId, entry.goal.goal_id, continuationId]
1919
+ )?.run_id : void 0;
1920
+ return { entry, acceptedRunId };
1921
+ }
1922
+ async update(sessionId, update) {
1923
+ const db = await this.getDb();
1924
+ db.exec("BEGIN IMMEDIATE");
1925
+ try {
1926
+ const tx = {
1927
+ entry: this.load(db, sessionId),
1928
+ consume: (continuationId, goalId, runId) => db.run(
1929
+ "INSERT INTO goal_continuations (continuation_id, session_id, goal_id, run_id) VALUES (?, ?, ?, ?)",
1930
+ [continuationId, sessionId, goalId, runId]
1931
+ )
1932
+ };
1933
+ const result = update(tx);
1934
+ if (tx.entry) {
1935
+ db.run(
1936
+ "INSERT INTO session_goals (session_id, payload) VALUES (?, ?) ON CONFLICT(session_id) DO UPDATE SET payload = excluded.payload",
1937
+ [sessionId, JSON.stringify(tx.entry)]
1938
+ );
1939
+ } else {
1940
+ db.run("DELETE FROM session_goals WHERE session_id = ?", [sessionId]);
1941
+ db.run("DELETE FROM goal_continuations WHERE session_id = ?", [
1942
+ sessionId
1943
+ ]);
1944
+ }
1945
+ db.exec("COMMIT");
1946
+ return result;
1947
+ } catch (error) {
1948
+ db.exec("ROLLBACK");
1949
+ throw error;
1950
+ }
1951
+ }
1952
+ };
1953
+
1502
1954
  // src/session-state.ts
1503
1955
  var LEGACY_STATE_DIRNAME = "state";
1504
1956
  var MESSAGES_DIRNAME = "messages";
@@ -1562,6 +2014,7 @@ var deserializeMessages = (payload) => {
1562
2014
  var SessionStateStoreImpl = class {
1563
2015
  /** Root that `session_runs.rel_path` values are relative to. */
1564
2016
  sessionsDir;
2017
+ goals = new SessionGoalStore(() => this.requireDb("goals"));
1565
2018
  legacyStateDir;
1566
2019
  messagesDir;
1567
2020
  contextsDir;
@@ -1653,41 +2106,7 @@ var SessionStateStoreImpl = class {
1653
2106
  }
1654
2107
  async openDatabase() {
1655
2108
  await this.ensureDirs;
1656
- if (process.versions.bun) {
1657
- const bunSqliteSpecifier = "bun:sqlite";
1658
- const { Database } = await import(bunSqliteSpecifier);
1659
- const db2 = new Database(this.stateDbPath, { create: true });
1660
- return {
1661
- exec: (sql) => {
1662
- db2.exec(sql);
1663
- },
1664
- run: (sql, params = []) => {
1665
- db2.query(sql).run(...params);
1666
- },
1667
- get: (sql, params = []) => {
1668
- const row = db2.query(sql).get(...params);
1669
- return row ?? void 0;
1670
- },
1671
- all: (sql, params = []) => db2.query(sql).all(...params)
1672
- };
1673
- }
1674
- const betterSqliteSpecifier = "better-sqlite3";
1675
- const betterSqliteModule = await import(betterSqliteSpecifier);
1676
- const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
1677
- const db = new BetterSqlite3(this.stateDbPath);
1678
- return {
1679
- exec: (sql) => {
1680
- db.exec(sql);
1681
- },
1682
- run: (sql, params = []) => {
1683
- db.prepare(sql).run(...params);
1684
- },
1685
- get: (sql, params = []) => {
1686
- const row = db.prepare(sql).get(...params);
1687
- return row ?? void 0;
1688
- },
1689
- all: (sql, params = []) => db.prepare(sql).all(...params)
1690
- };
2109
+ return openSqlite(this.stateDbPath);
1691
2110
  }
1692
2111
  initDatabaseSchema(db) {
1693
2112
  db.exec("PRAGMA busy_timeout = 5000;");
@@ -1729,6 +2148,12 @@ var SessionStateStoreImpl = class {
1729
2148
  db.exec(`
1730
2149
  CREATE INDEX IF NOT EXISTS idx_session_state_updated_at
1731
2150
  ON session_state(updated_at DESC);
2151
+ CREATE TABLE IF NOT EXISTS session_approval_steers (
2152
+ session_id TEXT NOT NULL,
2153
+ run_id TEXT NOT NULL,
2154
+ steer_id TEXT NOT NULL,
2155
+ PRIMARY KEY (session_id, run_id, steer_id)
2156
+ );
1732
2157
  `);
1733
2158
  db.exec(`
1734
2159
  CREATE TABLE IF NOT EXISTS session_runs (
@@ -1761,6 +2186,7 @@ var SessionStateStoreImpl = class {
1761
2186
  value TEXT NOT NULL
1762
2187
  );
1763
2188
  `);
2189
+ initSessionGoals(db);
1764
2190
  db.exec("COMMIT");
1765
2191
  } catch (error) {
1766
2192
  db.exec("ROLLBACK");
@@ -1923,12 +2349,16 @@ var SessionStateStoreImpl = class {
1923
2349
  );
1924
2350
  });
1925
2351
  }
1926
- async appendMessages(sessionId, messages) {
2352
+ async appendMessages(sessionId, messages, origins) {
1927
2353
  const db = await this.requireDb("archive.append", sessionId);
1928
2354
  if (!await this.getSummary(sessionId)) await this.load(sessionId);
1929
2355
  await this.withRetentionGuard(sessionId, () => {
1930
2356
  this.ensureArchive(sessionId, db);
1931
- appendOriginalMessages(this.resolveMessagePath(sessionId), messages);
2357
+ appendOriginalMessages(
2358
+ this.resolveMessagePath(sessionId),
2359
+ messages,
2360
+ origins
2361
+ );
1932
2362
  });
1933
2363
  }
1934
2364
  async searchMessages(sessionId, options) {
@@ -1939,6 +2369,25 @@ var SessionStateStoreImpl = class {
1939
2369
  if (!await this.getSummary(sessionId)) await this.load(sessionId);
1940
2370
  return readOriginalMessage(this.resolveMessagePath(sessionId), options);
1941
2371
  }
2372
+ async readApprovalContext(sessionId, references) {
2373
+ if (!await this.getSummary(sessionId)) return null;
2374
+ const db = await this.requireDb("archive.approval", sessionId);
2375
+ return readOriginalApprovalContext(
2376
+ this.resolveMessagePath(sessionId),
2377
+ references,
2378
+ (runId, steerId) => !!db.get(
2379
+ "SELECT 1 AS applied FROM session_approval_steers WHERE session_id = ? AND run_id = ? AND steer_id = ?",
2380
+ [sessionId, runId, steerId]
2381
+ )
2382
+ );
2383
+ }
2384
+ async confirmApprovalSteer(sessionId, runId, steerId) {
2385
+ const db = await this.requireDb("archive.steer", sessionId);
2386
+ db.run(
2387
+ "INSERT OR IGNORE INTO session_approval_steers (session_id, run_id, steer_id) VALUES (?, ?, ?)",
2388
+ [sessionId, runId, steerId]
2389
+ );
2390
+ }
1942
2391
  async load(sessionId) {
1943
2392
  const db = await this.requireDb("load", sessionId);
1944
2393
  try {
@@ -2245,10 +2694,10 @@ var import_node_fs14 = require("fs");
2245
2694
  var import_node_path12 = __toESM(require("path"), 1);
2246
2695
 
2247
2696
  // src/run-log-compression.ts
2248
- var import_node_crypto6 = require("crypto");
2697
+ var import_node_crypto7 = require("crypto");
2249
2698
  var import_node_fs11 = require("fs");
2250
2699
  var import_node_stream2 = require("stream");
2251
- var import_promises6 = require("stream/promises");
2700
+ var import_promises7 = require("stream/promises");
2252
2701
  var import_node_zlib3 = require("zlib");
2253
2702
 
2254
2703
  // src/run-log-records.ts
@@ -2346,10 +2795,10 @@ async function* projectArchivedRunLog(file, usage) {
2346
2795
  // src/run-log-compression.ts
2347
2796
  async function prepareCompressedLog(file, usage) {
2348
2797
  const temporary = `${file}.${crypto.randomUUID()}.gz.tmp`;
2349
- const hash = (0, import_node_crypto6.createHash)("sha256");
2798
+ const hash = (0, import_node_crypto7.createHash)("sha256");
2350
2799
  let bytes = 0;
2351
2800
  try {
2352
- await (0, import_promises6.pipeline)(
2801
+ await (0, import_promises7.pipeline)(
2353
2802
  import_node_stream2.Readable.from(projectArchivedRunLog(file, usage)),
2354
2803
  new import_node_stream2.Transform({
2355
2804
  transform(chunk, _encoding, callback) {
@@ -2362,9 +2811,9 @@ async function prepareCompressedLog(file, usage) {
2362
2811
  (0, import_node_fs11.createWriteStream)(temporary, { flags: "wx", mode: 384 })
2363
2812
  );
2364
2813
  const expected = hash.digest("hex");
2365
- const verification = (0, import_node_crypto6.createHash)("sha256");
2814
+ const verification = (0, import_node_crypto7.createHash)("sha256");
2366
2815
  let decoded = 0;
2367
- await (0, import_promises6.pipeline)(
2816
+ await (0, import_promises7.pipeline)(
2368
2817
  (0, import_node_fs11.createReadStream)(temporary),
2369
2818
  (0, import_node_zlib3.createGunzip)(),
2370
2819
  new import_node_stream2.Transform({
@@ -3458,6 +3907,7 @@ ${snippet}`;
3458
3907
  ProjectsPolicyStore,
3459
3908
  RUN_LOG_RETENTION_MS,
3460
3909
  RunEventStoreFactoryImpl,
3910
+ SessionGoalStore,
3461
3911
  SessionStateStoreImpl,
3462
3912
  SessionStoreWriterImpl,
3463
3913
  StoragePathServiceImpl,