@codelia/storage 0.1.85 → 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 +467 -90
- package/dist/index.d.cts +46 -10
- package/dist/index.d.ts +46 -10
- package/dist/index.js +470 -90
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -880,16 +880,154 @@ var getProcessIdentity = async (pid, options = {}) => {
|
|
|
880
880
|
};
|
|
881
881
|
|
|
882
882
|
// src/projects-store.ts
|
|
883
|
+
var import_node_crypto5 = require("crypto");
|
|
883
884
|
var import_node_fs5 = require("fs");
|
|
885
|
+
var import_node_os2 = __toESM(require("os"), 1);
|
|
884
886
|
var import_node_path5 = __toESM(require("path"), 1);
|
|
887
|
+
var import_promises6 = require("timers/promises");
|
|
885
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
|
|
886
932
|
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
887
|
-
var
|
|
888
|
-
const
|
|
889
|
-
|
|
890
|
-
|
|
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);
|
|
967
|
+
}
|
|
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");
|
|
891
998
|
}
|
|
892
|
-
|
|
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
|
+
};
|
|
893
1031
|
};
|
|
894
1032
|
var normalizeProjectsPolicyFile = (value) => {
|
|
895
1033
|
if (!isRecord2(value)) {
|
|
@@ -899,42 +1037,24 @@ var normalizeProjectsPolicyFile = (value) => {
|
|
|
899
1037
|
throw new Error("projects policy version must be 1");
|
|
900
1038
|
}
|
|
901
1039
|
const normalized = { version: 1 };
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
if (
|
|
908
|
-
normalized.default = {
|
|
909
|
-
approval_mode: parseApprovalModeField(
|
|
910
|
-
"projects policy default.approval_mode",
|
|
911
|
-
defaultValue.approval_mode
|
|
912
|
-
)
|
|
913
|
-
};
|
|
914
|
-
}
|
|
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;
|
|
915
1046
|
}
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
if (!isRecord2(projectsValue)) {
|
|
1047
|
+
if (value.projects !== void 0) {
|
|
1048
|
+
if (!isRecord2(value.projects))
|
|
919
1049
|
throw new Error("projects policy projects must be an object");
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
approval_mode: parseApprovalModeField(
|
|
929
|
-
`projects policy projects['${key}'].approval_mode`,
|
|
930
|
-
projectValue.approval_mode
|
|
931
|
-
)
|
|
932
|
-
};
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
if (Object.keys(entries2).length > 0) {
|
|
936
|
-
normalized.projects = entries2;
|
|
937
|
-
}
|
|
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);
|
|
938
1058
|
}
|
|
939
1059
|
return normalized;
|
|
940
1060
|
};
|
|
@@ -959,10 +1079,223 @@ var ProjectsPolicyStore = class {
|
|
|
959
1079
|
getFilePath() {
|
|
960
1080
|
return this.paths.projectsFile;
|
|
961
1081
|
}
|
|
962
|
-
async
|
|
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`;
|
|
963
1251
|
try {
|
|
964
|
-
const raw = await
|
|
965
|
-
const
|
|
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
|
+
}
|
|
966
1299
|
return normalizeProjectsPolicyFile(parsed);
|
|
967
1300
|
} catch (error) {
|
|
968
1301
|
if (error.code === "ENOENT") {
|
|
@@ -987,7 +1320,7 @@ var import_node_fs8 = require("fs");
|
|
|
987
1320
|
var import_node_path8 = __toESM(require("path"), 1);
|
|
988
1321
|
|
|
989
1322
|
// src/run-log-paths.ts
|
|
990
|
-
var
|
|
1323
|
+
var import_node_crypto6 = require("crypto");
|
|
991
1324
|
var import_node_path6 = __toESM(require("path"), 1);
|
|
992
1325
|
var runDatePath = (startedAt) => {
|
|
993
1326
|
const date = new Date(startedAt);
|
|
@@ -1003,7 +1336,7 @@ var validateRunLogId = (id2) => {
|
|
|
1003
1336
|
var activeRunDirectory = (paths, sessionId) => import_node_path6.default.join(
|
|
1004
1337
|
paths.sessionsDir,
|
|
1005
1338
|
"active-runs",
|
|
1006
|
-
(0,
|
|
1339
|
+
(0, import_node_crypto6.createHash)("sha256").update(sessionId).digest("hex")
|
|
1007
1340
|
);
|
|
1008
1341
|
var usageLogPath = (paths, datePath, runId) => import_node_path6.default.join(paths.root, "usage", datePath, `${validateRunLogId(runId)}.jsonl`);
|
|
1009
1342
|
|
|
@@ -1351,9 +1684,13 @@ var import_core2 = require("@codelia/core");
|
|
|
1351
1684
|
// src/conversation-archive.ts
|
|
1352
1685
|
var import_node_fs9 = require("fs");
|
|
1353
1686
|
var import_core = require("@codelia/core");
|
|
1354
|
-
function appendOriginalMessages(file, messages) {
|
|
1687
|
+
function appendOriginalMessages(file, messages, provenance) {
|
|
1355
1688
|
const data = Buffer.from(
|
|
1356
|
-
messages.map(
|
|
1689
|
+
messages.map(
|
|
1690
|
+
(message, index) => JSON.stringify(
|
|
1691
|
+
provenance?.[index] ? { ...message, approval_provenance: provenance[index] } : message
|
|
1692
|
+
)
|
|
1693
|
+
).join("\n") + (messages.length ? "\n" : "")
|
|
1357
1694
|
);
|
|
1358
1695
|
const fd = (0, import_node_fs9.openSync)(
|
|
1359
1696
|
file,
|
|
@@ -1395,7 +1732,7 @@ var textOf = (message) => {
|
|
|
1395
1732
|
return message.role === "assistant" && message.tool_calls?.length ? `${text}
|
|
1396
1733
|
${JSON.stringify(message.tool_calls.map((call) => ({ id: call.id, function: call.function })))}` : text;
|
|
1397
1734
|
};
|
|
1398
|
-
async function* entries(file, start) {
|
|
1735
|
+
async function* entries(file, start, maxBytes) {
|
|
1399
1736
|
const fd = (0, import_node_fs9.openSync)(file, import_node_fs9.constants.O_RDONLY | (import_node_fs9.constants.O_NOFOLLOW ?? 0));
|
|
1400
1737
|
let stream;
|
|
1401
1738
|
try {
|
|
@@ -1403,6 +1740,8 @@ async function* entries(file, start) {
|
|
|
1403
1740
|
if (!stat.isFile()) throw new Error("Invalid conversation archive");
|
|
1404
1741
|
if (start > stat.size)
|
|
1405
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");
|
|
1406
1745
|
if (start === stat.size) return;
|
|
1407
1746
|
if (start > 0) {
|
|
1408
1747
|
const previous = Buffer.alloc(1);
|
|
@@ -1442,6 +1781,8 @@ async function* entries(file, start) {
|
|
|
1442
1781
|
position = end;
|
|
1443
1782
|
}
|
|
1444
1783
|
}
|
|
1784
|
+
if (maxBytes !== void 0 && length > 0)
|
|
1785
|
+
throw new Error("Incomplete approval conversation window");
|
|
1445
1786
|
} finally {
|
|
1446
1787
|
if (!stream) (0, import_node_fs9.closeSync)(fd);
|
|
1447
1788
|
else if (!stream.closed) {
|
|
@@ -1453,6 +1794,47 @@ async function* entries(file, start) {
|
|
|
1453
1794
|
}
|
|
1454
1795
|
}
|
|
1455
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
|
+
}
|
|
1456
1838
|
async function searchOriginalMessages(file, options) {
|
|
1457
1839
|
const query = options.query.trim().toLowerCase();
|
|
1458
1840
|
if (!query || query.length > 200)
|
|
@@ -1724,41 +2106,7 @@ var SessionStateStoreImpl = class {
|
|
|
1724
2106
|
}
|
|
1725
2107
|
async openDatabase() {
|
|
1726
2108
|
await this.ensureDirs;
|
|
1727
|
-
|
|
1728
|
-
const bunSqliteSpecifier = "bun:sqlite";
|
|
1729
|
-
const { Database } = await import(bunSqliteSpecifier);
|
|
1730
|
-
const db2 = new Database(this.stateDbPath, { create: true });
|
|
1731
|
-
return {
|
|
1732
|
-
exec: (sql) => {
|
|
1733
|
-
db2.exec(sql);
|
|
1734
|
-
},
|
|
1735
|
-
run: (sql, params = []) => {
|
|
1736
|
-
db2.query(sql).run(...params);
|
|
1737
|
-
},
|
|
1738
|
-
get: (sql, params = []) => {
|
|
1739
|
-
const row = db2.query(sql).get(...params);
|
|
1740
|
-
return row ?? void 0;
|
|
1741
|
-
},
|
|
1742
|
-
all: (sql, params = []) => db2.query(sql).all(...params)
|
|
1743
|
-
};
|
|
1744
|
-
}
|
|
1745
|
-
const betterSqliteSpecifier = "better-sqlite3";
|
|
1746
|
-
const betterSqliteModule = await import(betterSqliteSpecifier);
|
|
1747
|
-
const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
|
|
1748
|
-
const db = new BetterSqlite3(this.stateDbPath);
|
|
1749
|
-
return {
|
|
1750
|
-
exec: (sql) => {
|
|
1751
|
-
db.exec(sql);
|
|
1752
|
-
},
|
|
1753
|
-
run: (sql, params = []) => {
|
|
1754
|
-
db.prepare(sql).run(...params);
|
|
1755
|
-
},
|
|
1756
|
-
get: (sql, params = []) => {
|
|
1757
|
-
const row = db.prepare(sql).get(...params);
|
|
1758
|
-
return row ?? void 0;
|
|
1759
|
-
},
|
|
1760
|
-
all: (sql, params = []) => db.prepare(sql).all(...params)
|
|
1761
|
-
};
|
|
2109
|
+
return openSqlite(this.stateDbPath);
|
|
1762
2110
|
}
|
|
1763
2111
|
initDatabaseSchema(db) {
|
|
1764
2112
|
db.exec("PRAGMA busy_timeout = 5000;");
|
|
@@ -1800,6 +2148,12 @@ var SessionStateStoreImpl = class {
|
|
|
1800
2148
|
db.exec(`
|
|
1801
2149
|
CREATE INDEX IF NOT EXISTS idx_session_state_updated_at
|
|
1802
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
|
+
);
|
|
1803
2157
|
`);
|
|
1804
2158
|
db.exec(`
|
|
1805
2159
|
CREATE TABLE IF NOT EXISTS session_runs (
|
|
@@ -1995,12 +2349,16 @@ var SessionStateStoreImpl = class {
|
|
|
1995
2349
|
);
|
|
1996
2350
|
});
|
|
1997
2351
|
}
|
|
1998
|
-
async appendMessages(sessionId, messages) {
|
|
2352
|
+
async appendMessages(sessionId, messages, origins) {
|
|
1999
2353
|
const db = await this.requireDb("archive.append", sessionId);
|
|
2000
2354
|
if (!await this.getSummary(sessionId)) await this.load(sessionId);
|
|
2001
2355
|
await this.withRetentionGuard(sessionId, () => {
|
|
2002
2356
|
this.ensureArchive(sessionId, db);
|
|
2003
|
-
appendOriginalMessages(
|
|
2357
|
+
appendOriginalMessages(
|
|
2358
|
+
this.resolveMessagePath(sessionId),
|
|
2359
|
+
messages,
|
|
2360
|
+
origins
|
|
2361
|
+
);
|
|
2004
2362
|
});
|
|
2005
2363
|
}
|
|
2006
2364
|
async searchMessages(sessionId, options) {
|
|
@@ -2011,6 +2369,25 @@ var SessionStateStoreImpl = class {
|
|
|
2011
2369
|
if (!await this.getSummary(sessionId)) await this.load(sessionId);
|
|
2012
2370
|
return readOriginalMessage(this.resolveMessagePath(sessionId), options);
|
|
2013
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
|
+
}
|
|
2014
2391
|
async load(sessionId) {
|
|
2015
2392
|
const db = await this.requireDb("load", sessionId);
|
|
2016
2393
|
try {
|
|
@@ -2317,10 +2694,10 @@ var import_node_fs14 = require("fs");
|
|
|
2317
2694
|
var import_node_path12 = __toESM(require("path"), 1);
|
|
2318
2695
|
|
|
2319
2696
|
// src/run-log-compression.ts
|
|
2320
|
-
var
|
|
2697
|
+
var import_node_crypto7 = require("crypto");
|
|
2321
2698
|
var import_node_fs11 = require("fs");
|
|
2322
2699
|
var import_node_stream2 = require("stream");
|
|
2323
|
-
var
|
|
2700
|
+
var import_promises7 = require("stream/promises");
|
|
2324
2701
|
var import_node_zlib3 = require("zlib");
|
|
2325
2702
|
|
|
2326
2703
|
// src/run-log-records.ts
|
|
@@ -2418,10 +2795,10 @@ async function* projectArchivedRunLog(file, usage) {
|
|
|
2418
2795
|
// src/run-log-compression.ts
|
|
2419
2796
|
async function prepareCompressedLog(file, usage) {
|
|
2420
2797
|
const temporary = `${file}.${crypto.randomUUID()}.gz.tmp`;
|
|
2421
|
-
const hash = (0,
|
|
2798
|
+
const hash = (0, import_node_crypto7.createHash)("sha256");
|
|
2422
2799
|
let bytes = 0;
|
|
2423
2800
|
try {
|
|
2424
|
-
await (0,
|
|
2801
|
+
await (0, import_promises7.pipeline)(
|
|
2425
2802
|
import_node_stream2.Readable.from(projectArchivedRunLog(file, usage)),
|
|
2426
2803
|
new import_node_stream2.Transform({
|
|
2427
2804
|
transform(chunk, _encoding, callback) {
|
|
@@ -2434,9 +2811,9 @@ async function prepareCompressedLog(file, usage) {
|
|
|
2434
2811
|
(0, import_node_fs11.createWriteStream)(temporary, { flags: "wx", mode: 384 })
|
|
2435
2812
|
);
|
|
2436
2813
|
const expected = hash.digest("hex");
|
|
2437
|
-
const verification = (0,
|
|
2814
|
+
const verification = (0, import_node_crypto7.createHash)("sha256");
|
|
2438
2815
|
let decoded = 0;
|
|
2439
|
-
await (0,
|
|
2816
|
+
await (0, import_promises7.pipeline)(
|
|
2440
2817
|
(0, import_node_fs11.createReadStream)(temporary),
|
|
2441
2818
|
(0, import_node_zlib3.createGunzip)(),
|
|
2442
2819
|
new import_node_stream2.Transform({
|