@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 +540 -90
- package/dist/index.d.cts +86 -11
- package/dist/index.d.ts +86 -11
- package/dist/index.js +542 -90
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -823,16 +823,157 @@ var getProcessIdentity = async (pid, options = {}) => {
|
|
|
823
823
|
};
|
|
824
824
|
|
|
825
825
|
// src/projects-store.ts
|
|
826
|
-
import {
|
|
826
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
827
|
+
import { constants as constants3, promises as fs3 } from "fs";
|
|
828
|
+
import os2 from "os";
|
|
827
829
|
import path5 from "path";
|
|
828
|
-
import {
|
|
830
|
+
import { setTimeout as delay } from "timers/promises";
|
|
831
|
+
import {
|
|
832
|
+
parseApprovalMode,
|
|
833
|
+
parseSandboxMode
|
|
834
|
+
} from "@codelia/shared-types";
|
|
835
|
+
|
|
836
|
+
// src/sqlite.ts
|
|
837
|
+
var openSqlite = async (filename) => {
|
|
838
|
+
if (process.versions.bun) {
|
|
839
|
+
const bunSqliteSpecifier = "bun:sqlite";
|
|
840
|
+
const { Database } = await import(bunSqliteSpecifier);
|
|
841
|
+
const db2 = new Database(filename, { create: true });
|
|
842
|
+
return {
|
|
843
|
+
close: () => db2.close(),
|
|
844
|
+
exec: (sql) => {
|
|
845
|
+
db2.exec(sql);
|
|
846
|
+
},
|
|
847
|
+
run: (sql, params = []) => {
|
|
848
|
+
db2.query(sql).run(...params);
|
|
849
|
+
},
|
|
850
|
+
get: (sql, params = []) => {
|
|
851
|
+
const row = db2.query(sql).get(...params);
|
|
852
|
+
return row ?? void 0;
|
|
853
|
+
},
|
|
854
|
+
all: (sql, params = []) => db2.query(sql).all(...params)
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
const betterSqliteSpecifier = "better-sqlite3";
|
|
858
|
+
const betterSqliteModule = await import(betterSqliteSpecifier);
|
|
859
|
+
const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
|
|
860
|
+
const db = new BetterSqlite3(filename);
|
|
861
|
+
return {
|
|
862
|
+
close: () => db.close(),
|
|
863
|
+
exec: (sql) => {
|
|
864
|
+
db.exec(sql);
|
|
865
|
+
},
|
|
866
|
+
run: (sql, params = []) => {
|
|
867
|
+
db.prepare(sql).run(...params);
|
|
868
|
+
},
|
|
869
|
+
get: (sql, params = []) => {
|
|
870
|
+
const row = db.prepare(sql).get(...params);
|
|
871
|
+
return row ?? void 0;
|
|
872
|
+
},
|
|
873
|
+
all: (sql, params = []) => db.prepare(sql).all(...params)
|
|
874
|
+
};
|
|
875
|
+
};
|
|
876
|
+
|
|
877
|
+
// src/projects-store.ts
|
|
829
878
|
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
830
|
-
var
|
|
831
|
-
const
|
|
832
|
-
|
|
833
|
-
|
|
879
|
+
var within = (root, target) => {
|
|
880
|
+
const relative = path5.relative(root, target);
|
|
881
|
+
return !path5.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path5.sep}`);
|
|
882
|
+
};
|
|
883
|
+
var missing = (error) => error.code === "ENOENT";
|
|
884
|
+
var lockFileFor = (file) => path5.join(path5.dirname(file), ".projects-policy-lock.sqlite");
|
|
885
|
+
var lstatIfPresent = (file) => fs3.lstat(file).catch((error) => {
|
|
886
|
+
if (!missing(error)) throw error;
|
|
887
|
+
return void 0;
|
|
888
|
+
});
|
|
889
|
+
var verifyLockFile = async (file) => {
|
|
890
|
+
const info = await lstatIfPresent(file);
|
|
891
|
+
if (info && (!info.isFile() || info.uid !== process.geteuid?.() || info.size === 0 || (info.mode & 18) !== 0))
|
|
892
|
+
throw new Error("unsafe_projects_policy_lock");
|
|
893
|
+
};
|
|
894
|
+
var initializeUpdateLock = async (lockPath) => {
|
|
895
|
+
if (await lstatIfPresent(lockPath)) return;
|
|
896
|
+
const temporary = `${lockPath}.${randomUUID4()}.tmp`;
|
|
897
|
+
try {
|
|
898
|
+
const file = await fs3.open(temporary, "wx", 384);
|
|
899
|
+
await file.close();
|
|
900
|
+
const db = await openSqlite(temporary);
|
|
901
|
+
try {
|
|
902
|
+
db.exec("PRAGMA user_version = 1");
|
|
903
|
+
} finally {
|
|
904
|
+
db.close();
|
|
905
|
+
}
|
|
906
|
+
try {
|
|
907
|
+
await fs3.link(temporary, lockPath);
|
|
908
|
+
} catch (error) {
|
|
909
|
+
if (error.code !== "EEXIST") throw error;
|
|
910
|
+
}
|
|
911
|
+
} finally {
|
|
912
|
+
await fs3.unlink(temporary).catch(() => void 0);
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
var openUpdateLock = async (lockPath) => {
|
|
916
|
+
await initializeUpdateLock(lockPath);
|
|
917
|
+
await verifyLockFile(lockPath);
|
|
918
|
+
const db = await openSqlite(lockPath);
|
|
919
|
+
const deadline = performance.now() + 1e3;
|
|
920
|
+
try {
|
|
921
|
+
db.exec("PRAGMA busy_timeout = 0");
|
|
922
|
+
for (; ; ) {
|
|
923
|
+
try {
|
|
924
|
+
db.exec("BEGIN IMMEDIATE");
|
|
925
|
+
return db;
|
|
926
|
+
} catch (error) {
|
|
927
|
+
if (error.code !== "SQLITE_BUSY" || performance.now() >= deadline)
|
|
928
|
+
throw error;
|
|
929
|
+
await delay(20);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
} catch (error) {
|
|
933
|
+
db.close();
|
|
934
|
+
throw error;
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
var verifyAncestors = async (directory2, uid) => {
|
|
938
|
+
let child = directory2;
|
|
939
|
+
while (child !== path5.dirname(child)) {
|
|
940
|
+
child = path5.dirname(child);
|
|
941
|
+
const info = await fs3.stat(child);
|
|
942
|
+
if (!info.isDirectory() || info.uid !== 0 && info.uid !== uid || (info.mode & 18) !== 0 && (info.mode & 512) === 0)
|
|
943
|
+
throw new Error("unsafe_projects_policy_ancestor");
|
|
834
944
|
}
|
|
835
|
-
|
|
945
|
+
};
|
|
946
|
+
var normalizeProjectPolicy = (value, field) => {
|
|
947
|
+
if (!isRecord2(value)) throw new Error(`${field} must be an object`);
|
|
948
|
+
const { approval_mode, sandbox_mode, protected_paths, trust_project_allows } = value;
|
|
949
|
+
if (trust_project_allows !== void 0 && typeof trust_project_allows !== "boolean")
|
|
950
|
+
throw new Error(`${field}.trust_project_allows must be boolean`);
|
|
951
|
+
const approvalMode = parseApprovalMode(approval_mode);
|
|
952
|
+
const sandboxMode = parseSandboxMode(sandbox_mode);
|
|
953
|
+
const toolAllows = value.remembered_tool_allows;
|
|
954
|
+
if (toolAllows !== void 0 && (!Array.isArray(toolAllows) || toolAllows.some(
|
|
955
|
+
(rule) => !isRecord2(rule) || Object.keys(rule).length !== 1 || typeof rule.tool !== "string" || !/^[a-z][a-z0-9_]*$/.test(rule.tool)
|
|
956
|
+
)))
|
|
957
|
+
throw new Error(
|
|
958
|
+
`${field}.remembered_tool_allows must contain tool-only rules`
|
|
959
|
+
);
|
|
960
|
+
if (approval_mode !== void 0 && !approvalMode)
|
|
961
|
+
throw new Error(`${field}.approval_mode is invalid`);
|
|
962
|
+
if (sandbox_mode !== void 0 && !sandboxMode)
|
|
963
|
+
throw new Error(`${field}.sandbox_mode is invalid`);
|
|
964
|
+
if (protected_paths !== void 0 && (!Array.isArray(protected_paths) || protected_paths.some(
|
|
965
|
+
(entry) => typeof entry !== "string" || !path5.isAbsolute(entry) || [...entry].some(
|
|
966
|
+
(character) => character < " " || character === "\x7F"
|
|
967
|
+
)
|
|
968
|
+
)))
|
|
969
|
+
throw new Error(`${field}.protected_paths must contain absolute paths`);
|
|
970
|
+
return {
|
|
971
|
+
...Array.isArray(toolAllows) ? { remembered_tool_allows: toolAllows.map(({ tool }) => ({ tool })) } : {},
|
|
972
|
+
...typeof trust_project_allows === "boolean" ? { trust_project_allows } : {},
|
|
973
|
+
...approvalMode ? { approval_mode: approvalMode } : {},
|
|
974
|
+
...sandboxMode ? { sandbox_mode: sandboxMode } : {},
|
|
975
|
+
...Array.isArray(protected_paths) ? { protected_paths: [...new Set(protected_paths)] } : {}
|
|
976
|
+
};
|
|
836
977
|
};
|
|
837
978
|
var normalizeProjectsPolicyFile = (value) => {
|
|
838
979
|
if (!isRecord2(value)) {
|
|
@@ -842,42 +983,24 @@ var normalizeProjectsPolicyFile = (value) => {
|
|
|
842
983
|
throw new Error("projects policy version must be 1");
|
|
843
984
|
}
|
|
844
985
|
const normalized = { version: 1 };
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
if (
|
|
851
|
-
normalized.default = {
|
|
852
|
-
approval_mode: parseApprovalModeField(
|
|
853
|
-
"projects policy default.approval_mode",
|
|
854
|
-
defaultValue.approval_mode
|
|
855
|
-
)
|
|
856
|
-
};
|
|
857
|
-
}
|
|
986
|
+
if (value.default !== void 0) {
|
|
987
|
+
const entry = normalizeProjectPolicy(
|
|
988
|
+
value.default,
|
|
989
|
+
"projects policy default"
|
|
990
|
+
);
|
|
991
|
+
if (Object.keys(entry).length) normalized.default = entry;
|
|
858
992
|
}
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
if (!isRecord2(projectsValue)) {
|
|
993
|
+
if (value.projects !== void 0) {
|
|
994
|
+
if (!isRecord2(value.projects))
|
|
862
995
|
throw new Error("projects policy projects must be an object");
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
approval_mode: parseApprovalModeField(
|
|
872
|
-
`projects policy projects['${key}'].approval_mode`,
|
|
873
|
-
projectValue.approval_mode
|
|
874
|
-
)
|
|
875
|
-
};
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
if (Object.keys(entries2).length > 0) {
|
|
879
|
-
normalized.projects = entries2;
|
|
880
|
-
}
|
|
996
|
+
const entries2 = Object.entries(value.projects).flatMap(([key, value2]) => {
|
|
997
|
+
const entry = normalizeProjectPolicy(
|
|
998
|
+
value2,
|
|
999
|
+
`projects policy projects['${key}']`
|
|
1000
|
+
);
|
|
1001
|
+
return Object.keys(entry).length ? [[key, entry]] : [];
|
|
1002
|
+
});
|
|
1003
|
+
if (entries2.length) normalized.projects = Object.fromEntries(entries2);
|
|
881
1004
|
}
|
|
882
1005
|
return normalized;
|
|
883
1006
|
};
|
|
@@ -902,10 +1025,223 @@ var ProjectsPolicyStore = class {
|
|
|
902
1025
|
getFilePath() {
|
|
903
1026
|
return this.paths.projectsFile;
|
|
904
1027
|
}
|
|
905
|
-
async
|
|
1028
|
+
async verifyWorkspaceLocation(workspace, configured, file, access, reservedFile = resolveStoragePaths().projectsFile) {
|
|
1029
|
+
if (!within(workspace, configured) && !within(workspace, file)) return;
|
|
1030
|
+
const home = path5.resolve(os2.homedir());
|
|
1031
|
+
const canonicalHome = await fs3.realpath(home);
|
|
1032
|
+
const apparentHome = within(home, configured) ? home : canonicalHome;
|
|
1033
|
+
if (access === "read" && workspace === canonicalHome && configured === path5.resolve(reservedFile) && within(apparentHome, configured) && file === path5.join(canonicalHome, path5.relative(apparentHome, configured)))
|
|
1034
|
+
return;
|
|
1035
|
+
throw new Error("unsafe_projects_policy_path");
|
|
1036
|
+
}
|
|
1037
|
+
async trustedPath(workspace, access, configured = path5.resolve(this.paths.projectsFile), reservedFile = resolveStoragePaths().projectsFile) {
|
|
1038
|
+
const uid = process.geteuid?.();
|
|
1039
|
+
if (uid === void 0) throw new Error("unsafe_projects_policy_path");
|
|
1040
|
+
const destination = path5.dirname(configured);
|
|
1041
|
+
let ancestor = destination;
|
|
1042
|
+
let canonical;
|
|
1043
|
+
for (; ; ) {
|
|
1044
|
+
try {
|
|
1045
|
+
canonical = await fs3.realpath(ancestor);
|
|
1046
|
+
break;
|
|
1047
|
+
} catch (error) {
|
|
1048
|
+
if (!missing(error) || ancestor === path5.dirname(ancestor)) throw error;
|
|
1049
|
+
if (await lstatIfPresent(ancestor))
|
|
1050
|
+
throw new Error("unsafe_projects_policy_path");
|
|
1051
|
+
ancestor = path5.dirname(ancestor);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
const directory2 = path5.join(
|
|
1055
|
+
canonical,
|
|
1056
|
+
path5.relative(ancestor, destination)
|
|
1057
|
+
);
|
|
1058
|
+
const file = path5.join(directory2, path5.basename(configured));
|
|
1059
|
+
await this.verifyWorkspaceLocation(
|
|
1060
|
+
workspace,
|
|
1061
|
+
configured,
|
|
1062
|
+
file,
|
|
1063
|
+
access,
|
|
1064
|
+
reservedFile
|
|
1065
|
+
);
|
|
1066
|
+
const owner = await fs3.stat(canonical);
|
|
1067
|
+
if (!owner.isDirectory() || owner.uid !== uid || (owner.mode & 18) !== 0)
|
|
1068
|
+
throw new Error("unsafe_projects_policy_directory");
|
|
1069
|
+
await verifyAncestors(canonical, uid);
|
|
1070
|
+
if (ancestor !== canonical) await verifyAncestors(ancestor, uid);
|
|
1071
|
+
if (access !== "read")
|
|
1072
|
+
await fs3.access(canonical, constants3.W_OK | constants3.X_OK);
|
|
1073
|
+
if (access === "create" && ancestor !== destination) {
|
|
1074
|
+
await fs3.mkdir(directory2, { recursive: true, mode: 448 });
|
|
1075
|
+
if (await fs3.realpath(directory2) !== directory2)
|
|
1076
|
+
throw new Error("unsafe_projects_policy_directory");
|
|
1077
|
+
return this.trustedPath(workspace, "write");
|
|
1078
|
+
}
|
|
1079
|
+
return file;
|
|
1080
|
+
}
|
|
1081
|
+
async readUserFile(file, owner) {
|
|
1082
|
+
const info = await lstatIfPresent(file);
|
|
1083
|
+
if (!info) return void 0;
|
|
1084
|
+
if (!info.isFile() || info.nlink !== 1)
|
|
1085
|
+
throw new Error("unsafe_projects_policy_file");
|
|
1086
|
+
const handle = await fs3.open(
|
|
1087
|
+
file,
|
|
1088
|
+
constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0) | (constants3.O_NONBLOCK ?? 0)
|
|
1089
|
+
);
|
|
1090
|
+
try {
|
|
1091
|
+
const current = await handle.stat();
|
|
1092
|
+
if (!current.isFile() || current.dev !== info.dev || current.ino !== info.ino || current.nlink !== 1 || owner !== null && (current.uid !== owner || (current.mode & 18) !== 0))
|
|
1093
|
+
throw new Error("unsafe_projects_policy_file");
|
|
1094
|
+
return await handle.readFile("utf8");
|
|
1095
|
+
} finally {
|
|
1096
|
+
await handle.close();
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
/** Read user-authored permission settings through the same private-file boundary as project trust. */
|
|
1100
|
+
async readUserConfig(workspace, configured) {
|
|
1101
|
+
const uid = process.geteuid?.();
|
|
1102
|
+
if (uid === void 0) throw new Error("unsafe_projects_policy_path");
|
|
1103
|
+
const file = await this.trustedPath(
|
|
1104
|
+
workspace,
|
|
1105
|
+
"read",
|
|
1106
|
+
path5.resolve(configured),
|
|
1107
|
+
this.paths.configFile
|
|
1108
|
+
);
|
|
1109
|
+
return this.readUserFile(file, uid);
|
|
1110
|
+
}
|
|
1111
|
+
async readPolicyFile(file, owner) {
|
|
1112
|
+
const text = await this.readUserFile(file, owner);
|
|
1113
|
+
const raw = text === void 0 ? { version: 1 } : JSON.parse(text);
|
|
1114
|
+
const normalized = normalizeProjectsPolicyFile(raw);
|
|
1115
|
+
return { raw, normalized };
|
|
1116
|
+
}
|
|
1117
|
+
readTrusted(file) {
|
|
1118
|
+
const owner = process.geteuid?.();
|
|
1119
|
+
if (owner === void 0) throw new Error("unsafe_projects_policy_path");
|
|
1120
|
+
return this.readPolicyFile(file, owner);
|
|
1121
|
+
}
|
|
1122
|
+
async hasUnverifiableProtectedPaths(workspace) {
|
|
1123
|
+
const configured = path5.resolve(this.paths.projectsFile);
|
|
1124
|
+
const canonicalParent = await fs3.realpath(path5.dirname(configured));
|
|
1125
|
+
const file = path5.join(canonicalParent, path5.basename(configured));
|
|
1126
|
+
await this.verifyWorkspaceLocation(workspace, configured, file, "read");
|
|
1127
|
+
const { normalized: policy } = await this.readPolicyFile(file, null);
|
|
1128
|
+
return Boolean(
|
|
1129
|
+
policy.default?.protected_paths?.length || Object.entries(policy.projects ?? {}).some(
|
|
1130
|
+
([root, entry]) => entry.protected_paths?.length && path5.isAbsolute(root) && path5.relative(workspace, root) === ""
|
|
1131
|
+
)
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
async loadUserOwned(workspace, { strict = false } = {}) {
|
|
1135
|
+
let hasUnverifiablePaths;
|
|
1136
|
+
try {
|
|
1137
|
+
if (strict && !await lstatIfPresent(this.paths.projectsFile))
|
|
1138
|
+
return null;
|
|
1139
|
+
if (strict && process.geteuid?.() === void 0) {
|
|
1140
|
+
hasUnverifiablePaths = await this.hasUnverifiableProtectedPaths(workspace);
|
|
1141
|
+
} else {
|
|
1142
|
+
const file = await this.trustedPath(workspace, "read");
|
|
1143
|
+
return (await this.readTrusted(file)).normalized;
|
|
1144
|
+
}
|
|
1145
|
+
} catch (error) {
|
|
1146
|
+
if (strict)
|
|
1147
|
+
throw new Error("untrusted_projects_policy", { cause: error });
|
|
1148
|
+
return null;
|
|
1149
|
+
}
|
|
1150
|
+
if (hasUnverifiablePaths)
|
|
1151
|
+
throw new Error("protected_paths_owner_verification_unavailable");
|
|
1152
|
+
return null;
|
|
1153
|
+
}
|
|
1154
|
+
async verifyProjectModeWritable(workspace) {
|
|
1155
|
+
const file = await this.trustedPath(workspace, "write");
|
|
1156
|
+
await this.readTrusted(file);
|
|
1157
|
+
await verifyLockFile(lockFileFor(file));
|
|
1158
|
+
}
|
|
1159
|
+
/** Merge into a private user policy while other runtimes are excluded. */
|
|
1160
|
+
async writeProjectMode(workspace, mode) {
|
|
1161
|
+
return this.updateProject(workspace, { sandbox_mode: mode });
|
|
1162
|
+
}
|
|
1163
|
+
async writeProjectAllowTrust(workspace, trusted, verify) {
|
|
1164
|
+
return this.updateProject(
|
|
1165
|
+
workspace,
|
|
1166
|
+
{ trust_project_allows: trusted },
|
|
1167
|
+
verify
|
|
1168
|
+
);
|
|
1169
|
+
}
|
|
1170
|
+
async updateRememberedTool(workspace, tool, allow, verify) {
|
|
1171
|
+
if (!/^[a-z][a-z0-9_]*$/.test(tool))
|
|
1172
|
+
throw new Error("invalid_remembered_tool");
|
|
1173
|
+
let changed = false;
|
|
1174
|
+
await this.updateProject(
|
|
1175
|
+
workspace,
|
|
1176
|
+
(current) => {
|
|
1177
|
+
const exists = current.remembered_tool_allows?.some((rule) => rule.tool === tool) ?? false;
|
|
1178
|
+
if (exists === allow) return void 0;
|
|
1179
|
+
changed = true;
|
|
1180
|
+
return {
|
|
1181
|
+
remembered_tool_allows: [
|
|
1182
|
+
...(current.remembered_tool_allows ?? []).filter(
|
|
1183
|
+
(rule) => rule.tool !== tool
|
|
1184
|
+
),
|
|
1185
|
+
...allow ? [{ tool }] : []
|
|
1186
|
+
]
|
|
1187
|
+
};
|
|
1188
|
+
},
|
|
1189
|
+
verify
|
|
1190
|
+
);
|
|
1191
|
+
return changed;
|
|
1192
|
+
}
|
|
1193
|
+
async updateProject(workspace, patch, verify) {
|
|
1194
|
+
const file = await this.trustedPath(workspace, "create");
|
|
1195
|
+
const lock = await openUpdateLock(lockFileFor(file));
|
|
1196
|
+
const temporary = `${file}.${randomUUID4()}.tmp`;
|
|
1197
|
+
try {
|
|
1198
|
+
const { raw: policy } = await this.readTrusted(file);
|
|
1199
|
+
const projects = policy.projects;
|
|
1200
|
+
const changes = typeof patch === "function" ? patch(projects?.[workspace] ?? {}) : patch;
|
|
1201
|
+
if (!changes) {
|
|
1202
|
+
verify?.();
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
const next = {
|
|
1206
|
+
...policy,
|
|
1207
|
+
projects: {
|
|
1208
|
+
...projects,
|
|
1209
|
+
[workspace]: { ...projects?.[workspace], ...changes }
|
|
1210
|
+
}
|
|
1211
|
+
};
|
|
1212
|
+
await fs3.writeFile(temporary, `${JSON.stringify(next, null, 2)}
|
|
1213
|
+
`, {
|
|
1214
|
+
mode: 384,
|
|
1215
|
+
flag: "wx"
|
|
1216
|
+
});
|
|
1217
|
+
await fs3.chmod(temporary, 384);
|
|
1218
|
+
if (await this.trustedPath(workspace, "write") !== file)
|
|
1219
|
+
throw new Error("unsafe_projects_policy_path");
|
|
1220
|
+
verify?.();
|
|
1221
|
+
await fs3.rename(temporary, file);
|
|
1222
|
+
} finally {
|
|
1223
|
+
lock.close();
|
|
1224
|
+
await fs3.unlink(temporary).catch(() => void 0);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
async load(canonicalPath) {
|
|
906
1228
|
try {
|
|
907
|
-
const
|
|
908
|
-
|
|
1229
|
+
const handle = await fs3.open(
|
|
1230
|
+
canonicalPath ?? this.paths.projectsFile,
|
|
1231
|
+
canonicalPath ? constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0) | (constants3.O_NONBLOCK ?? 0) : "r"
|
|
1232
|
+
);
|
|
1233
|
+
let parsed;
|
|
1234
|
+
try {
|
|
1235
|
+
if (canonicalPath) {
|
|
1236
|
+
const info = await handle.stat();
|
|
1237
|
+
const uid = process.geteuid?.();
|
|
1238
|
+
if (!info.isFile() || info.nlink !== 1 || uid !== void 0 && (info.uid !== uid || (info.mode & 18) !== 0))
|
|
1239
|
+
return null;
|
|
1240
|
+
}
|
|
1241
|
+
parsed = JSON.parse(await handle.readFile("utf8"));
|
|
1242
|
+
} finally {
|
|
1243
|
+
await handle.close();
|
|
1244
|
+
}
|
|
909
1245
|
return normalizeProjectsPolicyFile(parsed);
|
|
910
1246
|
} catch (error) {
|
|
911
1247
|
if (error.code === "ENOENT") {
|
|
@@ -955,7 +1291,7 @@ import { promises as fs5, lstatSync } from "fs";
|
|
|
955
1291
|
import path7 from "path";
|
|
956
1292
|
|
|
957
1293
|
// src/run-log-reader.ts
|
|
958
|
-
import { constants as
|
|
1294
|
+
import { constants as constants4, existsSync, promises as fs4 } from "fs";
|
|
959
1295
|
import { createInterface } from "readline";
|
|
960
1296
|
import { Readable } from "stream";
|
|
961
1297
|
import { createGunzip } from "zlib";
|
|
@@ -966,7 +1302,7 @@ async function* readRunLogChunks(file) {
|
|
|
966
1302
|
try {
|
|
967
1303
|
handle = await fs4.open(
|
|
968
1304
|
resolved,
|
|
969
|
-
|
|
1305
|
+
constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0)
|
|
970
1306
|
);
|
|
971
1307
|
} catch (error) {
|
|
972
1308
|
if (error.code !== "ENOENT" || file.endsWith(".gz"))
|
|
@@ -974,7 +1310,7 @@ async function* readRunLogChunks(file) {
|
|
|
974
1310
|
resolved = `${file}.gz`;
|
|
975
1311
|
handle = await fs4.open(
|
|
976
1312
|
resolved,
|
|
977
|
-
|
|
1313
|
+
constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0)
|
|
978
1314
|
);
|
|
979
1315
|
}
|
|
980
1316
|
const source = handle.createReadStream();
|
|
@@ -1305,7 +1641,7 @@ import { stringifyContent as stringifyContent2 } from "@codelia/core";
|
|
|
1305
1641
|
// src/conversation-archive.ts
|
|
1306
1642
|
import {
|
|
1307
1643
|
closeSync,
|
|
1308
|
-
constants as
|
|
1644
|
+
constants as constants5,
|
|
1309
1645
|
createReadStream,
|
|
1310
1646
|
fstatSync,
|
|
1311
1647
|
fsyncSync,
|
|
@@ -1314,13 +1650,17 @@ import {
|
|
|
1314
1650
|
writeSync
|
|
1315
1651
|
} from "fs";
|
|
1316
1652
|
import { stringifyContent } from "@codelia/core";
|
|
1317
|
-
function appendOriginalMessages(file, messages) {
|
|
1653
|
+
function appendOriginalMessages(file, messages, provenance) {
|
|
1318
1654
|
const data = Buffer.from(
|
|
1319
|
-
messages.map(
|
|
1655
|
+
messages.map(
|
|
1656
|
+
(message, index) => JSON.stringify(
|
|
1657
|
+
provenance?.[index] ? { ...message, approval_provenance: provenance[index] } : message
|
|
1658
|
+
)
|
|
1659
|
+
).join("\n") + (messages.length ? "\n" : "")
|
|
1320
1660
|
);
|
|
1321
1661
|
const fd = openSync(
|
|
1322
1662
|
file,
|
|
1323
|
-
|
|
1663
|
+
constants5.O_RDWR | constants5.O_CREAT | constants5.O_APPEND | (constants5.O_NOFOLLOW ?? 0),
|
|
1324
1664
|
384
|
|
1325
1665
|
);
|
|
1326
1666
|
try {
|
|
@@ -1358,14 +1698,16 @@ var textOf = (message) => {
|
|
|
1358
1698
|
return message.role === "assistant" && message.tool_calls?.length ? `${text}
|
|
1359
1699
|
${JSON.stringify(message.tool_calls.map((call) => ({ id: call.id, function: call.function })))}` : text;
|
|
1360
1700
|
};
|
|
1361
|
-
async function* entries(file, start) {
|
|
1362
|
-
const fd = openSync(file,
|
|
1701
|
+
async function* entries(file, start, maxBytes) {
|
|
1702
|
+
const fd = openSync(file, constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0));
|
|
1363
1703
|
let stream;
|
|
1364
1704
|
try {
|
|
1365
1705
|
const stat = fstatSync(fd);
|
|
1366
1706
|
if (!stat.isFile()) throw new Error("Invalid conversation archive");
|
|
1367
1707
|
if (start > stat.size)
|
|
1368
1708
|
throw new Error("Conversation cursor is beyond the archive");
|
|
1709
|
+
if (maxBytes !== void 0 && stat.size - start > maxBytes)
|
|
1710
|
+
throw new Error("Approval conversation window is too large");
|
|
1369
1711
|
if (start === stat.size) return;
|
|
1370
1712
|
if (start > 0) {
|
|
1371
1713
|
const previous = Buffer.alloc(1);
|
|
@@ -1405,6 +1747,8 @@ async function* entries(file, start) {
|
|
|
1405
1747
|
position = end;
|
|
1406
1748
|
}
|
|
1407
1749
|
}
|
|
1750
|
+
if (maxBytes !== void 0 && length > 0)
|
|
1751
|
+
throw new Error("Incomplete approval conversation window");
|
|
1408
1752
|
} finally {
|
|
1409
1753
|
if (!stream) closeSync(fd);
|
|
1410
1754
|
else if (!stream.closed) {
|
|
@@ -1416,6 +1760,47 @@ async function* entries(file, start) {
|
|
|
1416
1760
|
}
|
|
1417
1761
|
}
|
|
1418
1762
|
}
|
|
1763
|
+
async function readOriginalApprovalContext(file, {
|
|
1764
|
+
userMessageId,
|
|
1765
|
+
proposalMessageId,
|
|
1766
|
+
workspace,
|
|
1767
|
+
cwd,
|
|
1768
|
+
workspaceIdentity,
|
|
1769
|
+
cwdIdentity
|
|
1770
|
+
}, isAppliedSteer) {
|
|
1771
|
+
const first = parseId(proposalMessageId ?? userMessageId);
|
|
1772
|
+
if (proposalMessageId && first >= parseId(userMessageId)) return null;
|
|
1773
|
+
const matchesScope = (scope) => scope.workspace === workspace && scope.cwd === cwd && scope.workspaceIdentity === workspaceIdentity && scope.cwdIdentity === cwdIdentity;
|
|
1774
|
+
let proposal;
|
|
1775
|
+
const userMessages = [];
|
|
1776
|
+
for await (const { id: id2, message } of entries(file, first, 2 * 1024 * 1024)) {
|
|
1777
|
+
const source = message.approval_provenance;
|
|
1778
|
+
if (message.role === "assistant") {
|
|
1779
|
+
if (!proposalMessageId || userMessages.length > 0) continue;
|
|
1780
|
+
const text = stringifyContent(message.content, { mode: "display" });
|
|
1781
|
+
if (!text.trim() && !message.refusal) continue;
|
|
1782
|
+
if (id2 !== proposalMessageId || message.tool_calls?.length || message.refusal || source?.source !== "assistant" || !matchesScope(source) || text.length > 1800)
|
|
1783
|
+
return null;
|
|
1784
|
+
proposal = { id: id2, role: "assistant", text, truncated: false };
|
|
1785
|
+
continue;
|
|
1786
|
+
}
|
|
1787
|
+
if (message.role !== "user" || source?.source === "internal_input")
|
|
1788
|
+
continue;
|
|
1789
|
+
if (source?.source !== "user_input" && source?.source !== "user_steer" || !matchesScope(source) || !source.text.trim() || source.text.includes("<shell_result>") || source.text.length > 1800)
|
|
1790
|
+
return null;
|
|
1791
|
+
if (userMessages.length === 0 && id2 !== userMessageId) return null;
|
|
1792
|
+
if (source.source === "user_steer" && !isAppliedSteer(source.runId, source.steerId))
|
|
1793
|
+
return null;
|
|
1794
|
+
userMessages.push({
|
|
1795
|
+
id: id2,
|
|
1796
|
+
role: "user",
|
|
1797
|
+
text: source.text,
|
|
1798
|
+
truncated: false
|
|
1799
|
+
});
|
|
1800
|
+
if (userMessages.length > 8) return null;
|
|
1801
|
+
}
|
|
1802
|
+
return userMessages.length && (!proposalMessageId || proposal) ? { userMessages, proposal } : null;
|
|
1803
|
+
}
|
|
1419
1804
|
async function searchOriginalMessages(file, options) {
|
|
1420
1805
|
const query = options.query.trim().toLowerCase();
|
|
1421
1806
|
if (!query || query.length > 200)
|
|
@@ -1463,6 +1848,75 @@ async function readOriginalMessage(file, options) {
|
|
|
1463
1848
|
return null;
|
|
1464
1849
|
}
|
|
1465
1850
|
|
|
1851
|
+
// src/session-goals.ts
|
|
1852
|
+
function initSessionGoals(db) {
|
|
1853
|
+
db.exec(`
|
|
1854
|
+
CREATE TABLE IF NOT EXISTS session_goals (
|
|
1855
|
+
session_id TEXT PRIMARY KEY,
|
|
1856
|
+
payload TEXT NOT NULL
|
|
1857
|
+
);
|
|
1858
|
+
CREATE TABLE IF NOT EXISTS goal_continuations (
|
|
1859
|
+
continuation_id TEXT PRIMARY KEY,
|
|
1860
|
+
session_id TEXT NOT NULL,
|
|
1861
|
+
goal_id TEXT NOT NULL,
|
|
1862
|
+
run_id TEXT NOT NULL
|
|
1863
|
+
);
|
|
1864
|
+
CREATE INDEX IF NOT EXISTS goal_continuations_session ON goal_continuations (session_id);
|
|
1865
|
+
`);
|
|
1866
|
+
}
|
|
1867
|
+
var SessionGoalStore = class {
|
|
1868
|
+
constructor(getDb) {
|
|
1869
|
+
this.getDb = getDb;
|
|
1870
|
+
}
|
|
1871
|
+
getDb;
|
|
1872
|
+
load(db, sessionId) {
|
|
1873
|
+
const row = db.get(
|
|
1874
|
+
"SELECT payload FROM session_goals WHERE session_id = ?",
|
|
1875
|
+
[sessionId]
|
|
1876
|
+
);
|
|
1877
|
+
return row ? JSON.parse(row.payload) : null;
|
|
1878
|
+
}
|
|
1879
|
+
async read(sessionId, continuationId) {
|
|
1880
|
+
const db = await this.getDb();
|
|
1881
|
+
const entry = this.load(db, sessionId);
|
|
1882
|
+
const acceptedRunId = continuationId && entry ? db.get(
|
|
1883
|
+
"SELECT run_id FROM goal_continuations WHERE session_id = ? AND goal_id = ? AND continuation_id = ?",
|
|
1884
|
+
[sessionId, entry.goal.goal_id, continuationId]
|
|
1885
|
+
)?.run_id : void 0;
|
|
1886
|
+
return { entry, acceptedRunId };
|
|
1887
|
+
}
|
|
1888
|
+
async update(sessionId, update) {
|
|
1889
|
+
const db = await this.getDb();
|
|
1890
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1891
|
+
try {
|
|
1892
|
+
const tx = {
|
|
1893
|
+
entry: this.load(db, sessionId),
|
|
1894
|
+
consume: (continuationId, goalId, runId) => db.run(
|
|
1895
|
+
"INSERT INTO goal_continuations (continuation_id, session_id, goal_id, run_id) VALUES (?, ?, ?, ?)",
|
|
1896
|
+
[continuationId, sessionId, goalId, runId]
|
|
1897
|
+
)
|
|
1898
|
+
};
|
|
1899
|
+
const result = update(tx);
|
|
1900
|
+
if (tx.entry) {
|
|
1901
|
+
db.run(
|
|
1902
|
+
"INSERT INTO session_goals (session_id, payload) VALUES (?, ?) ON CONFLICT(session_id) DO UPDATE SET payload = excluded.payload",
|
|
1903
|
+
[sessionId, JSON.stringify(tx.entry)]
|
|
1904
|
+
);
|
|
1905
|
+
} else {
|
|
1906
|
+
db.run("DELETE FROM session_goals WHERE session_id = ?", [sessionId]);
|
|
1907
|
+
db.run("DELETE FROM goal_continuations WHERE session_id = ?", [
|
|
1908
|
+
sessionId
|
|
1909
|
+
]);
|
|
1910
|
+
}
|
|
1911
|
+
db.exec("COMMIT");
|
|
1912
|
+
return result;
|
|
1913
|
+
} catch (error) {
|
|
1914
|
+
db.exec("ROLLBACK");
|
|
1915
|
+
throw error;
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
};
|
|
1919
|
+
|
|
1466
1920
|
// src/session-state.ts
|
|
1467
1921
|
var LEGACY_STATE_DIRNAME = "state";
|
|
1468
1922
|
var MESSAGES_DIRNAME = "messages";
|
|
@@ -1526,6 +1980,7 @@ var deserializeMessages = (payload) => {
|
|
|
1526
1980
|
var SessionStateStoreImpl = class {
|
|
1527
1981
|
/** Root that `session_runs.rel_path` values are relative to. */
|
|
1528
1982
|
sessionsDir;
|
|
1983
|
+
goals = new SessionGoalStore(() => this.requireDb("goals"));
|
|
1529
1984
|
legacyStateDir;
|
|
1530
1985
|
messagesDir;
|
|
1531
1986
|
contextsDir;
|
|
@@ -1617,41 +2072,7 @@ var SessionStateStoreImpl = class {
|
|
|
1617
2072
|
}
|
|
1618
2073
|
async openDatabase() {
|
|
1619
2074
|
await this.ensureDirs;
|
|
1620
|
-
|
|
1621
|
-
const bunSqliteSpecifier = "bun:sqlite";
|
|
1622
|
-
const { Database } = await import(bunSqliteSpecifier);
|
|
1623
|
-
const db2 = new Database(this.stateDbPath, { create: true });
|
|
1624
|
-
return {
|
|
1625
|
-
exec: (sql) => {
|
|
1626
|
-
db2.exec(sql);
|
|
1627
|
-
},
|
|
1628
|
-
run: (sql, params = []) => {
|
|
1629
|
-
db2.query(sql).run(...params);
|
|
1630
|
-
},
|
|
1631
|
-
get: (sql, params = []) => {
|
|
1632
|
-
const row = db2.query(sql).get(...params);
|
|
1633
|
-
return row ?? void 0;
|
|
1634
|
-
},
|
|
1635
|
-
all: (sql, params = []) => db2.query(sql).all(...params)
|
|
1636
|
-
};
|
|
1637
|
-
}
|
|
1638
|
-
const betterSqliteSpecifier = "better-sqlite3";
|
|
1639
|
-
const betterSqliteModule = await import(betterSqliteSpecifier);
|
|
1640
|
-
const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
|
|
1641
|
-
const db = new BetterSqlite3(this.stateDbPath);
|
|
1642
|
-
return {
|
|
1643
|
-
exec: (sql) => {
|
|
1644
|
-
db.exec(sql);
|
|
1645
|
-
},
|
|
1646
|
-
run: (sql, params = []) => {
|
|
1647
|
-
db.prepare(sql).run(...params);
|
|
1648
|
-
},
|
|
1649
|
-
get: (sql, params = []) => {
|
|
1650
|
-
const row = db.prepare(sql).get(...params);
|
|
1651
|
-
return row ?? void 0;
|
|
1652
|
-
},
|
|
1653
|
-
all: (sql, params = []) => db.prepare(sql).all(...params)
|
|
1654
|
-
};
|
|
2075
|
+
return openSqlite(this.stateDbPath);
|
|
1655
2076
|
}
|
|
1656
2077
|
initDatabaseSchema(db) {
|
|
1657
2078
|
db.exec("PRAGMA busy_timeout = 5000;");
|
|
@@ -1693,6 +2114,12 @@ var SessionStateStoreImpl = class {
|
|
|
1693
2114
|
db.exec(`
|
|
1694
2115
|
CREATE INDEX IF NOT EXISTS idx_session_state_updated_at
|
|
1695
2116
|
ON session_state(updated_at DESC);
|
|
2117
|
+
CREATE TABLE IF NOT EXISTS session_approval_steers (
|
|
2118
|
+
session_id TEXT NOT NULL,
|
|
2119
|
+
run_id TEXT NOT NULL,
|
|
2120
|
+
steer_id TEXT NOT NULL,
|
|
2121
|
+
PRIMARY KEY (session_id, run_id, steer_id)
|
|
2122
|
+
);
|
|
1696
2123
|
`);
|
|
1697
2124
|
db.exec(`
|
|
1698
2125
|
CREATE TABLE IF NOT EXISTS session_runs (
|
|
@@ -1725,6 +2152,7 @@ var SessionStateStoreImpl = class {
|
|
|
1725
2152
|
value TEXT NOT NULL
|
|
1726
2153
|
);
|
|
1727
2154
|
`);
|
|
2155
|
+
initSessionGoals(db);
|
|
1728
2156
|
db.exec("COMMIT");
|
|
1729
2157
|
} catch (error) {
|
|
1730
2158
|
db.exec("ROLLBACK");
|
|
@@ -1887,12 +2315,16 @@ var SessionStateStoreImpl = class {
|
|
|
1887
2315
|
);
|
|
1888
2316
|
});
|
|
1889
2317
|
}
|
|
1890
|
-
async appendMessages(sessionId, messages) {
|
|
2318
|
+
async appendMessages(sessionId, messages, origins) {
|
|
1891
2319
|
const db = await this.requireDb("archive.append", sessionId);
|
|
1892
2320
|
if (!await this.getSummary(sessionId)) await this.load(sessionId);
|
|
1893
2321
|
await this.withRetentionGuard(sessionId, () => {
|
|
1894
2322
|
this.ensureArchive(sessionId, db);
|
|
1895
|
-
appendOriginalMessages(
|
|
2323
|
+
appendOriginalMessages(
|
|
2324
|
+
this.resolveMessagePath(sessionId),
|
|
2325
|
+
messages,
|
|
2326
|
+
origins
|
|
2327
|
+
);
|
|
1896
2328
|
});
|
|
1897
2329
|
}
|
|
1898
2330
|
async searchMessages(sessionId, options) {
|
|
@@ -1903,6 +2335,25 @@ var SessionStateStoreImpl = class {
|
|
|
1903
2335
|
if (!await this.getSummary(sessionId)) await this.load(sessionId);
|
|
1904
2336
|
return readOriginalMessage(this.resolveMessagePath(sessionId), options);
|
|
1905
2337
|
}
|
|
2338
|
+
async readApprovalContext(sessionId, references) {
|
|
2339
|
+
if (!await this.getSummary(sessionId)) return null;
|
|
2340
|
+
const db = await this.requireDb("archive.approval", sessionId);
|
|
2341
|
+
return readOriginalApprovalContext(
|
|
2342
|
+
this.resolveMessagePath(sessionId),
|
|
2343
|
+
references,
|
|
2344
|
+
(runId, steerId) => !!db.get(
|
|
2345
|
+
"SELECT 1 AS applied FROM session_approval_steers WHERE session_id = ? AND run_id = ? AND steer_id = ?",
|
|
2346
|
+
[sessionId, runId, steerId]
|
|
2347
|
+
)
|
|
2348
|
+
);
|
|
2349
|
+
}
|
|
2350
|
+
async confirmApprovalSteer(sessionId, runId, steerId) {
|
|
2351
|
+
const db = await this.requireDb("archive.steer", sessionId);
|
|
2352
|
+
db.run(
|
|
2353
|
+
"INSERT OR IGNORE INTO session_approval_steers (session_id, run_id, steer_id) VALUES (?, ?, ?)",
|
|
2354
|
+
[sessionId, runId, steerId]
|
|
2355
|
+
);
|
|
2356
|
+
}
|
|
1906
2357
|
async load(sessionId) {
|
|
1907
2358
|
const db = await this.requireDb("load", sessionId);
|
|
1908
2359
|
try {
|
|
@@ -3434,6 +3885,7 @@ export {
|
|
|
3434
3885
|
ProjectsPolicyStore,
|
|
3435
3886
|
RUN_LOG_RETENTION_MS,
|
|
3436
3887
|
RunEventStoreFactoryImpl,
|
|
3888
|
+
SessionGoalStore,
|
|
3437
3889
|
SessionStateStoreImpl,
|
|
3438
3890
|
SessionStoreWriterImpl,
|
|
3439
3891
|
StoragePathServiceImpl,
|