@zero-gravity/zero-gravity 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/LICENSE +21 -0
- package/README.md +50 -2
- package/THIRD-PARTY-NOTICES.md +100 -0
- package/dist/adv-context-SLTP32JQ.js +36 -0
- package/dist/advanced-EPLZB6DG.js +164 -0
- package/dist/agents-JYRQHH7R.js +181 -0
- package/dist/chat-AEHVCKXX.js +47 -0
- package/dist/chunk-2OH5KHWO.js +112 -0
- package/dist/chunk-2ZYSAYMJ.js +108 -0
- package/dist/chunk-4BZ4IXTO.js +161 -0
- package/dist/chunk-4ITJY25Z.js +144 -0
- package/dist/chunk-4JBLZQAQ.js +65 -0
- package/dist/chunk-6QLYRU3N.js +28 -0
- package/dist/chunk-7TACFVY2.js +57 -0
- package/dist/chunk-AY36KJTH.js +3023 -0
- package/dist/chunk-BJABQO7S.js +378 -0
- package/dist/chunk-C2GFK4JP.js +387 -0
- package/dist/chunk-CDC2K2KP.js +47 -0
- package/dist/chunk-DKCCXMSE.js +27 -0
- package/dist/chunk-FC3UOHOO.js +194 -0
- package/dist/chunk-FIASMDLX.js +216 -0
- package/dist/chunk-GMVDCQVW.js +88 -0
- package/dist/chunk-JQYZX56A.js +231 -0
- package/dist/chunk-JU5PGDOD.js +138 -0
- package/dist/chunk-JUZP5SXD.js +309 -0
- package/dist/chunk-KGA7VWQG.js +70 -0
- package/dist/chunk-L7VNR5LM.js +407 -0
- package/dist/chunk-LOSXCWHU.js +145 -0
- package/dist/chunk-NVC433AX.js +24 -0
- package/dist/chunk-QH27MDJM.js +248 -0
- package/dist/chunk-QUC5URWQ.js +708 -0
- package/dist/chunk-R2CPYTSP.js +31 -0
- package/dist/chunk-R5KQACGR.js +2833 -0
- package/dist/chunk-R6DONQKN.js +153 -0
- package/dist/chunk-RIX4S3J7.js +4747 -0
- package/dist/chunk-SZKAZ2VN.js +35 -0
- package/dist/chunk-T6DDNE3W.js +1338 -0
- package/dist/chunk-U4URD6TU.js +4605 -0
- package/dist/chunk-U5UIUB6L.js +51 -0
- package/dist/chunk-UMC77TR3.js +79 -0
- package/dist/chunk-UQURXFAE.js +80 -0
- package/dist/chunk-VBG7T7XY.js +1703 -0
- package/dist/chunk-VCCMJIAG.js +326 -0
- package/dist/chunk-VS375NYD.js +91 -0
- package/dist/chunk-WANZOLI5.js +1073 -0
- package/dist/chunk-WUF3TVAE.js +51 -0
- package/dist/chunk-XCWLFZSM.js +149 -0
- package/dist/chunk-YJEUXO5I.js +76 -0
- package/dist/chunk-YR6RCC6Y.js +894 -0
- package/dist/chunk-ZQFAX275.js +35 -0
- package/dist/config-ELG4FQ3K.js +30 -0
- package/dist/config-IEWRCG7R.js +50 -0
- package/dist/doctor-ZZC2D3RW.js +357 -0
- package/dist/ext-context-RIMZMEPB.js +37 -0
- package/dist/index.js +20 -0
- package/dist/init-UB3E47KM.js +22 -0
- package/dist/integrations-HW4VTLN4.js +183 -0
- package/dist/main-RAWWT22W.js +115 -0
- package/dist/mcp-SWD4SO35.js +232 -0
- package/dist/mcp-context-PM5FY665.js +28 -0
- package/dist/memory-QQ54GRCN.js +128 -0
- package/dist/memory-session-R6DGT6CS.js +14 -0
- package/dist/memory-summary-4P26B2ZY.js +18 -0
- package/dist/plugins-VUGTEUNV.js +166 -0
- package/dist/providers-O3WOVP5Q.js +417 -0
- package/dist/report-DDIZ6BLF.js +28 -0
- package/dist/sec-context-VQHW6TOZ.js +15 -0
- package/dist/security-SAYW4LU4.js +95 -0
- package/dist/sessions-CL6CRNQL.js +160 -0
- package/dist/skills-7KDGTTKX.js +126 -0
- package/dist/version-6E6A23B3.js +13 -0
- package/package.json +70 -4
|
@@ -0,0 +1,4605 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
AdvancedService,
|
|
4
|
+
ApprovedCommand,
|
|
5
|
+
ExecutionError,
|
|
6
|
+
FsError,
|
|
7
|
+
FsPermissions,
|
|
8
|
+
INDEX_VERSION,
|
|
9
|
+
Indexer,
|
|
10
|
+
UserApproval,
|
|
11
|
+
buildGraph,
|
|
12
|
+
decodeUtf8,
|
|
13
|
+
defaultLanguages,
|
|
14
|
+
dependentsOf,
|
|
15
|
+
detectLineEnding,
|
|
16
|
+
encodeUtf8,
|
|
17
|
+
findReferences,
|
|
18
|
+
fromLf,
|
|
19
|
+
fromNodeError,
|
|
20
|
+
looksBinary,
|
|
21
|
+
readTextFile,
|
|
22
|
+
sha256,
|
|
23
|
+
splitIdentifier,
|
|
24
|
+
splitLines,
|
|
25
|
+
summarize,
|
|
26
|
+
toLf
|
|
27
|
+
} from "./chunk-R5KQACGR.js";
|
|
28
|
+
import {
|
|
29
|
+
GitApproval,
|
|
30
|
+
GitError,
|
|
31
|
+
MAX_PATHS,
|
|
32
|
+
OutputCollector,
|
|
33
|
+
RawStdoutCollector,
|
|
34
|
+
assertReadArgs,
|
|
35
|
+
assertWriteArgs,
|
|
36
|
+
clip,
|
|
37
|
+
diffToText,
|
|
38
|
+
explainGitFailure,
|
|
39
|
+
parseRange,
|
|
40
|
+
safeText,
|
|
41
|
+
sanitizeRemoteUrl,
|
|
42
|
+
secretPathReason,
|
|
43
|
+
unquoteGitPath,
|
|
44
|
+
validateBranchName,
|
|
45
|
+
validateCommitMessage,
|
|
46
|
+
validateRelPath,
|
|
47
|
+
validateRevision
|
|
48
|
+
} from "./chunk-L7VNR5LM.js";
|
|
49
|
+
import {
|
|
50
|
+
fenceUntrusted,
|
|
51
|
+
policyFromSettings
|
|
52
|
+
} from "./chunk-LOSXCWHU.js";
|
|
53
|
+
import {
|
|
54
|
+
projectIdFor
|
|
55
|
+
} from "./chunk-YR6RCC6Y.js";
|
|
56
|
+
import {
|
|
57
|
+
atomicWriteFile
|
|
58
|
+
} from "./chunk-U5UIUB6L.js";
|
|
59
|
+
import {
|
|
60
|
+
detectProject,
|
|
61
|
+
findProjectRoot,
|
|
62
|
+
loadIgnoreRules,
|
|
63
|
+
walk
|
|
64
|
+
} from "./chunk-JQYZX56A.js";
|
|
65
|
+
import {
|
|
66
|
+
NEVER_PASS_ENV
|
|
67
|
+
} from "./chunk-QH27MDJM.js";
|
|
68
|
+
import {
|
|
69
|
+
protectedDirReason,
|
|
70
|
+
sensitiveReason
|
|
71
|
+
} from "./chunk-ZQFAX275.js";
|
|
72
|
+
import {
|
|
73
|
+
redactSecrets
|
|
74
|
+
} from "./chunk-WUF3TVAE.js";
|
|
75
|
+
|
|
76
|
+
// src/security/guards.ts
|
|
77
|
+
var DEPENDENCY_PROGRAMS = /* @__PURE__ */ new Set(["npm", "pnpm", "yarn", "bun", "pip", "pip3", "pipx", "poetry", "uv", "cargo", "go", "gem", "bundle", "composer", "dotnet", "nuget", "apt", "apt-get", "dnf", "yum", "pacman", "apk", "brew", "choco", "winget", "scoop", "pkg"]);
|
|
78
|
+
var DEPENDENCY_VERBS = /^(install|i|add|remove|rm|uninstall|update|upgrade|up|ci|get|dedupe|prune|link|unlink|publish)$/;
|
|
79
|
+
var baseName = (p) => p.replace(/^.*[\\/]/, "").replace(/\.(exe|cmd|bat)$/i, "").toLowerCase();
|
|
80
|
+
var RISK = { low: "low", medium: "medium", high: "high", blocked: "critical" };
|
|
81
|
+
function commandLevel(spec) {
|
|
82
|
+
if (spec.kind === "direct") {
|
|
83
|
+
const prog = baseName(spec.program);
|
|
84
|
+
const verb = spec.args.find((a) => !a.startsWith("-"));
|
|
85
|
+
if (DEPENDENCY_PROGRAMS.has(prog) && verb && DEPENDENCY_VERBS.test(verb)) return "dependency";
|
|
86
|
+
if ((prog === "pip" || prog === "pip3" || prog === "python" || prog === "python3") && spec.args.includes("pip") && spec.args.some((a) => /^(install|uninstall)$/.test(a))) return "dependency";
|
|
87
|
+
return "command";
|
|
88
|
+
}
|
|
89
|
+
return /\b(npm|pnpm|yarn|pip3?|cargo|apt(-get)?|brew|gem|composer)\s+(install|add|remove|uninstall|update|upgrade|i)\b/.test(spec.line) ? "dependency" : "command";
|
|
90
|
+
}
|
|
91
|
+
function commandRequest(p, actor = "user") {
|
|
92
|
+
const spec = p.request.spec;
|
|
93
|
+
const risk = RISK[p.assessment.risk];
|
|
94
|
+
return {
|
|
95
|
+
level: commandLevel(spec),
|
|
96
|
+
operation: p.assessment.usesShell ? "run shell command" : "run command",
|
|
97
|
+
resource: "command",
|
|
98
|
+
target: spec.kind === "direct" ? baseName(spec.program) : "shell",
|
|
99
|
+
detail: redactSecrets(p.display).slice(0, 1e3),
|
|
100
|
+
component: "command-engine",
|
|
101
|
+
actor: p.request.source === "agent" || p.request.source === "ai-proposed" ? "ai" : actor,
|
|
102
|
+
risk: p.assessment.usesShell && risk === "low" ? "medium" : risk,
|
|
103
|
+
reason: p.request.purpose,
|
|
104
|
+
consequences: p.request.expectedEffect
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function fileRequest(rel, op, extra = {}) {
|
|
108
|
+
const read = op === "read";
|
|
109
|
+
return {
|
|
110
|
+
level: read ? "analyze" : "modify",
|
|
111
|
+
operation: read ? "read file" : `${op} file`,
|
|
112
|
+
resource: "file",
|
|
113
|
+
target: rel,
|
|
114
|
+
component: "filesystem",
|
|
115
|
+
actor: read ? "ai" : "user",
|
|
116
|
+
risk: op === "delete" ? "high" : "low",
|
|
117
|
+
destructive: op === "delete",
|
|
118
|
+
...extra
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// src/execution/command-parser.ts
|
|
123
|
+
var MAX_SEGMENTS = 10;
|
|
124
|
+
var MAX_LINE = 2e3;
|
|
125
|
+
function analyzeShellLine(line, flavor) {
|
|
126
|
+
const out = { segments: [], operators: [], blocked: [], warnings: [] };
|
|
127
|
+
if (line.length > MAX_LINE) {
|
|
128
|
+
out.blocked.push("the command line is too long to assess");
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
const win = flavor === "windows";
|
|
132
|
+
let i = 0;
|
|
133
|
+
let tokens = [];
|
|
134
|
+
let redirects = [];
|
|
135
|
+
const block = (reason) => {
|
|
136
|
+
if (!out.blocked.includes(reason)) out.blocked.push(reason);
|
|
137
|
+
};
|
|
138
|
+
const warn = (w) => {
|
|
139
|
+
if (!out.warnings.includes(w)) out.warnings.push(w);
|
|
140
|
+
};
|
|
141
|
+
const endSegment = (op) => {
|
|
142
|
+
if (tokens.length === 0 && redirects.length === 0) {
|
|
143
|
+
if (op !== null && (out.segments.length > 0 || op !== "newline")) {
|
|
144
|
+
if (op !== "newline") block("a command in the chain is empty");
|
|
145
|
+
}
|
|
146
|
+
} else out.segments.push({ tokens, redirects });
|
|
147
|
+
tokens = [];
|
|
148
|
+
redirects = [];
|
|
149
|
+
if (op !== null) out.operators.push(op);
|
|
150
|
+
};
|
|
151
|
+
const readWord = () => {
|
|
152
|
+
let buf = "";
|
|
153
|
+
let any = false;
|
|
154
|
+
for (; i < line.length; i++) {
|
|
155
|
+
const c = line[i];
|
|
156
|
+
if (c === " " || c === " " || c === "\n" || c === "\r" || c === ";" || c === "&" || c === "|" || c === "<" || c === ">" || c === "(" || c === ")") break;
|
|
157
|
+
any = true;
|
|
158
|
+
if (c === "`") {
|
|
159
|
+
block("command substitution with backticks");
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (win && (c === "%" || c === "^")) {
|
|
163
|
+
block("cmd.exe variable expansion or escape characters (% and ^)");
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
if (c === "'" && !win) {
|
|
167
|
+
const end = line.indexOf("'", i + 1);
|
|
168
|
+
if (end < 0) {
|
|
169
|
+
block("an unbalanced quote");
|
|
170
|
+
i = line.length;
|
|
171
|
+
return buf;
|
|
172
|
+
}
|
|
173
|
+
buf += line.slice(i + 1, end);
|
|
174
|
+
i = end;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (c === '"') {
|
|
178
|
+
let j = i + 1;
|
|
179
|
+
let closed = false;
|
|
180
|
+
for (; j < line.length; j++) {
|
|
181
|
+
const d = line[j];
|
|
182
|
+
if (d === '"') {
|
|
183
|
+
closed = true;
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
if (d === "\\" && !win && j + 1 < line.length && '"\\$`'.includes(line[j + 1])) {
|
|
187
|
+
buf += line[j + 1];
|
|
188
|
+
j++;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (d === "`") block("command substitution with backticks");
|
|
192
|
+
else if (d === "$" && (line[j + 1] === "(" || line[j + 1] === "{")) block("command or parameter substitution ($( or ${)");
|
|
193
|
+
else if (d === "$" && /[A-Za-z_?0-9@*#!$-]/.test(line[j + 1] ?? "")) warn("contains a $variable the shell would expand");
|
|
194
|
+
else if (win && (d === "%" || d === "^")) block("cmd.exe variable expansion or escape characters (% and ^)");
|
|
195
|
+
buf += d;
|
|
196
|
+
}
|
|
197
|
+
if (!closed) {
|
|
198
|
+
block("an unbalanced quote");
|
|
199
|
+
i = line.length;
|
|
200
|
+
return buf;
|
|
201
|
+
}
|
|
202
|
+
i = j;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (c === "\\" && !win) {
|
|
206
|
+
if (i + 1 < line.length) {
|
|
207
|
+
buf += line[i + 1];
|
|
208
|
+
i++;
|
|
209
|
+
}
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (c === "$") {
|
|
213
|
+
const n = line[i + 1] ?? "";
|
|
214
|
+
if (n === "(" || n === "{") block("command or parameter substitution ($( or ${)");
|
|
215
|
+
else if (/[A-Za-z_?0-9@*#!$-]/.test(n)) warn("contains a $variable the shell would expand");
|
|
216
|
+
}
|
|
217
|
+
if (c === "#" && buf === "") block("shell comments");
|
|
218
|
+
buf += c;
|
|
219
|
+
}
|
|
220
|
+
return any ? buf : null;
|
|
221
|
+
};
|
|
222
|
+
while (i < line.length) {
|
|
223
|
+
const c = line[i];
|
|
224
|
+
if (c === " " || c === " " || c === "\r") {
|
|
225
|
+
i++;
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (c === "\n") {
|
|
229
|
+
if (win) block("multi-line commands on Windows");
|
|
230
|
+
i++;
|
|
231
|
+
endSegment("newline");
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
if (c === ";") {
|
|
235
|
+
i++;
|
|
236
|
+
endSegment(";");
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (c === "&") {
|
|
240
|
+
if (line[i + 1] === "&") {
|
|
241
|
+
i += 2;
|
|
242
|
+
endSegment("&&");
|
|
243
|
+
} else {
|
|
244
|
+
i++;
|
|
245
|
+
if (win) endSegment("&");
|
|
246
|
+
else {
|
|
247
|
+
block("background execution (&)");
|
|
248
|
+
endSegment("&");
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
if (c === "|") {
|
|
254
|
+
if (line[i + 1] === "|") {
|
|
255
|
+
i += 2;
|
|
256
|
+
endSegment("||");
|
|
257
|
+
} else {
|
|
258
|
+
if (line[i + 1] === "&") block("piping stderr with |&");
|
|
259
|
+
i++;
|
|
260
|
+
endSegment("|");
|
|
261
|
+
}
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
if (c === "(" || c === ")") {
|
|
265
|
+
block("grouping or a subshell");
|
|
266
|
+
i++;
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
if (c === "<" || c === ">") {
|
|
270
|
+
let op = c;
|
|
271
|
+
i++;
|
|
272
|
+
if (line[i] === c) {
|
|
273
|
+
op += c;
|
|
274
|
+
i++;
|
|
275
|
+
if (c === "<") {
|
|
276
|
+
block("a here-document");
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (c === "<" && line[i] === "(") {
|
|
281
|
+
block("process substitution");
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (c === ">" && line[i] === "(") {
|
|
285
|
+
block("process substitution");
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (line[i] === "&") {
|
|
289
|
+
const m = /^&(\d|-)/.exec(line.slice(i));
|
|
290
|
+
if (m) {
|
|
291
|
+
i += 2;
|
|
292
|
+
if (tokens.length > 0 && /^\d$/.test(tokens[tokens.length - 1])) tokens.pop();
|
|
293
|
+
redirects.push({ op: "dup", target: m[1] });
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
i++;
|
|
297
|
+
op += "&";
|
|
298
|
+
}
|
|
299
|
+
while (line[i] === " " || line[i] === " ") i++;
|
|
300
|
+
const target = readWord();
|
|
301
|
+
if (target === null || target === "") block("a redirection with no target");
|
|
302
|
+
else redirects.push({ op, target });
|
|
303
|
+
if (tokens.length > 0 && /^\d$/.test(tokens[tokens.length - 1]) && line[i - 1] !== " ") tokens.pop();
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
const w = readWord();
|
|
307
|
+
if (w !== null) tokens.push(w);
|
|
308
|
+
else i++;
|
|
309
|
+
}
|
|
310
|
+
const dangling = tokens.length === 0 && redirects.length === 0 && ["&&", "||", "|"].includes(out.operators[out.operators.length - 1] ?? "");
|
|
311
|
+
if (dangling) block("the command ends with an operator and nothing after it");
|
|
312
|
+
endSegment(null);
|
|
313
|
+
if (out.segments.length > MAX_SEGMENTS) block(`more than ${MAX_SEGMENTS} chained commands`);
|
|
314
|
+
if (out.segments.length === 0 && out.blocked.length === 0) out.blocked.push("the command is empty");
|
|
315
|
+
return out;
|
|
316
|
+
}
|
|
317
|
+
var ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
318
|
+
function parseUserCommand(line, flavor) {
|
|
319
|
+
const text3 = line.trim();
|
|
320
|
+
if (text3 === "") return { ok: false, error: "The command is empty." };
|
|
321
|
+
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(text3)) return { ok: false, error: "The command contains control characters." };
|
|
322
|
+
const a = analyzeShellLine(text3, flavor);
|
|
323
|
+
const simple = a.segments.length === 1 && a.operators.length === 0 && a.segments[0].redirects.length === 0 && a.blocked.length === 0;
|
|
324
|
+
if (!simple) return { ok: true, spec: { kind: "shell", line: text3 }, warnings: a.warnings, blocked: a.blocked };
|
|
325
|
+
const tokens = a.segments[0].tokens;
|
|
326
|
+
const program = tokens[0];
|
|
327
|
+
if (program === void 0) return { ok: false, error: "The command is empty." };
|
|
328
|
+
if (ENV_ASSIGNMENT.test(program)) return { ok: false, error: "Setting environment variables inline (NAME=value command) is not supported. Allowed variables are set with execution.envAllowlist." };
|
|
329
|
+
const warnings = a.warnings.map((w) => `${w}; without a shell it is passed as literal text`);
|
|
330
|
+
if (tokens.some((t) => /[*?]/.test(t))) warnings.push("wildcards (* ?) are not expanded without a shell; they are passed as literal text");
|
|
331
|
+
return { ok: true, spec: { kind: "direct", program, args: tokens.slice(1) }, warnings, blocked: [] };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/execution/command-session.ts
|
|
335
|
+
var MAX_HISTORY = 50;
|
|
336
|
+
var OUTPUT_KEPT = 2e3;
|
|
337
|
+
var CommandSession = class {
|
|
338
|
+
#entries = [];
|
|
339
|
+
record(result) {
|
|
340
|
+
const { output, ...rest } = result;
|
|
341
|
+
this.#entries.push({ ...rest, outputTail: output.length > OUTPUT_KEPT ? `[...]
|
|
342
|
+
${output.slice(-OUTPUT_KEPT)}` : output });
|
|
343
|
+
while (this.#entries.length > MAX_HISTORY) this.#entries.shift();
|
|
344
|
+
}
|
|
345
|
+
list() {
|
|
346
|
+
return this.#entries;
|
|
347
|
+
}
|
|
348
|
+
/** Clears the stored output of past commands. The list itself (what ran, exit codes) is kept as a record. */
|
|
349
|
+
clearOutput() {
|
|
350
|
+
let n = 0;
|
|
351
|
+
for (const e of this.#entries) {
|
|
352
|
+
if (e.outputTail !== "") n++;
|
|
353
|
+
e.outputTail = "";
|
|
354
|
+
}
|
|
355
|
+
return n;
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
// src/execution/command-validator.ts
|
|
360
|
+
import { createHash, randomBytes } from "crypto";
|
|
361
|
+
import { promises as fsp4 } from "fs";
|
|
362
|
+
|
|
363
|
+
// src/execution/command-policy.ts
|
|
364
|
+
import { promises as fsp2 } from "fs";
|
|
365
|
+
import path2 from "path";
|
|
366
|
+
|
|
367
|
+
// src/filesystem/path-validator.ts
|
|
368
|
+
import { promises as fsp } from "fs";
|
|
369
|
+
import path from "path";
|
|
370
|
+
var RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;
|
|
371
|
+
function isInside(parent, child) {
|
|
372
|
+
const rel = path.relative(parent, child);
|
|
373
|
+
return rel === "" || rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
|
|
374
|
+
}
|
|
375
|
+
var PathValidator = class _PathValidator {
|
|
376
|
+
root;
|
|
377
|
+
constructor(root) {
|
|
378
|
+
this.root = root;
|
|
379
|
+
}
|
|
380
|
+
/** `rootInput` must be an existing directory. Its canonical path becomes the workspace root. */
|
|
381
|
+
static async create(rootInput) {
|
|
382
|
+
let real;
|
|
383
|
+
try {
|
|
384
|
+
real = await fsp.realpath(rootInput);
|
|
385
|
+
if (!(await fsp.stat(real)).isDirectory()) throw new FsError("unusable-root", "The project root is not a directory.");
|
|
386
|
+
} catch (err) {
|
|
387
|
+
if (err instanceof FsError) throw err;
|
|
388
|
+
throw new FsError("unusable-root", "The project root does not exist or cannot be read.", "Check filesystem.projectRoot or start zg inside your project folder.");
|
|
389
|
+
}
|
|
390
|
+
if (path.parse(real).root === real) throw new FsError("unusable-root", "The filesystem root cannot be used as a project root.", "Start zg inside your project folder.");
|
|
391
|
+
return new _PathValidator(real);
|
|
392
|
+
}
|
|
393
|
+
/** Purely lexical checks and normalisation. Does not touch the disk. */
|
|
394
|
+
lexical(input, opts = {}) {
|
|
395
|
+
if (typeof input !== "string" || input.trim() === "") throw new FsError("invalid-path", "The path is empty.");
|
|
396
|
+
if (input.length > 1e3) throw new FsError("invalid-path", "The path is too long.");
|
|
397
|
+
if (/[\u0000-\u001f\u007f]/.test(input)) throw new FsError("invalid-path", "The path contains control characters.");
|
|
398
|
+
if (/^[a-zA-Z]:/.test(input) && !path.isAbsolute(input)) throw new FsError("invalid-path", "Drive-relative paths are not allowed.");
|
|
399
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(input)) throw new FsError("invalid-path", "URLs are not file paths.");
|
|
400
|
+
if (input.startsWith("~")) throw new FsError("outside-workspace", "Paths starting with ~ are outside the project.", "Use a path relative to the project root.");
|
|
401
|
+
let rel;
|
|
402
|
+
if (path.isAbsolute(input)) {
|
|
403
|
+
const abs = path.resolve(input);
|
|
404
|
+
if (!isInside(this.root, abs)) throw new FsError("outside-workspace", `${shorten(input)} is outside the project root.`, "Only paths inside the project can be used.");
|
|
405
|
+
rel = path.relative(this.root, abs).split(path.sep).join("/");
|
|
406
|
+
} else {
|
|
407
|
+
rel = input.replace(/\\/g, "/");
|
|
408
|
+
}
|
|
409
|
+
const segments = rel.split("/").filter((s) => s !== "" && s !== ".");
|
|
410
|
+
if (segments.some((s) => s === "..")) throw new FsError("outside-workspace", `${shorten(input)} uses "..", which is not allowed.`, 'Use a path relative to the project root, without "..".');
|
|
411
|
+
for (const s of segments) {
|
|
412
|
+
if (RESERVED.test(s) || /[. ]$/.test(s) || /[<>"|?*]/.test(s)) throw new FsError("invalid-path", `"${shorten(s)}" is not a valid file name on every supported system.`);
|
|
413
|
+
}
|
|
414
|
+
const clean = segments.join("/");
|
|
415
|
+
if (clean === "" && !opts.allowRoot) throw new FsError("invalid-path", "The path points at the project root itself.");
|
|
416
|
+
return clean;
|
|
417
|
+
}
|
|
418
|
+
/** Canonical, containment-checked path of something that must already exist. */
|
|
419
|
+
async resolveExisting(input, opts = {}) {
|
|
420
|
+
const rel = this.lexical(input, opts);
|
|
421
|
+
this.#policy(rel, opts, false);
|
|
422
|
+
const lexicalAbs = path.join(this.root, ...rel.split("/").filter(Boolean));
|
|
423
|
+
let real;
|
|
424
|
+
try {
|
|
425
|
+
real = await fsp.realpath(lexicalAbs);
|
|
426
|
+
} catch (err) {
|
|
427
|
+
throw fromNodeError(err, rel || ".");
|
|
428
|
+
}
|
|
429
|
+
if (!isInside(this.root, real)) throw new FsError("symlink", `${rel} resolves outside the project root through a symbolic link.`, "Symbolic links that leave the project are never followed.");
|
|
430
|
+
const realRel = path.relative(this.root, real).split(path.sep).join("/");
|
|
431
|
+
if (realRel !== rel) this.#policy(realRel, opts, false);
|
|
432
|
+
return { rel, abs: real };
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* For a file that will be created or written: the parent must exist and resolve inside the root,
|
|
436
|
+
* and the final component must not be a symbolic link (zg never writes through links).
|
|
437
|
+
*/
|
|
438
|
+
async resolveForWrite(input, opts) {
|
|
439
|
+
const rel = this.lexical(input);
|
|
440
|
+
this.#policy(rel, {}, true);
|
|
441
|
+
const parts = rel.split("/");
|
|
442
|
+
const name = parts[parts.length - 1];
|
|
443
|
+
const parentRel = parts.slice(0, -1).join("/");
|
|
444
|
+
const parentAbs = path.join(this.root, ...parts.slice(0, -1));
|
|
445
|
+
const parentReal = await this.#nearestExistingReal(parentAbs, parentRel);
|
|
446
|
+
const abs = path.join(parentReal.real, ...parentReal.missing, name);
|
|
447
|
+
let exists = false;
|
|
448
|
+
try {
|
|
449
|
+
const st = await fsp.lstat(abs);
|
|
450
|
+
exists = true;
|
|
451
|
+
if (st.isSymbolicLink()) throw new FsError("symlink", `${rel} is a symbolic link. zg does not write through links.`);
|
|
452
|
+
if (st.isDirectory()) throw new FsError("is-directory", `${rel} is a directory.`);
|
|
453
|
+
} catch (err) {
|
|
454
|
+
if (err instanceof FsError) throw err;
|
|
455
|
+
if (err.code !== "ENOENT") throw fromNodeError(err, rel);
|
|
456
|
+
}
|
|
457
|
+
if (opts.mustExist && !exists) throw new FsError("not-found", `${rel} does not exist.`);
|
|
458
|
+
return { rel, abs, exists };
|
|
459
|
+
}
|
|
460
|
+
/** Directories that do not exist yet below the nearest existing real directory (all inside the root). */
|
|
461
|
+
async missingParents(rel) {
|
|
462
|
+
const parts = this.lexical(rel).split("/").slice(0, -1);
|
|
463
|
+
const out = [];
|
|
464
|
+
for (let i = parts.length; i > 0; i--) {
|
|
465
|
+
const dir = path.join(this.root, ...parts.slice(0, i));
|
|
466
|
+
try {
|
|
467
|
+
await fsp.lstat(dir);
|
|
468
|
+
break;
|
|
469
|
+
} catch (err) {
|
|
470
|
+
if (err.code !== "ENOENT") throw fromNodeError(err, parts.slice(0, i).join("/"));
|
|
471
|
+
out.unshift(parts.slice(0, i).join("/"));
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return out;
|
|
475
|
+
}
|
|
476
|
+
async #nearestExistingReal(abs, relForErrors) {
|
|
477
|
+
const missing = [];
|
|
478
|
+
let cur = abs;
|
|
479
|
+
for (; ; ) {
|
|
480
|
+
try {
|
|
481
|
+
const real = await fsp.realpath(cur);
|
|
482
|
+
if (!isInside(this.root, real)) throw new FsError("symlink", `${relForErrors || "."} resolves outside the project root through a symbolic link.`);
|
|
483
|
+
if (!(await fsp.stat(real)).isDirectory()) throw new FsError("not-a-file", `${relForErrors || "."} is not a directory.`);
|
|
484
|
+
return { real, missing };
|
|
485
|
+
} catch (err) {
|
|
486
|
+
if (err instanceof FsError) throw err;
|
|
487
|
+
if (err.code !== "ENOENT") throw fromNodeError(err, relForErrors);
|
|
488
|
+
const parent = path.dirname(cur);
|
|
489
|
+
if (parent === cur || !isInside(this.root, parent)) throw new FsError("outside-workspace", "The path leaves the project root.");
|
|
490
|
+
missing.unshift(path.basename(cur));
|
|
491
|
+
cur = parent;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
#policy(rel, opts, forWrite) {
|
|
496
|
+
if (rel === "") return;
|
|
497
|
+
if (!opts.allowSensitive || forWrite) {
|
|
498
|
+
const why = sensitiveReason(rel);
|
|
499
|
+
if (why) throw new FsError("sensitive", `${rel} is ${why}, so zg will not ${forWrite ? "change" : "read"} it.`, forWrite ? void 0 : "Only you can allow reading such a file, explicitly, with /read <path> allow.");
|
|
500
|
+
}
|
|
501
|
+
if (forWrite) {
|
|
502
|
+
const why = protectedDirReason(rel);
|
|
503
|
+
if (why) throw new FsError("protected", `${rel} is ${why}.`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
function shorten(s) {
|
|
508
|
+
const clean = s.replace(/[\u0000-\u001f\u007f]/g, "?");
|
|
509
|
+
return clean.length > 80 ? `${clean.slice(0, 77)}...` : clean;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// src/execution/command-types.ts
|
|
513
|
+
import { z } from "zod";
|
|
514
|
+
var RISK_ORDER = ["low", "medium", "high", "blocked"];
|
|
515
|
+
function maxRisk(a, b) {
|
|
516
|
+
return RISK_ORDER.indexOf(a) >= RISK_ORDER.indexOf(b) ? a : b;
|
|
517
|
+
}
|
|
518
|
+
var text = (min, max) => z.string().trim().min(min).max(max);
|
|
519
|
+
var CommandProposalSchema = z.object({
|
|
520
|
+
clarify: text(1, 400).optional(),
|
|
521
|
+
program: z.string().min(1).max(260).optional(),
|
|
522
|
+
args: z.array(z.string().max(2e3)).max(100).default([]),
|
|
523
|
+
shell: z.string().min(1).max(2e3).optional(),
|
|
524
|
+
cwd: z.string().min(1).max(260).optional(),
|
|
525
|
+
purpose: text(3, 300).optional(),
|
|
526
|
+
expectedEffect: text(3, 500).optional(),
|
|
527
|
+
timeoutSeconds: z.number().int().min(1).max(3600).optional()
|
|
528
|
+
}).strict();
|
|
529
|
+
function displayCommand(spec) {
|
|
530
|
+
if (spec.kind === "shell") return spec.line;
|
|
531
|
+
return [spec.program, ...spec.args].map(quoteForDisplay).join(" ");
|
|
532
|
+
}
|
|
533
|
+
function quoteForDisplay(token) {
|
|
534
|
+
if (token === "") return '""';
|
|
535
|
+
return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(token) ? token : `"${token.replace(/(["\\])/g, "\\$1")}"`;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// src/execution/command-policy.ts
|
|
539
|
+
var BLOCKED = {
|
|
540
|
+
sudo: "elevates privileges",
|
|
541
|
+
su: "elevates privileges",
|
|
542
|
+
doas: "elevates privileges",
|
|
543
|
+
pkexec: "elevates privileges",
|
|
544
|
+
runas: "elevates privileges",
|
|
545
|
+
mkfs: "formats storage",
|
|
546
|
+
fdisk: "changes disk partitions",
|
|
547
|
+
parted: "changes disk partitions",
|
|
548
|
+
format: "formats storage",
|
|
549
|
+
diskpart: "changes disk partitions",
|
|
550
|
+
dd: "writes raw data to devices",
|
|
551
|
+
shutdown: "shuts the system down",
|
|
552
|
+
reboot: "restarts the system",
|
|
553
|
+
halt: "shuts the system down",
|
|
554
|
+
poweroff: "shuts the system down",
|
|
555
|
+
init: "changes the system state",
|
|
556
|
+
mount: "changes mounted storage",
|
|
557
|
+
umount: "changes mounted storage",
|
|
558
|
+
iptables: "changes firewall rules",
|
|
559
|
+
ufw: "changes firewall rules",
|
|
560
|
+
netsh: "changes network settings",
|
|
561
|
+
passwd: "changes accounts",
|
|
562
|
+
useradd: "changes accounts",
|
|
563
|
+
userdel: "changes accounts",
|
|
564
|
+
usermod: "changes accounts",
|
|
565
|
+
net: "changes accounts or network shares",
|
|
566
|
+
systemctl: "controls system services",
|
|
567
|
+
service: "controls system services",
|
|
568
|
+
launchctl: "controls system services",
|
|
569
|
+
sc: "controls system services",
|
|
570
|
+
schtasks: "creates scheduled tasks",
|
|
571
|
+
crontab: "changes scheduled tasks",
|
|
572
|
+
at: "creates scheduled tasks",
|
|
573
|
+
reg: "edits the Windows registry",
|
|
574
|
+
regedit: "edits the Windows registry",
|
|
575
|
+
bcdedit: "changes boot settings",
|
|
576
|
+
vssadmin: "deletes system backups",
|
|
577
|
+
cipher: "can wipe free space",
|
|
578
|
+
takeown: "changes ownership",
|
|
579
|
+
setenforce: "disables security controls",
|
|
580
|
+
csrutil: "disables security controls",
|
|
581
|
+
spctl: "changes security settings",
|
|
582
|
+
ssh: "opens remote sessions",
|
|
583
|
+
scp: "copies to or from remote machines",
|
|
584
|
+
sftp: "opens remote sessions",
|
|
585
|
+
ftp: "opens remote sessions",
|
|
586
|
+
telnet: "opens remote sessions",
|
|
587
|
+
nc: "opens raw network connections",
|
|
588
|
+
ncat: "opens raw network connections",
|
|
589
|
+
netcat: "opens raw network connections",
|
|
590
|
+
socat: "opens raw network connections",
|
|
591
|
+
docker: "can reach outside the project (volumes, privileged containers)",
|
|
592
|
+
podman: "can reach outside the project (volumes, privileged containers)",
|
|
593
|
+
kubectl: "changes remote clusters",
|
|
594
|
+
chroot: "changes the root directory",
|
|
595
|
+
eval: "runs text as code",
|
|
596
|
+
exec: "replaces the process with another program",
|
|
597
|
+
source: "runs another script in the shell",
|
|
598
|
+
ln: "creates links that can point outside the project",
|
|
599
|
+
env: "can run other programs and print the environment",
|
|
600
|
+
printenv: "prints environment variables, which may hold secrets",
|
|
601
|
+
export: "changes environment variables",
|
|
602
|
+
set: "prints or changes shell variables",
|
|
603
|
+
xargs: "runs other programs",
|
|
604
|
+
nohup: "runs other programs",
|
|
605
|
+
nice: "runs other programs",
|
|
606
|
+
time: "runs other programs",
|
|
607
|
+
timeout: "runs other programs",
|
|
608
|
+
command: "runs other programs",
|
|
609
|
+
busybox: "runs other programs",
|
|
610
|
+
stdbuf: "runs other programs",
|
|
611
|
+
watch: "runs other programs repeatedly",
|
|
612
|
+
script: "records and runs other programs",
|
|
613
|
+
start: "launches other programs",
|
|
614
|
+
wsl: "runs Linux commands outside this check",
|
|
615
|
+
powershell: "is a shell: run the program directly instead",
|
|
616
|
+
pwsh: "is a shell: run the program directly instead",
|
|
617
|
+
cmd: "is a shell: run the program directly instead",
|
|
618
|
+
bash: "is a shell: run the program directly instead",
|
|
619
|
+
sh: "is a shell: run the program directly instead",
|
|
620
|
+
zsh: "is a shell: run the program directly instead",
|
|
621
|
+
fish: "is a shell: run the program directly instead",
|
|
622
|
+
dash: "is a shell: run the program directly instead",
|
|
623
|
+
ksh: "is a shell: run the program directly instead",
|
|
624
|
+
csh: "is a shell: run the program directly instead",
|
|
625
|
+
tcsh: "is a shell: run the program directly instead",
|
|
626
|
+
vim: "is interactive (zg has no terminal input for commands)",
|
|
627
|
+
vi: "is interactive (zg has no terminal input for commands)",
|
|
628
|
+
nano: "is interactive (zg has no terminal input for commands)",
|
|
629
|
+
emacs: "is interactive (zg has no terminal input for commands)",
|
|
630
|
+
less: "is interactive (zg has no terminal input for commands)",
|
|
631
|
+
more: "is interactive (zg has no terminal input for commands)",
|
|
632
|
+
top: "is interactive (zg has no terminal input for commands)",
|
|
633
|
+
htop: "is interactive (zg has no terminal input for commands)",
|
|
634
|
+
man: "is interactive (zg has no terminal input for commands)",
|
|
635
|
+
mshta: "runs downloaded scripts",
|
|
636
|
+
rundll32: "runs arbitrary code",
|
|
637
|
+
regsvr32: "runs arbitrary code",
|
|
638
|
+
certutil: "downloads and decodes files",
|
|
639
|
+
bitsadmin: "downloads files",
|
|
640
|
+
wscript: "runs scripts",
|
|
641
|
+
cscript: "runs scripts"
|
|
642
|
+
};
|
|
643
|
+
var REMOVERS = /* @__PURE__ */ new Set(["rm", "rmdir", "del", "erase", "rd", "unlink", "shred"]);
|
|
644
|
+
var PERMISSION = /* @__PURE__ */ new Set(["chmod", "chown", "chgrp", "icacls", "attrib", "setfacl"]);
|
|
645
|
+
var WRITERS = /* @__PURE__ */ new Set(["cp", "copy", "xcopy", "robocopy", "mv", "move", "ren", "rename", "mkdir", "md", "touch", "tee", "truncate", "install"]);
|
|
646
|
+
var ARCHIVERS = /* @__PURE__ */ new Set(["tar", "unzip", "zip", "7z", "gzip", "gunzip", "bzip2", "xz", "unrar"]);
|
|
647
|
+
var NETWORK = /* @__PURE__ */ new Set(["curl", "wget", "iwr", "invoke-webrequest", "aria2c"]);
|
|
648
|
+
var REMOTE_OPS = /* @__PURE__ */ new Set(["aws", "gcloud", "az", "terraform", "helm", "heroku", "vercel", "netlify", "firebase", "fly", "flyctl", "gh", "pulumi", "ansible", "ansible-playbook"]);
|
|
649
|
+
var READ_ONLY = /* @__PURE__ */ new Set(["ls", "dir", "pwd", "echo", "cat", "head", "tail", "wc", "grep", "egrep", "fgrep", "rg", "tree", "which", "where", "whoami", "date", "uname", "hostname", "type", "stat", "file", "sort", "uniq", "diff", "cmp", "du", "df", "basename", "dirname", "realpath", "readlink", "true", "false", "cut", "tr", "nl", "id", "uptime", "findstr", "fc", "sha256sum", "md5sum", "shasum", "ver", "vol", "hostid", "locale", "arch", "nproc", "free"]);
|
|
650
|
+
var TOOLING = /* @__PURE__ */ new Set(["tsc", "eslint", "prettier", "vitest", "jest", "mocha", "ava", "tsx", "ts-node", "esbuild", "tsup", "vite", "webpack", "rollup", "parcel", "next", "nuxt", "astro", "svelte-kit", "playwright", "cypress", "pytest", "tox", "nox", "ruff", "mypy", "black", "flake8", "pylint", "isort", "pyright", "cargo", "rustc", "rustfmt", "go", "gofmt", "make", "cmake", "ninja", "gradle", "gradlew", "mvn", "mvnw", "javac", "java", "dotnet", "swift", "swiftc", "gcc", "g++", "clang", "clang++", "cc", "c++", "deno", "bun", "composer", "php", "phpunit", "ruby", "bundle", "rake", "rspec", "mix", "elixir", "dart", "flutter", "kotlinc", "scalac", "sbt", "zig", "nvcc", "pip", "pip3", "pipenv", "poetry", "uv"]);
|
|
651
|
+
var NODE_PM = /* @__PURE__ */ new Set(["npm", "pnpm", "yarn", "bun"]);
|
|
652
|
+
var RUNNERS = /* @__PURE__ */ new Set(["npx", "bunx", "pnpx"]);
|
|
653
|
+
var INTERPRETERS = /* @__PURE__ */ new Set(["node", "python", "python3", "py", "nodejs"]);
|
|
654
|
+
var VERSION_ONLY = /* @__PURE__ */ new Set(["--version", "-v", "-V", "version", "--help", "-h", "help", "-version"]);
|
|
655
|
+
function baseOf(program) {
|
|
656
|
+
const name = program.split(/[\\/]/).pop() ?? program;
|
|
657
|
+
return name.toLowerCase().replace(/\.(exe|cmd|bat|com|ps1)$/, "");
|
|
658
|
+
}
|
|
659
|
+
var part = (risk, reason, warning) => ({ risk, reasons: reason ? [reason] : [], warnings: warning ? [warning] : [] });
|
|
660
|
+
function flagSet(args) {
|
|
661
|
+
const longs = new Set(args.filter((a) => a.startsWith("--")).map((a) => a.split("=")[0]));
|
|
662
|
+
const lower = new Set(args.map((a) => a.toLowerCase()));
|
|
663
|
+
const shorts = new Set(args.filter((a) => /^-[A-Za-z]+$/.test(a)).flatMap((a) => a.slice(1).split("")));
|
|
664
|
+
return { has: (...n) => n.some((x) => longs.has(x) || lower.has(x.toLowerCase())), chars: (...c) => c.some((x) => shorts.has(x)) };
|
|
665
|
+
}
|
|
666
|
+
function classifyProgram(program, args, extraBlocked) {
|
|
667
|
+
const base = baseOf(program);
|
|
668
|
+
if (/[\\/]/.test(program)) {
|
|
669
|
+
if (["gradlew", "mvnw"].includes(base)) return part("medium", `runs the project's ${base} build wrapper`, "Build wrappers run whatever the project's build files say; they are not inspected.");
|
|
670
|
+
return part("high", `runs a program from inside the project (${program})`, "The program file is not inspected. Only approve programs you trust.");
|
|
671
|
+
}
|
|
672
|
+
if (extraBlocked.has(base)) return part("blocked", `"${base}" is on your blocked-programs list`);
|
|
673
|
+
const blockedReason = BLOCKED[base];
|
|
674
|
+
if (blockedReason) return part("blocked", `${base} ${blockedReason}`);
|
|
675
|
+
const f = flagSet(args);
|
|
676
|
+
const onlyVersion = args.length === 1 && VERSION_ONLY.has(args[0]);
|
|
677
|
+
if (REMOVERS.has(base)) {
|
|
678
|
+
if (f.chars("r", "R", "f") || f.has("--recursive", "--force", "/s", "/q", "/f") || args.some((a) => a === "*" || a === "." || a === ".." || a === "/")) return part("blocked", `${base} with recursive, force or wildcard options can delete many files at once`);
|
|
679
|
+
return part("high", `${base} deletes files`, "Deleted files are not backed up. File changes made through zg's edit flow show a diff and keep backups; commands do not.");
|
|
680
|
+
}
|
|
681
|
+
if (PERMISSION.has(base)) return part("high", `${base} changes file permissions or ownership`);
|
|
682
|
+
if (WRITERS.has(base)) return part(base === "mkdir" || base === "md" || base === "touch" ? "medium" : "high", `${base} creates, copies or overwrites files`, "File changes made by commands are not shown as a diff and are not backed up.");
|
|
683
|
+
if (ARCHIVERS.has(base)) return part("high", `${base} can create or extract many files`, "Archives can contain paths that overwrite other files.");
|
|
684
|
+
if (NETWORK.has(base)) return part("high", `${base} downloads from the network`, "Nothing downloaded is executed by zg, but the files may be unsafe.");
|
|
685
|
+
if (REMOTE_OPS.has(base)) return part("high", `${base} acts on remote systems or accounts`);
|
|
686
|
+
if (base === "find") {
|
|
687
|
+
if (f.has("-exec", "-execdir", "-ok", "-okdir")) return part("blocked", "find -exec runs other programs");
|
|
688
|
+
if (f.has("-delete")) return part("high", "find -delete removes files");
|
|
689
|
+
return part("low", "lists files");
|
|
690
|
+
}
|
|
691
|
+
if (base === "sed" || base === "perl" || base === "awk") {
|
|
692
|
+
if (f.has("-i", "--in-place") || args.some((a) => /^-i/.test(a))) return part("high", `${base} -i rewrites files in place`, "In-place edits are not backed up.");
|
|
693
|
+
if (base === "perl" && f.has("-e", "-E")) return part("high", "perl -e runs code from the command line");
|
|
694
|
+
return part("medium", `${base} transforms text`);
|
|
695
|
+
}
|
|
696
|
+
if (base === "git") return classifyGit(args);
|
|
697
|
+
if (NODE_PM.has(base)) return classifyNodePm(base, args);
|
|
698
|
+
if (RUNNERS.has(base)) return part("high", `${base} downloads and runs a package`, "This executes code from the network. Prefer installing and running a project dependency.");
|
|
699
|
+
if (INTERPRETERS.has(base)) return classifyInterpreter(base, args);
|
|
700
|
+
if (READ_ONLY.has(base)) return part("low", "read-only inspection");
|
|
701
|
+
if (TOOLING.has(base)) return classifyTooling(base, args, onlyVersion);
|
|
702
|
+
return part("high", `"${base}" is not a program zg recognises`, "Unknown programs are treated as high risk. Check what it does before approving.");
|
|
703
|
+
}
|
|
704
|
+
function classifyGit(args) {
|
|
705
|
+
let i = 0;
|
|
706
|
+
while (i < args.length && args[i].startsWith("-")) {
|
|
707
|
+
const a = args[i];
|
|
708
|
+
if (a === "--no-pager" || a === "--no-optional-locks") i++;
|
|
709
|
+
else if (a === "--version" || a === "-v" || a === "--help") return part("low", "prints git information");
|
|
710
|
+
else return part("high", `git option ${a.split("=")[0]} changes how git runs`, "Options such as -c or --exec-path can make git run other programs.");
|
|
711
|
+
}
|
|
712
|
+
const sub = (args[i] ?? "").toLowerCase();
|
|
713
|
+
const rest = args.slice(i + 1);
|
|
714
|
+
const f = flagSet(rest);
|
|
715
|
+
if (sub === "") return part("low", "prints git help");
|
|
716
|
+
if (["status", "log", "diff", "show", "rev-parse", "ls-files", "describe", "blame", "shortlog", "grep", "rev-list", "ls-tree", "cat-file", "whatchanged", "reflog", "version", "help", "count-objects", "check-ignore", "diff-tree", "name-rev", "merge-base"].includes(sub)) {
|
|
717
|
+
if (f.has("--output", "--ext-diff", "--textconv")) return part("high", `git ${sub} with ${rest.find((a) => /^--(output|ext-diff|textconv)/.test(a)) ?? "an option"} can write files or run helpers`);
|
|
718
|
+
return part("low", `git ${sub} only reads repository data`);
|
|
719
|
+
}
|
|
720
|
+
if (["branch", "tag", "remote", "stash", "config", "worktree", "notes"].includes(sub)) {
|
|
721
|
+
if (sub === "config") return f.has("--get", "--list", "-l", "--get-all") ? part("low", "reads git configuration") : part("high", "git config changes settings that can run programs");
|
|
722
|
+
if (sub === "remote") return rest.length === 0 || rest.length === 1 && ["-v", "show", "--verbose"].includes(rest[0]) ? part("low", "lists remotes") : part("high", "git remote changes where code is sent");
|
|
723
|
+
if (rest.length === 0 || f.has("--list", "-l", "-a", "--all", "-r", "-v", "-vv", "list")) return part("low", `git ${sub} lists entries`);
|
|
724
|
+
if (f.chars("d", "D") || f.has("--delete", "-d", "-D", "drop", "clear", "prune", "remove")) return part("high", `git ${sub} deletes data`);
|
|
725
|
+
return part("medium", `git ${sub} changes repository data`);
|
|
726
|
+
}
|
|
727
|
+
if (["add", "commit", "checkout", "switch", "restore", "merge", "cherry-pick", "revert", "mv", "init", "apply", "am", "fetch", "pull", "submodule"].includes(sub)) {
|
|
728
|
+
if (sub === "checkout" && rest.includes("--")) return part("high", "git checkout -- discards local changes");
|
|
729
|
+
if (sub === "restore" && !f.has("--staged")) return part("high", "git restore discards local changes");
|
|
730
|
+
if (["fetch", "pull", "submodule"].includes(sub)) return part("high", `git ${sub} uses the network and can change many files`);
|
|
731
|
+
return part("medium", `git ${sub} changes the repository`);
|
|
732
|
+
}
|
|
733
|
+
if (["push", "reset", "clean", "rebase", "clone", "gc", "filter-branch", "update-ref", "rm", "prune", "replace"].includes(sub)) return part("high", `git ${sub} can discard work or change remotes`, "Check the exact arguments carefully.");
|
|
734
|
+
return part("high", `git ${sub} is not a subcommand zg recognises`);
|
|
735
|
+
}
|
|
736
|
+
function classifyNodePm(pm, args) {
|
|
737
|
+
const f = flagSet(args);
|
|
738
|
+
const sub = (args.find((a) => !a.startsWith("-")) ?? "").toLowerCase();
|
|
739
|
+
if (f.has("-g", "--global", "--location=global")) return part("high", `${pm} would change global (system-wide) packages`);
|
|
740
|
+
if (args.length === 0 || args.length === 1 && VERSION_ONLY.has(args[0])) return part("low", `${pm} prints its version or help`);
|
|
741
|
+
if (["ls", "list", "outdated", "view", "info", "why", "explain", "help", "root", "bin", "prefix", "doctor", "whoami"].includes(sub)) return part("low", `${pm} ${sub} only reads package information`, void 0);
|
|
742
|
+
if (["login", "adduser", "token", "access", "owner", "team", "logout", "profile", "hook", "set-script"].includes(sub)) return part("blocked", `${pm} ${sub} deals with account credentials`);
|
|
743
|
+
if (["publish", "unpublish", "deprecate", "dist-tag"].includes(sub)) return part("high", `${pm} ${sub} changes a public registry`);
|
|
744
|
+
if (["uninstall", "remove", "rm", "un", "prune", "unlink", "cache", "dedupe", "link", "config", "set", "exec", "x", "dlx", "create", "init", "patch", "patch-commit", "rebuild"].includes(sub)) return part("high", `${pm} ${sub} removes or reconfigures packages or runs downloaded code`);
|
|
745
|
+
if (["install", "i", "ci", "add", "update", "up", "upgrade", "audit", "fund", "pack", "clean-install", "install-test", "it"].includes(sub)) {
|
|
746
|
+
const url = args.some((a) => /^(https?:|git\+|github:|file:|git:|ssh:)/i.test(a));
|
|
747
|
+
return url ? part("high", `${pm} ${sub} would install from a URL or repository`) : part("medium", `${pm} ${sub} downloads packages and may run their install scripts`, "Install scripts of dependencies run on your machine.");
|
|
748
|
+
}
|
|
749
|
+
if (["test", "t", "tst", "run", "run-script", "rum", "urn", "start", "stop", "restart", "build", "dev", "lint", "typecheck", "format", "check", "watch", "serve", "preview"].includes(sub)) {
|
|
750
|
+
return part("medium", `${pm} ${sub} runs a script defined in package.json`, "The script's contents are not inspected here; open package.json to see what it does.");
|
|
751
|
+
}
|
|
752
|
+
if (sub === "") return part("medium", `${pm} runs with options only`);
|
|
753
|
+
return part("high", `${pm} ${sub} is not a subcommand zg recognises`);
|
|
754
|
+
}
|
|
755
|
+
function classifyInterpreter(base, args) {
|
|
756
|
+
const f = flagSet(args);
|
|
757
|
+
if (args.length === 0) return part("blocked", `${base} with no arguments opens an interactive prompt, which zg cannot drive`);
|
|
758
|
+
if (args.length === 1 && VERSION_ONLY.has(args[0])) return part("low", `${base} prints its version`);
|
|
759
|
+
if (base === "node" || base === "nodejs") {
|
|
760
|
+
if (f.has("-e", "--eval", "-p", "--print", "-r", "--require", "--import", "--loader", "--experimental-loader", "-i", "--interactive", "--inspect", "--inspect-brk")) return part("high", `${base} would run code from the command line or preload other code`, "Code passed on the command line is not inspected.");
|
|
761
|
+
} else {
|
|
762
|
+
if (f.has("-c") || f.chars("c")) return part("high", `${base} -c runs code from the command line`, "Code passed on the command line is not inspected.");
|
|
763
|
+
const m = args.indexOf("-m");
|
|
764
|
+
if (m >= 0) {
|
|
765
|
+
const mod = (args[m + 1] ?? "").toLowerCase();
|
|
766
|
+
if (["pytest", "unittest", "compileall", "mypy", "ruff", "black", "flake8", "pylint", "isort", "build"].includes(mod)) return part("medium", `${base} -m ${mod} runs a Python tool`, "Test and build tools run project code.");
|
|
767
|
+
if (mod === "pip") return classifyTooling("pip", args.slice(m + 2), false);
|
|
768
|
+
if (mod === "venv" || mod === "ensurepip") return part("medium", `${base} -m ${mod} creates files in the project`);
|
|
769
|
+
return part("high", `${base} -m ${mod || "(module)"} runs a module zg does not recognise`);
|
|
770
|
+
}
|
|
771
|
+
if (f.has("-i") || f.chars("i")) return part("high", `${base} -i would keep an interactive prompt open`);
|
|
772
|
+
}
|
|
773
|
+
const script = args.find((a) => !a.startsWith("-"));
|
|
774
|
+
return part("medium", `${base} runs ${script ?? "a script"}`, "The script's code is not inspected. It can read and change anything your user account can.");
|
|
775
|
+
}
|
|
776
|
+
function classifyTooling(base, args, onlyVersion) {
|
|
777
|
+
if (onlyVersion) return part("low", `${base} prints its version`);
|
|
778
|
+
const sub = (args.find((a) => !a.startsWith("-")) ?? "").toLowerCase();
|
|
779
|
+
const f = flagSet(args);
|
|
780
|
+
if (["pip", "pip3", "pipenv", "poetry", "uv"].includes(base)) {
|
|
781
|
+
if (["list", "show", "freeze", "check", "search", "--version", "help", "debug", "config"].includes(sub) && sub !== "config") return part("low", `${base} ${sub} reads package information`);
|
|
782
|
+
if (["uninstall", "remove", "cache", "purge", "publish", "lock"].includes(sub)) return part("high", `${base} ${sub} removes packages or publishes`);
|
|
783
|
+
if (f.has("--user", "--break-system-packages", "--target") || args.some((a) => /^(https?:|git\+|file:)/i.test(a))) return part("high", `${base} would install outside the project or from a URL`);
|
|
784
|
+
return part("medium", `${base} ${sub || "runs"} installs packages and may run their setup code`, "Package setup code runs on your machine.");
|
|
785
|
+
}
|
|
786
|
+
if (base === "cargo") {
|
|
787
|
+
if (["install", "publish", "login", "owner", "yank", "uninstall", "cache"].includes(sub)) return part(sub === "login" ? "blocked" : "high", `cargo ${sub} installs globally, publishes or handles credentials`);
|
|
788
|
+
return part("medium", `cargo ${sub || "runs"} builds or tests the project`, "Build scripts and tests run project code.");
|
|
789
|
+
}
|
|
790
|
+
if (base === "go") {
|
|
791
|
+
if (["get", "install", "clean", "mod"].includes(sub)) return part("high", `go ${sub} downloads code or changes caches and modules`);
|
|
792
|
+
return part("medium", `go ${sub || "runs"} builds or tests the project`, "Tests and generators run project code.");
|
|
793
|
+
}
|
|
794
|
+
if (base === "composer" || base === "bundle" || base === "dotnet" || base === "mix" || base === "poetry") {
|
|
795
|
+
if (["require", "install", "update", "add", "restore", "remove", "publish", "global"].includes(sub)) return part("high", `${base} ${sub} downloads or removes dependencies`);
|
|
796
|
+
}
|
|
797
|
+
if (["make", "cmake", "ninja", "gradle", "gradlew", "mvn", "mvnw", "sbt", "rake"].includes(base)) return part("medium", `${base} runs the project's build rules`, "Build files can run any command; they are not inspected.");
|
|
798
|
+
return part("medium", `${base} ${sub} runs a development tool on the project`, "Development tools run project code and may write files (caches, build output).");
|
|
799
|
+
}
|
|
800
|
+
var PATHLIKE = /^(\/|\\|~|\.{1,2}([\\/]|$)|[A-Za-z]:[\\/]|file:)/;
|
|
801
|
+
var DOTDOT = /(^|[\\/])\.\.([\\/]|$)/;
|
|
802
|
+
async function checkPathArgs(args, cwdAbs, root, flavor) {
|
|
803
|
+
const reasons = [];
|
|
804
|
+
for (const raw of args) {
|
|
805
|
+
let value = raw;
|
|
806
|
+
if (value.startsWith("-")) {
|
|
807
|
+
const eq = value.indexOf("=");
|
|
808
|
+
if (eq < 0) continue;
|
|
809
|
+
value = value.slice(eq + 1);
|
|
810
|
+
}
|
|
811
|
+
if (value === "" || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) continue;
|
|
812
|
+
if (flavor === "windows" && /^\/[A-Za-z?]$/.test(value)) continue;
|
|
813
|
+
const looksPath = PATHLIKE.test(value) || DOTDOT.test(value);
|
|
814
|
+
const fileish = looksPath || /[\\/]/.test(value) || /^\.[^./\\]/.test(value) || /\.[A-Za-z0-9]{1,8}$/.test(value);
|
|
815
|
+
if (!fileish) {
|
|
816
|
+
try {
|
|
817
|
+
const real2 = await fsp2.realpath(path2.resolve(cwdAbs, value));
|
|
818
|
+
if (!isInside(root, real2)) reasons.push(`${shorten2(value)} leads outside the project folder through a symbolic link`);
|
|
819
|
+
} catch {
|
|
820
|
+
}
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
if (value.startsWith("~")) {
|
|
824
|
+
reasons.push(`${shorten2(value)} is in your home folder, outside the project`);
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
const abs = path2.resolve(cwdAbs, value);
|
|
828
|
+
if (!isInside(root, abs)) {
|
|
829
|
+
if (looksPath) reasons.push(`${shorten2(value)} is outside the project folder`);
|
|
830
|
+
continue;
|
|
831
|
+
}
|
|
832
|
+
let real = abs;
|
|
833
|
+
try {
|
|
834
|
+
real = await fsp2.realpath(abs);
|
|
835
|
+
} catch {
|
|
836
|
+
}
|
|
837
|
+
if (!isInside(root, real)) {
|
|
838
|
+
reasons.push(`${shorten2(value)} leads outside the project folder through a symbolic link`);
|
|
839
|
+
continue;
|
|
840
|
+
}
|
|
841
|
+
for (const candidate of /* @__PURE__ */ new Set([abs, real])) {
|
|
842
|
+
const sens = sensitiveReason(path2.relative(root, candidate).split(path2.sep).join("/"));
|
|
843
|
+
if (sens) {
|
|
844
|
+
reasons.push(`${shorten2(value)} is ${sens}`);
|
|
845
|
+
break;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
return reasons;
|
|
850
|
+
}
|
|
851
|
+
function shorten2(s) {
|
|
852
|
+
return s.length > 60 ? `${s.slice(0, 57)}...` : s;
|
|
853
|
+
}
|
|
854
|
+
async function assessCommand(input) {
|
|
855
|
+
const extra = new Set(input.settings.extraBlockedPrograms.map((p) => p.toLowerCase()));
|
|
856
|
+
const parts = [];
|
|
857
|
+
const programs = [];
|
|
858
|
+
const blockedReasons = [...input.parserBlocked ?? []];
|
|
859
|
+
let usesShell = false;
|
|
860
|
+
const warnings = [...input.warnings ?? []];
|
|
861
|
+
const segments = [];
|
|
862
|
+
if (input.spec.kind === "direct") {
|
|
863
|
+
segments.push({ tokens: [input.spec.program, ...input.spec.args], redirects: [] });
|
|
864
|
+
} else {
|
|
865
|
+
usesShell = true;
|
|
866
|
+
const a = analyzeShellLine(input.spec.line, input.flavor);
|
|
867
|
+
blockedReasons.push(...a.blocked.filter((b) => !blockedReasons.includes(b)));
|
|
868
|
+
warnings.push(...a.warnings);
|
|
869
|
+
segments.push(...a.segments);
|
|
870
|
+
if (a.segments.length > 1) warnings.push(`Runs ${a.segments.length} commands in one go (${a.operators.filter((o) => o !== "newline").join(" ") || "newline"}): ${a.segments.map((s) => s.tokens[0] ?? "?").join(", ")}.`);
|
|
871
|
+
}
|
|
872
|
+
for (const seg of segments) {
|
|
873
|
+
const program = seg.tokens[0];
|
|
874
|
+
if (program === void 0) {
|
|
875
|
+
blockedReasons.push("a command in the line has no program");
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
programs.push(baseOf(program));
|
|
879
|
+
parts.push(classifyProgram(program, seg.tokens.slice(1), extra));
|
|
880
|
+
blockedReasons.push(...await checkPathArgs(seg.tokens.slice(1), input.cwdAbs, input.root, input.flavor));
|
|
881
|
+
if (/[\\/]/.test(program)) blockedReasons.push(...await checkPathArgs([program], input.cwdAbs, input.root, input.flavor));
|
|
882
|
+
for (const r of seg.redirects) {
|
|
883
|
+
if (r.op === "dup") continue;
|
|
884
|
+
if (r.op.startsWith(">")) parts.push(part("high", `redirects output into ${shorten2(r.target)}, overwriting or extending a file`, "Redirected writes are not shown as a diff and are not backed up."));
|
|
885
|
+
blockedReasons.push(...await checkPathArgs([r.target.startsWith("-") ? `./${r.target}` : r.target.includes("/") || r.target.includes("\\") || PATHLIKE.test(r.target) ? r.target : `./${r.target}`], input.cwdAbs, input.root, input.flavor));
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
if (input.spec.kind === "shell") {
|
|
889
|
+
const a = analyzeShellLine(input.spec.line, input.flavor);
|
|
890
|
+
for (const [i, seg] of segments.entries()) {
|
|
891
|
+
if (i === 0 || a.operators[i - 1] !== "|") continue;
|
|
892
|
+
const b = baseOf(seg.tokens[0] ?? "");
|
|
893
|
+
if (["sh", "bash", "zsh", "dash", "ksh", "fish", "powershell", "pwsh", "cmd", "python", "python3", "node", "perl", "ruby", "php"].includes(b)) blockedReasons.push(`output is piped into ${b}, which would run it as code`);
|
|
894
|
+
}
|
|
895
|
+
parts.push(part("high", "uses shell syntax (pipes, chains or redirects) that is interpreted by a shell", "Shell mode is the riskiest way to run a command: a shell reads the whole line."));
|
|
896
|
+
}
|
|
897
|
+
let risk = "low";
|
|
898
|
+
const reasons = [];
|
|
899
|
+
for (const p of parts) {
|
|
900
|
+
risk = maxRisk(risk, p.risk);
|
|
901
|
+
reasons.push(...p.reasons);
|
|
902
|
+
warnings.push(...p.warnings);
|
|
903
|
+
}
|
|
904
|
+
if (blockedReasons.length > 0) {
|
|
905
|
+
risk = "blocked";
|
|
906
|
+
reasons.unshift(...blockedReasons);
|
|
907
|
+
}
|
|
908
|
+
const uniq = (xs) => [...new Set(xs)];
|
|
909
|
+
const needsConfirm = risk !== "blocked" && (risk === "high" || usesShell || risk === "medium" && input.settings.confirmMedium);
|
|
910
|
+
return { risk, reasons: uniq(reasons), warnings: uniq(warnings), needsConfirm, usesShell, programs: uniq(programs) };
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// src/execution/executable-resolver.ts
|
|
914
|
+
import { constants, promises as fsp3 } from "fs";
|
|
915
|
+
import path3 from "path";
|
|
916
|
+
var DEFAULT_PATHEXT = [".COM", ".EXE", ".BAT", ".CMD"];
|
|
917
|
+
async function isFile(p, windows) {
|
|
918
|
+
try {
|
|
919
|
+
const st = await fsp3.stat(p);
|
|
920
|
+
if (!st.isFile()) return false;
|
|
921
|
+
if (!windows) await fsp3.access(p, constants.X_OK);
|
|
922
|
+
return true;
|
|
923
|
+
} catch {
|
|
924
|
+
return false;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
function candidates(dir, name, windows, pathext) {
|
|
928
|
+
if (!windows) return [path3.join(dir, name)];
|
|
929
|
+
const hasExt = pathext.some((e) => name.toUpperCase().endsWith(e));
|
|
930
|
+
return hasExt ? [path3.join(dir, name)] : pathext.map((e) => path3.join(dir, name + e.toLowerCase()));
|
|
931
|
+
}
|
|
932
|
+
async function resolveExecutable(input) {
|
|
933
|
+
const { program, windows } = input;
|
|
934
|
+
const pathext = (input.env["PATHEXT"] ?? input.env["Pathext"] ?? DEFAULT_PATHEXT.join(";")).split(";").filter(Boolean).map((e) => e.toUpperCase());
|
|
935
|
+
const cmdLike = (f) => windows && /\.(cmd|bat)$/i.test(f);
|
|
936
|
+
if (/[\\/]/.test(program)) {
|
|
937
|
+
if (path3.isAbsolute(program) || /^[A-Za-z]:/.test(program)) throw new ExecutionError("invalid-command", 'Programs must be named (for example "node") or be inside the project (for example ./script.sh), not given as absolute paths.');
|
|
938
|
+
const abs = path3.resolve(input.cwdAbs, program);
|
|
939
|
+
for (const c of candidates(path3.dirname(abs), path3.basename(abs), windows, pathext)) {
|
|
940
|
+
if (!await isFile(c, windows)) continue;
|
|
941
|
+
const real = await fsp3.realpath(c);
|
|
942
|
+
if (!isInside(input.root, real)) throw new ExecutionError("outside-workspace", `${program} resolves outside the project folder.`);
|
|
943
|
+
return { file: real, cmdScript: cmdLike(real) };
|
|
944
|
+
}
|
|
945
|
+
throw new ExecutionError("not-found", `${program} was not found or is not executable.`, windows ? void 0 : "Check the file exists and has execute permission (chmod +x).");
|
|
946
|
+
}
|
|
947
|
+
const entries = (input.env[windows ? "PATH" : "PATH"] ?? input.env["Path"] ?? "").split(path3.delimiter).filter((e) => e !== "");
|
|
948
|
+
for (const dir of entries) {
|
|
949
|
+
if (!path3.isAbsolute(dir)) continue;
|
|
950
|
+
let realDir;
|
|
951
|
+
try {
|
|
952
|
+
realDir = await fsp3.realpath(dir);
|
|
953
|
+
} catch {
|
|
954
|
+
continue;
|
|
955
|
+
}
|
|
956
|
+
if (isInside(input.root, realDir)) continue;
|
|
957
|
+
for (const c of candidates(realDir, program, windows, pathext)) {
|
|
958
|
+
if (await isFile(c, windows)) return { file: c, cmdScript: cmdLike(c) };
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
const builtin = windows && ["dir", "type", "echo", "copy", "del", "move", "ren", "md", "mkdir", "rd", "cd", "set", "cls", "ver", "vol"].includes(program.toLowerCase());
|
|
962
|
+
throw new ExecutionError("not-found", `"${program}" was not found on PATH.`, builtin ? `${program} is a cmd.exe built-in, not a program. Use a program instead, or enable shell mode (execution.shell).` : "Check that it is installed and that PATH includes it. zg does not install programs.");
|
|
963
|
+
}
|
|
964
|
+
var CMD_UNSAFE = /["%^&|<>!\r\n\0]/;
|
|
965
|
+
function cmdScriptInvocation(file, args) {
|
|
966
|
+
for (const a of [file, ...args]) {
|
|
967
|
+
if (CMD_UNSAFE.test(a)) throw new ExecutionError("unsafe-argument", "An argument contains characters that cmd.exe would interpret (such as & | < > ^ % ! or a quote), so it cannot be passed to a .cmd or .bat program safely.", "Use a different argument, or run the program as an .exe.");
|
|
968
|
+
if (/\\$/.test(a)) throw new ExecutionError("unsafe-argument", "An argument ends with a backslash, which cannot be quoted safely for cmd.exe.");
|
|
969
|
+
}
|
|
970
|
+
const quote = (s) => /[\s()]/.test(s) || s === "" ? `"${s}"` : s;
|
|
971
|
+
return ["/d", "/s", "/c", `"${[quote(file), ...args.map(quote)].join(" ")}"`];
|
|
972
|
+
}
|
|
973
|
+
async function resolveShell(input) {
|
|
974
|
+
if (input.windows) {
|
|
975
|
+
const sysRoot = input.env["SystemRoot"] ?? input.env["SYSTEMROOT"];
|
|
976
|
+
const comspec = input.env["ComSpec"] ?? input.env["COMSPEC"];
|
|
977
|
+
const cands = [comspec, sysRoot ? path3.join(sysRoot, "System32", "cmd.exe") : void 0].filter((x) => typeof x === "string" && path3.isAbsolute(x) && /cmd\.exe$/i.test(x));
|
|
978
|
+
for (const c of cands) if (await isFile(c, true)) return { file: c, leading: ["/d", "/s", "/c"], verbatim: true };
|
|
979
|
+
throw new ExecutionError("unsupported-platform", "cmd.exe could not be found, so shell mode is unavailable.");
|
|
980
|
+
}
|
|
981
|
+
const found = await resolveExecutable({ program: "sh", cwdAbs: input.root, root: input.root, env: input.env, windows: false });
|
|
982
|
+
return { file: found.file, leading: ["-c"], verbatim: false };
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
// src/execution/execution-env.ts
|
|
986
|
+
var BASE_ALLOW = [
|
|
987
|
+
"PATH",
|
|
988
|
+
"HOME",
|
|
989
|
+
"USERPROFILE",
|
|
990
|
+
"LANG",
|
|
991
|
+
"LANGUAGE",
|
|
992
|
+
"LC_ALL",
|
|
993
|
+
"LC_CTYPE",
|
|
994
|
+
"LC_MESSAGES",
|
|
995
|
+
"TERM",
|
|
996
|
+
"TZ",
|
|
997
|
+
"NO_COLOR",
|
|
998
|
+
"TMPDIR",
|
|
999
|
+
"TEMP",
|
|
1000
|
+
"TMP",
|
|
1001
|
+
// Windows needs these for programs to start at all.
|
|
1002
|
+
"SYSTEMROOT",
|
|
1003
|
+
"SYSTEMDRIVE",
|
|
1004
|
+
"COMSPEC",
|
|
1005
|
+
"PATHEXT",
|
|
1006
|
+
"WINDIR",
|
|
1007
|
+
"APPDATA",
|
|
1008
|
+
"LOCALAPPDATA",
|
|
1009
|
+
"PROGRAMFILES",
|
|
1010
|
+
"PROGRAMFILES(X86)",
|
|
1011
|
+
"PROGRAMDATA",
|
|
1012
|
+
"USERNAME",
|
|
1013
|
+
"OS",
|
|
1014
|
+
"PROCESSOR_ARCHITECTURE",
|
|
1015
|
+
"NUMBER_OF_PROCESSORS",
|
|
1016
|
+
// Termux and Android.
|
|
1017
|
+
"PREFIX",
|
|
1018
|
+
"ANDROID_ROOT",
|
|
1019
|
+
"ANDROID_DATA",
|
|
1020
|
+
"TERMUX_VERSION",
|
|
1021
|
+
"XDG_CACHE_HOME",
|
|
1022
|
+
"XDG_CONFIG_HOME",
|
|
1023
|
+
"XDG_DATA_HOME",
|
|
1024
|
+
"XDG_RUNTIME_DIR"
|
|
1025
|
+
];
|
|
1026
|
+
function buildChildEnv(parent, opts) {
|
|
1027
|
+
const norm = (n) => opts.windows ? n.toUpperCase() : n;
|
|
1028
|
+
const denied = new Set([...NEVER_PASS_ENV, ...(opts.denyNames ?? []).filter((x) => typeof x === "string")].map(norm));
|
|
1029
|
+
const allowed = new Set([...BASE_ALLOW, ...opts.allowlist].map(norm));
|
|
1030
|
+
const env = {};
|
|
1031
|
+
const passed = [];
|
|
1032
|
+
for (const [name, value] of Object.entries(parent)) {
|
|
1033
|
+
if (value === void 0) continue;
|
|
1034
|
+
const key = norm(name);
|
|
1035
|
+
if (!allowed.has(key) || denied.has(key) || /^ZG_/.test(key)) continue;
|
|
1036
|
+
if (!BASE_ALLOW.map(norm).includes(key) && /(api[-_]?key|secret|token|passw(or)?d|credential|auth|private)/i.test(name)) continue;
|
|
1037
|
+
env[name] = value;
|
|
1038
|
+
passed.push(name);
|
|
1039
|
+
}
|
|
1040
|
+
return { env, passed: passed.sort() };
|
|
1041
|
+
}
|
|
1042
|
+
function secretValuesToHide(parent, extraNames) {
|
|
1043
|
+
const names = [...NEVER_PASS_ENV, ...extraNames.filter((x) => typeof x === "string")];
|
|
1044
|
+
const out = [];
|
|
1045
|
+
for (const n of names) {
|
|
1046
|
+
const v = parent[n];
|
|
1047
|
+
if (typeof v === "string" && v.length >= 8) out.push(v);
|
|
1048
|
+
}
|
|
1049
|
+
return out;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// src/execution/command-validator.ts
|
|
1053
|
+
var CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
|
|
1054
|
+
function structural(req) {
|
|
1055
|
+
if (req.spec.kind === "direct") {
|
|
1056
|
+
const { program, args } = req.spec;
|
|
1057
|
+
if (program.trim() === "" || /[\s|&;<>$`()'"*?{}]/.test(program)) throw new ExecutionError("invalid-command", 'The program name must be a single word such as "npm". Put the arguments in the argument list.');
|
|
1058
|
+
if (CONTROL.test(program) || args.some((a) => CONTROL.test(a))) throw new ExecutionError("invalid-command", "The command contains control characters.");
|
|
1059
|
+
if (args.length > 100 || args.some((a) => a.length > 2e3)) throw new ExecutionError("invalid-command", "The command has too many or too long arguments.");
|
|
1060
|
+
} else if (CONTROL.test(req.spec.line.replace(/\n/g, "")) || req.spec.line.length > 2e3) {
|
|
1061
|
+
throw new ExecutionError("invalid-command", "The command line contains control characters or is too long.");
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
async function prepareCommand(deps, request) {
|
|
1065
|
+
const settings = deps.settings();
|
|
1066
|
+
if (settings.permission === "deny") throw new ExecutionError("denied", "Running commands is turned off (execution.permission is deny).");
|
|
1067
|
+
structural(request);
|
|
1068
|
+
if (request.spec.kind === "shell" && settings.shell === "deny") {
|
|
1069
|
+
throw new ExecutionError("shell-denied", "This command needs a shell (pipes, chains or redirects), and shell mode is off.", "Use a single program with arguments, or turn it on with: zg config set execution.shell ask");
|
|
1070
|
+
}
|
|
1071
|
+
const cwdInput = request.cwd.trim() === "" ? settings.defaultCwd : request.cwd;
|
|
1072
|
+
let cwdRel;
|
|
1073
|
+
let cwdAbs;
|
|
1074
|
+
try {
|
|
1075
|
+
const r = await deps.validator.resolveExisting(cwdInput, { allowRoot: true });
|
|
1076
|
+
cwdRel = r.rel === "" ? "." : r.rel;
|
|
1077
|
+
cwdAbs = r.abs;
|
|
1078
|
+
if (!(await fsp4.stat(cwdAbs)).isDirectory()) throw new ExecutionError("invalid-command", `${cwdRel} is not a folder.`);
|
|
1079
|
+
} catch (err) {
|
|
1080
|
+
if (err instanceof ExecutionError) throw err;
|
|
1081
|
+
if (err instanceof FsError) throw new ExecutionError(err.code === "outside-workspace" || err.code === "symlink" ? "outside-workspace" : "invalid-command", `Working folder: ${err.message}`, err.hint);
|
|
1082
|
+
throw new ExecutionError("invalid-command", "The working folder could not be checked.");
|
|
1083
|
+
}
|
|
1084
|
+
const assessment = await assessCommand({
|
|
1085
|
+
spec: request.spec,
|
|
1086
|
+
cwdAbs,
|
|
1087
|
+
root: deps.validator.root,
|
|
1088
|
+
flavor: deps.flavor,
|
|
1089
|
+
settings,
|
|
1090
|
+
...deps.warnings ? { warnings: deps.warnings } : {},
|
|
1091
|
+
...deps.parserBlocked ? { parserBlocked: deps.parserBlocked } : {}
|
|
1092
|
+
});
|
|
1093
|
+
let executable = null;
|
|
1094
|
+
let shell = null;
|
|
1095
|
+
if (assessment.risk !== "blocked") {
|
|
1096
|
+
const childEnv = buildChildEnv(deps.env, { windows: deps.windows, allowlist: settings.envAllowlist, denyNames: [deps.customEnvVar()] }).env;
|
|
1097
|
+
if (request.spec.kind === "direct") executable = await resolveExecutable({ program: request.spec.program, cwdAbs, root: deps.validator.root, env: childEnv, windows: deps.windows });
|
|
1098
|
+
else shell = await resolveShell({ env: deps.env, windows: deps.windows, root: deps.validator.root });
|
|
1099
|
+
}
|
|
1100
|
+
const timeoutSeconds = Math.min(request.timeoutSeconds ?? settings.timeoutSeconds, settings.timeoutSeconds);
|
|
1101
|
+
const fingerprint = createHash("sha256").update(JSON.stringify({ spec: request.spec, cwd: cwdAbs, exe: executable?.file ?? shell?.file ?? null })).digest("hex");
|
|
1102
|
+
return {
|
|
1103
|
+
id: `cmd-${Date.now().toString(36)}-${randomBytes(3).toString("hex")}`,
|
|
1104
|
+
request,
|
|
1105
|
+
display: displayCommand(request.spec),
|
|
1106
|
+
cwdRel,
|
|
1107
|
+
cwdAbs,
|
|
1108
|
+
assessment,
|
|
1109
|
+
executable,
|
|
1110
|
+
shell,
|
|
1111
|
+
timeoutSeconds,
|
|
1112
|
+
fingerprint,
|
|
1113
|
+
createdAt: Date.now()
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
// src/execution/process-manager.ts
|
|
1118
|
+
import { spawn as spawn2 } from "child_process";
|
|
1119
|
+
|
|
1120
|
+
// src/execution/cancellation.ts
|
|
1121
|
+
import { spawn } from "child_process";
|
|
1122
|
+
import path4 from "path";
|
|
1123
|
+
function taskkillArgs(pid, force) {
|
|
1124
|
+
return ["/pid", String(pid), "/t", ...force ? ["/f"] : []];
|
|
1125
|
+
}
|
|
1126
|
+
function defaultSignalGroup(pid, signal) {
|
|
1127
|
+
try {
|
|
1128
|
+
process.kill(-pid, signal);
|
|
1129
|
+
return true;
|
|
1130
|
+
} catch (err) {
|
|
1131
|
+
return err.code === "EPERM";
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
function defaultTaskkill(env) {
|
|
1135
|
+
const root = env["SystemRoot"] ?? env["SYSTEMROOT"];
|
|
1136
|
+
const exe = root ? path4.join(root, "System32", "taskkill.exe") : "taskkill.exe";
|
|
1137
|
+
return (args) => new Promise((resolve) => {
|
|
1138
|
+
try {
|
|
1139
|
+
const c = spawn(exe, args, { stdio: "ignore", windowsHide: true, shell: false });
|
|
1140
|
+
c.once("error", () => resolve());
|
|
1141
|
+
c.once("close", () => resolve());
|
|
1142
|
+
} catch {
|
|
1143
|
+
resolve();
|
|
1144
|
+
}
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1148
|
+
var pause = (child) => child.exited() ? sleep(50) : child.waitForExit(50);
|
|
1149
|
+
async function terminateTree(child, opts) {
|
|
1150
|
+
const pid = child.pid;
|
|
1151
|
+
if (pid === void 0) return child.exited() ? "graceful" : "failed";
|
|
1152
|
+
if (opts.windows) {
|
|
1153
|
+
const kill = opts.runTaskkill ?? defaultTaskkill(opts.env);
|
|
1154
|
+
await kill(taskkillArgs(pid, false));
|
|
1155
|
+
if (await child.waitForExit(opts.graceMs)) return "graceful";
|
|
1156
|
+
await kill(taskkillArgs(pid, true));
|
|
1157
|
+
return await child.waitForExit(2e3) ? "forced" : "failed";
|
|
1158
|
+
}
|
|
1159
|
+
const signal = opts.signalGroup ?? defaultSignalGroup;
|
|
1160
|
+
const groupAlive = () => signal(pid, 0);
|
|
1161
|
+
if (!child.exited() || groupAlive()) signal(pid, "SIGTERM");
|
|
1162
|
+
const deadline = Date.now() + opts.graceMs;
|
|
1163
|
+
while (Date.now() < deadline) {
|
|
1164
|
+
if (child.exited() && !groupAlive()) return "graceful";
|
|
1165
|
+
await pause(child);
|
|
1166
|
+
}
|
|
1167
|
+
if (child.exited() && !groupAlive()) return "graceful";
|
|
1168
|
+
signal(pid, "SIGKILL");
|
|
1169
|
+
const end = Date.now() + 2e3;
|
|
1170
|
+
while (Date.now() < end) {
|
|
1171
|
+
if (child.exited() && !groupAlive()) return "forced";
|
|
1172
|
+
await pause(child);
|
|
1173
|
+
}
|
|
1174
|
+
return "failed";
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// src/execution/process-manager.ts
|
|
1178
|
+
var ProcessManager = class {
|
|
1179
|
+
#active = /* @__PURE__ */ new Map();
|
|
1180
|
+
#used = /* @__PURE__ */ new Set();
|
|
1181
|
+
#max;
|
|
1182
|
+
#spawn;
|
|
1183
|
+
constructor(opts) {
|
|
1184
|
+
this.#max = opts.maxConcurrent;
|
|
1185
|
+
this.#spawn = opts.spawnFn ?? spawn2;
|
|
1186
|
+
}
|
|
1187
|
+
active() {
|
|
1188
|
+
return [...this.#active.values()].map((a) => ({ ...a.info }));
|
|
1189
|
+
}
|
|
1190
|
+
/** Ask a running operation to stop. Returns false when nothing with that id (or nothing at all) is running. */
|
|
1191
|
+
cancel(id) {
|
|
1192
|
+
const targets = id === void 0 ? [...this.#active.values()] : this.#active.has(id) ? [this.#active.get(id)] : [];
|
|
1193
|
+
for (const t of targets) t.cancel();
|
|
1194
|
+
return targets.length > 0;
|
|
1195
|
+
}
|
|
1196
|
+
async run(id, plan, opts) {
|
|
1197
|
+
if (this.#used.has(id)) throw new ExecutionError("duplicate", "This command was already started. It will not be run a second time.", "Ask for a new proposal if you want to run it again.");
|
|
1198
|
+
if (this.#active.size >= this.#max()) throw new ExecutionError("too-many-processes", `The limit of ${this.#max()} running command(s) is reached.`, "Wait for it to finish or cancel it.");
|
|
1199
|
+
this.#used.add(id);
|
|
1200
|
+
const startedAt = Date.now();
|
|
1201
|
+
const info = { id, pid: void 0, startedAt, state: "starting" };
|
|
1202
|
+
let child;
|
|
1203
|
+
try {
|
|
1204
|
+
child = this.#spawn(plan.file, plan.args, {
|
|
1205
|
+
cwd: plan.cwd,
|
|
1206
|
+
env: plan.env,
|
|
1207
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1208
|
+
shell: false,
|
|
1209
|
+
windowsHide: true,
|
|
1210
|
+
detached: !opts.windows,
|
|
1211
|
+
...plan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
|
|
1212
|
+
});
|
|
1213
|
+
} catch (err) {
|
|
1214
|
+
return { status: "spawn-error", exitCode: null, signal: null, durationMs: Date.now() - startedAt, spawnError: classifySpawn(err) };
|
|
1215
|
+
}
|
|
1216
|
+
info.pid = child.pid;
|
|
1217
|
+
let exited = false;
|
|
1218
|
+
let exitCode = null;
|
|
1219
|
+
let exitSignal = null;
|
|
1220
|
+
let spawnErr;
|
|
1221
|
+
const exitWaiters = [];
|
|
1222
|
+
const markExit = () => {
|
|
1223
|
+
exited = true;
|
|
1224
|
+
for (const w of exitWaiters.splice(0)) w();
|
|
1225
|
+
};
|
|
1226
|
+
const waitForExit = (ms) => exited ? Promise.resolve(true) : new Promise((resolve) => {
|
|
1227
|
+
const t = setTimeout(() => resolve(exited), ms);
|
|
1228
|
+
exitWaiters.push(() => {
|
|
1229
|
+
clearTimeout(t);
|
|
1230
|
+
resolve(true);
|
|
1231
|
+
});
|
|
1232
|
+
});
|
|
1233
|
+
let closed;
|
|
1234
|
+
const closedP = new Promise((r) => closed = r);
|
|
1235
|
+
child.stdout?.on("data", (b) => opts.collector.push("stdout", b));
|
|
1236
|
+
child.stderr?.on("data", (b) => opts.collector.push("stderr", b));
|
|
1237
|
+
child.once("error", (err) => {
|
|
1238
|
+
if (child.pid === void 0) spawnErr = classifySpawn(err);
|
|
1239
|
+
markExit();
|
|
1240
|
+
closed();
|
|
1241
|
+
});
|
|
1242
|
+
child.once("exit", (code, signal) => {
|
|
1243
|
+
exitCode = code;
|
|
1244
|
+
exitSignal = signal;
|
|
1245
|
+
markExit();
|
|
1246
|
+
});
|
|
1247
|
+
child.once("close", () => {
|
|
1248
|
+
markExit();
|
|
1249
|
+
closed();
|
|
1250
|
+
});
|
|
1251
|
+
let reason = null;
|
|
1252
|
+
let termination;
|
|
1253
|
+
let stopping = null;
|
|
1254
|
+
const stop = (why) => {
|
|
1255
|
+
if (reason !== null) return;
|
|
1256
|
+
reason = why;
|
|
1257
|
+
info.state = "stopping";
|
|
1258
|
+
stopping = terminateTree({ pid: child.pid, exited: () => exited, waitForExit }, { windows: opts.windows, graceMs: opts.graceMs, env: opts.parentEnv }).then((t) => {
|
|
1259
|
+
termination = t;
|
|
1260
|
+
child.stdout?.destroy();
|
|
1261
|
+
child.stderr?.destroy();
|
|
1262
|
+
markExit();
|
|
1263
|
+
closed();
|
|
1264
|
+
});
|
|
1265
|
+
};
|
|
1266
|
+
this.#active.set(id, { info, cancel: () => stop("cancel") });
|
|
1267
|
+
info.state = "running";
|
|
1268
|
+
const timer = setTimeout(() => stop("timeout"), opts.timeoutMs);
|
|
1269
|
+
const onAbort = () => stop("cancel");
|
|
1270
|
+
if (opts.signal?.aborted) stop("cancel");
|
|
1271
|
+
else opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1272
|
+
const beat = opts.onHeartbeat ? setInterval(() => opts.onHeartbeat?.(Date.now() - startedAt), opts.heartbeatMs ?? 1e4) : null;
|
|
1273
|
+
const idle = setInterval(() => opts.collector.flush(), 400);
|
|
1274
|
+
try {
|
|
1275
|
+
await closedP;
|
|
1276
|
+
if (stopping) await stopping;
|
|
1277
|
+
} finally {
|
|
1278
|
+
clearTimeout(timer);
|
|
1279
|
+
if (beat) clearInterval(beat);
|
|
1280
|
+
clearInterval(idle);
|
|
1281
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
1282
|
+
this.#active.delete(id);
|
|
1283
|
+
opts.collector.end();
|
|
1284
|
+
}
|
|
1285
|
+
const durationMs = Date.now() - startedAt;
|
|
1286
|
+
if (spawnErr) return { status: "spawn-error", exitCode: null, signal: null, durationMs, spawnError: spawnErr };
|
|
1287
|
+
if (reason === "timeout") return { status: "timed-out", exitCode, signal: exitSignal, durationMs, ...termination ? { termination } : {} };
|
|
1288
|
+
if (reason === "cancel") return { status: "cancelled", exitCode, signal: exitSignal, durationMs, ...termination ? { termination } : {} };
|
|
1289
|
+
return { status: exitCode === 0 ? "completed" : "failed", exitCode, signal: exitSignal, durationMs };
|
|
1290
|
+
}
|
|
1291
|
+
};
|
|
1292
|
+
function classifySpawn(err) {
|
|
1293
|
+
const code = err.code;
|
|
1294
|
+
if (code === "ENOENT") return { kind: "not-found", message: "The program could not be found when it was started." };
|
|
1295
|
+
if (code === "EACCES" || code === "EPERM") return { kind: "permission", message: "The system refused to run the program (permission denied)." };
|
|
1296
|
+
if (code === "EINVAL") return { kind: "other", message: "The system rejected the command (invalid arguments for this platform)." };
|
|
1297
|
+
return { kind: "other", message: "The program could not be started." };
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
// src/execution/command-engine.ts
|
|
1301
|
+
var ALLOWED_EXTRA_ENV = /^(GIT_CONFIG_COUNT|GIT_CONFIG_(KEY|VALUE)_\d{1,2}|GIT_OPTIONAL_LOCKS|GIT_TERMINAL_PROMPT|GIT_LITERAL_PATHSPECS|LC_ALL)$/;
|
|
1302
|
+
function checkedExtraEnv(extra) {
|
|
1303
|
+
const out = {};
|
|
1304
|
+
for (const [k, v] of Object.entries(extra ?? {})) {
|
|
1305
|
+
if (!ALLOWED_EXTRA_ENV.test(k) || typeof v !== "string" || v.length > 500 || v.includes("\0")) throw new ExecutionError("invalid-command", `The environment variable ${k} cannot be set for a command.`);
|
|
1306
|
+
out[k] = v;
|
|
1307
|
+
}
|
|
1308
|
+
return out;
|
|
1309
|
+
}
|
|
1310
|
+
var CommandEngine = class {
|
|
1311
|
+
session = new CommandSession();
|
|
1312
|
+
#d;
|
|
1313
|
+
#processes;
|
|
1314
|
+
#executed = /* @__PURE__ */ new Set();
|
|
1315
|
+
#security = null;
|
|
1316
|
+
constructor(deps) {
|
|
1317
|
+
this.#d = deps;
|
|
1318
|
+
this.#processes = deps.processes ?? new ProcessManager({ maxConcurrent: () => deps.settings().maxConcurrent });
|
|
1319
|
+
}
|
|
1320
|
+
/** Attach the central security engine: every execute is then checked and audited right before the process starts. */
|
|
1321
|
+
setSecurity(guard) {
|
|
1322
|
+
this.#security = guard;
|
|
1323
|
+
}
|
|
1324
|
+
get flavor() {
|
|
1325
|
+
return this.#d.platform.os === "windows" ? "windows" : "posix";
|
|
1326
|
+
}
|
|
1327
|
+
/** Why commands cannot run at all right now, or null. */
|
|
1328
|
+
unavailable() {
|
|
1329
|
+
if (this.#d.platform.os === "other") return "Command execution is not supported on this operating system (zg supports Linux, macOS, Windows and Android/Termux).";
|
|
1330
|
+
if (this.#d.settings().permission === "deny") return "Running commands is turned off (execution.permission is deny).";
|
|
1331
|
+
if (this.#d.approvalMode() === "read-only") return "Your approval mode is read-only, which does not allow running commands.";
|
|
1332
|
+
return null;
|
|
1333
|
+
}
|
|
1334
|
+
/** Parse text the user typed and prepare it. */
|
|
1335
|
+
async prepareTyped(line, cwd = "") {
|
|
1336
|
+
const parsed = parseUserCommand(line, this.flavor);
|
|
1337
|
+
if (!parsed.ok) throw new ExecutionError("invalid-command", parsed.error);
|
|
1338
|
+
return this.prepare({ spec: parsed.spec, cwd, purpose: "Typed by you", expectedEffect: "As written", source: "typed" }, parsed.warnings, parsed.blocked);
|
|
1339
|
+
}
|
|
1340
|
+
/** Prepare a read-only Git inspection: it works in every approval mode, because it cannot change anything. */
|
|
1341
|
+
async prepareRead(request) {
|
|
1342
|
+
if (this.#d.platform.os === "other") throw new ExecutionError("unsupported-platform", "Command execution is not supported on this operating system.");
|
|
1343
|
+
if (this.#d.settings().permission === "deny") throw new ExecutionError("denied", "Running commands is turned off (execution.permission is deny).");
|
|
1344
|
+
return prepareCommand(this.#validatorDeps(), request);
|
|
1345
|
+
}
|
|
1346
|
+
async prepare(request, warnings = [], parserBlocked = []) {
|
|
1347
|
+
const why = this.unavailable();
|
|
1348
|
+
if (why) throw new ExecutionError("denied", why);
|
|
1349
|
+
return prepareCommand(
|
|
1350
|
+
{
|
|
1351
|
+
validator: this.#d.validator,
|
|
1352
|
+
settings: this.#d.settings,
|
|
1353
|
+
flavor: this.flavor,
|
|
1354
|
+
windows: this.#d.platform.os === "windows",
|
|
1355
|
+
env: this.#d.env,
|
|
1356
|
+
customEnvVar: this.#d.customEnvVar ?? (() => null),
|
|
1357
|
+
warnings,
|
|
1358
|
+
parserBlocked
|
|
1359
|
+
},
|
|
1360
|
+
request
|
|
1361
|
+
);
|
|
1362
|
+
}
|
|
1363
|
+
active() {
|
|
1364
|
+
return this.#processes.active();
|
|
1365
|
+
}
|
|
1366
|
+
/** Stop what is running (graceful first). Returns whether anything was running. */
|
|
1367
|
+
cancelActive() {
|
|
1368
|
+
return this.#processes.cancel();
|
|
1369
|
+
}
|
|
1370
|
+
async execute(prepared, approval, opts = {}) {
|
|
1371
|
+
const why = this.unavailable();
|
|
1372
|
+
if (why) throw new ExecutionError("denied", why);
|
|
1373
|
+
if (approval.proposalId !== prepared.id) throw new ExecutionError("not-approved", "That approval belongs to a different command.");
|
|
1374
|
+
if (prepared.assessment.risk === "blocked") throw new ExecutionError("blocked", `This command is blocked and cannot be run: ${prepared.assessment.reasons[0] ?? "it is not allowed"}.`);
|
|
1375
|
+
if (prepared.assessment.needsConfirm && !approval.confirmed) throw new ExecutionError("not-approved", "This command needs the stronger confirmation (it is high risk or uses a shell).", "Review it, then approve with: confirm");
|
|
1376
|
+
if (this.#executed.has(prepared.id)) throw new ExecutionError("duplicate", "This command was already run. It will not be run a second time.");
|
|
1377
|
+
const fresh = await this.prepare(prepared.request);
|
|
1378
|
+
if (fresh.fingerprint !== prepared.fingerprint || fresh.assessment.risk === "blocked" || fresh.assessment.risk !== prepared.assessment.risk) {
|
|
1379
|
+
throw new ExecutionError("stale", "The project or the program changed since you reviewed this command, so it was not run.", "Ask for the command again to review it afresh.");
|
|
1380
|
+
}
|
|
1381
|
+
const decision = this.#security && prepared.request.source !== "git" ? await this.#security.authorize(commandRequest(prepared), { approved: true }) : null;
|
|
1382
|
+
this.#executed.add(prepared.id);
|
|
1383
|
+
if (!decision) return this.#start(prepared, opts, true);
|
|
1384
|
+
try {
|
|
1385
|
+
const res = await this.#start(prepared, opts, true);
|
|
1386
|
+
await this.#security?.complete(decision, "completed", `exit ${String(res.exitCode ?? "?")}`);
|
|
1387
|
+
return res;
|
|
1388
|
+
} catch (err) {
|
|
1389
|
+
await this.#security?.complete(decision, "failed", err instanceof Error ? err.message.slice(0, 120) : "failed");
|
|
1390
|
+
throw err;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Read-only Git inspection: the single place a command runs without a per-command approval. It accepts
|
|
1395
|
+
* only commands that the Git module prepared (source "git"), that run the git program directly and that
|
|
1396
|
+
* the risk policy rates LOW (it only reads repository data). Anything else needs `execute` and an approval.
|
|
1397
|
+
*/
|
|
1398
|
+
async executeReadOnly(prepared, opts = {}) {
|
|
1399
|
+
if (this.#d.platform.os === "other") throw new ExecutionError("unsupported-platform", "Command execution is not supported on this operating system.");
|
|
1400
|
+
if (this.#d.settings().permission === "deny") throw new ExecutionError("denied", "Running commands is turned off (execution.permission is deny).");
|
|
1401
|
+
const spec = prepared.request.spec;
|
|
1402
|
+
const program = spec.kind === "direct" ? spec.program.replace(/\.(exe|cmd|bat)$/i, "").toLowerCase() : "";
|
|
1403
|
+
if (prepared.request.source !== "git" || program !== "git") throw new ExecutionError("not-approved", "Only read-only Git inspection can run without approval.");
|
|
1404
|
+
if (prepared.assessment.risk !== "low" || prepared.assessment.needsConfirm || prepared.assessment.usesShell) throw new ExecutionError("not-approved", "Only low-risk, read-only commands can run without approval.");
|
|
1405
|
+
const fresh = await prepareCommand(this.#validatorDeps(), prepared.request);
|
|
1406
|
+
if (fresh.fingerprint !== prepared.fingerprint || fresh.assessment.risk !== "low") throw new ExecutionError("stale", "The project or the program changed, so the command was not run.");
|
|
1407
|
+
return this.#start(prepared, opts, false);
|
|
1408
|
+
}
|
|
1409
|
+
#validatorDeps() {
|
|
1410
|
+
return {
|
|
1411
|
+
validator: this.#d.validator,
|
|
1412
|
+
settings: this.#d.settings,
|
|
1413
|
+
flavor: this.flavor,
|
|
1414
|
+
windows: this.#d.platform.os === "windows",
|
|
1415
|
+
env: this.#d.env,
|
|
1416
|
+
customEnvVar: this.#d.customEnvVar ?? (() => null),
|
|
1417
|
+
warnings: [],
|
|
1418
|
+
parserBlocked: []
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
async #start(prepared, opts, record) {
|
|
1422
|
+
const settings = this.#d.settings();
|
|
1423
|
+
const win = this.#d.platform.os === "windows";
|
|
1424
|
+
const customVar = this.#d.customEnvVar?.() ?? null;
|
|
1425
|
+
const childEnv = { ...buildChildEnv(this.#d.env, { windows: win, allowlist: settings.envAllowlist, denyNames: [customVar] }).env, ...checkedExtraEnv(opts.extraEnv) };
|
|
1426
|
+
const plan = this.#plan(prepared, childEnv, win);
|
|
1427
|
+
const hidden = secretValuesToHide(this.#d.env, [customVar]);
|
|
1428
|
+
const maxBytes = opts.maxOutputBytes ?? settings.maxOutputBytes;
|
|
1429
|
+
const raw = opts.rawStdout === true ? new RawStdoutCollector({ maxBytes, hidden }) : null;
|
|
1430
|
+
const collector = raw ?? new OutputCollector({ maxBytes, hidden, ...opts.onOutput ? { onLine: opts.onOutput } : {} });
|
|
1431
|
+
const startedAt = (this.#d.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
1432
|
+
opts.onStart?.(prepared);
|
|
1433
|
+
const run = await this.#processes.run(prepared.id, plan, {
|
|
1434
|
+
timeoutMs: prepared.timeoutSeconds * 1e3,
|
|
1435
|
+
graceMs: settings.killGraceSeconds * 1e3,
|
|
1436
|
+
collector,
|
|
1437
|
+
windows: win,
|
|
1438
|
+
parentEnv: this.#d.env,
|
|
1439
|
+
...opts.signal ? { signal: opts.signal } : {},
|
|
1440
|
+
...opts.onHeartbeat ? { onHeartbeat: opts.onHeartbeat } : {},
|
|
1441
|
+
...opts.heartbeatMs ? { heartbeatMs: opts.heartbeatMs } : {}
|
|
1442
|
+
}).catch((err) => {
|
|
1443
|
+
if (err instanceof ExecutionError && err.code === "too-many-processes") this.#executed.delete(prepared.id);
|
|
1444
|
+
throw err;
|
|
1445
|
+
});
|
|
1446
|
+
const snap = raw ? { text: raw.snapshot().stderr, truncated: raw.snapshot().truncated, omittedBytes: 0 } : collector.snapshot();
|
|
1447
|
+
const result = {
|
|
1448
|
+
id: prepared.id,
|
|
1449
|
+
command: redactSecrets(prepared.display),
|
|
1450
|
+
cwd: prepared.cwdRel,
|
|
1451
|
+
risk: prepared.assessment.risk,
|
|
1452
|
+
status: run.status,
|
|
1453
|
+
exitCode: run.exitCode,
|
|
1454
|
+
signal: run.signal,
|
|
1455
|
+
durationMs: run.durationMs,
|
|
1456
|
+
...run.termination ? { termination: run.termination } : {},
|
|
1457
|
+
...run.spawnError ? { spawnError: run.spawnError } : {},
|
|
1458
|
+
output: snap.text,
|
|
1459
|
+
outputTruncated: snap.truncated,
|
|
1460
|
+
omittedBytes: snap.omittedBytes,
|
|
1461
|
+
startedAt: startedAt.toISOString(),
|
|
1462
|
+
source: prepared.request.source,
|
|
1463
|
+
...raw ? { stdoutRaw: raw.snapshot().stdout } : {}
|
|
1464
|
+
};
|
|
1465
|
+
if (record) this.session.record(result);
|
|
1466
|
+
return result;
|
|
1467
|
+
}
|
|
1468
|
+
#plan(p, env, win) {
|
|
1469
|
+
if (p.request.spec.kind === "shell") {
|
|
1470
|
+
if (!p.shell) throw new ExecutionError("unsupported-platform", "No shell is available for shell mode.");
|
|
1471
|
+
const line = p.request.spec.line;
|
|
1472
|
+
return { file: p.shell.file, args: [...p.shell.leading, win ? `"${line}"` : line], cwd: p.cwdAbs, env, ...p.shell.verbatim ? { windowsVerbatimArguments: true } : {} };
|
|
1473
|
+
}
|
|
1474
|
+
if (!p.executable) throw new ExecutionError("not-found", "The program was not resolved.");
|
|
1475
|
+
if (p.executable.cmdScript) {
|
|
1476
|
+
const cmd = this.#d.env["ComSpec"] ?? this.#d.env["COMSPEC"];
|
|
1477
|
+
if (!cmd) throw new ExecutionError("unsupported-platform", "cmd.exe could not be found (ComSpec is not set), which is needed for .cmd programs.");
|
|
1478
|
+
return { file: cmd, args: cmdScriptInvocation(p.executable.file, p.request.spec.args), cwd: p.cwdAbs, env, windowsVerbatimArguments: true };
|
|
1479
|
+
}
|
|
1480
|
+
return { file: p.executable.file, args: p.request.spec.args, cwd: p.cwdAbs, env };
|
|
1481
|
+
}
|
|
1482
|
+
};
|
|
1483
|
+
|
|
1484
|
+
// src/filesystem/workspace.ts
|
|
1485
|
+
import path10 from "path";
|
|
1486
|
+
|
|
1487
|
+
// src/filesystem/filesystem-manager.ts
|
|
1488
|
+
import { promises as fsp9 } from "fs";
|
|
1489
|
+
import path9 from "path";
|
|
1490
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
1491
|
+
|
|
1492
|
+
// src/filesystem/backup-manager.ts
|
|
1493
|
+
import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
|
|
1494
|
+
import { promises as fsp5 } from "fs";
|
|
1495
|
+
import path5 from "path";
|
|
1496
|
+
var BackupManager = class {
|
|
1497
|
+
#base;
|
|
1498
|
+
constructor(dataDir, root) {
|
|
1499
|
+
const ws = createHash2("sha256").update(root).digest("hex").slice(0, 12);
|
|
1500
|
+
this.#base = path5.join(dataDir, "backups", ws);
|
|
1501
|
+
}
|
|
1502
|
+
get location() {
|
|
1503
|
+
return this.#base;
|
|
1504
|
+
}
|
|
1505
|
+
dirFor(id) {
|
|
1506
|
+
if (!/^op-[0-9a-z-]{6,60}$/.test(id)) throw new FsError("invalid-operation", "That is not a valid operation id.");
|
|
1507
|
+
return path5.join(this.#base, id);
|
|
1508
|
+
}
|
|
1509
|
+
newId(now) {
|
|
1510
|
+
const stamp = now.toISOString().replace(/[-:T.Z]/g, "").slice(0, 14);
|
|
1511
|
+
return `op-${stamp}-${randomBytes2(3).toString("hex")}`;
|
|
1512
|
+
}
|
|
1513
|
+
async begin(id) {
|
|
1514
|
+
const dir = this.dirFor(id);
|
|
1515
|
+
try {
|
|
1516
|
+
await fsp5.mkdir(this.#base, { recursive: true, mode: 448 });
|
|
1517
|
+
await fsp5.mkdir(dir, { mode: 448 });
|
|
1518
|
+
} catch (err) {
|
|
1519
|
+
throw new FsError("backup-failed", `The backup folder could not be created${err.code === "EEXIST" ? " (id already used)" : ""}.`, "Nothing was changed. Check that the zg data folder is writable.");
|
|
1520
|
+
}
|
|
1521
|
+
return dir;
|
|
1522
|
+
}
|
|
1523
|
+
async saveContent(id, name, bytes) {
|
|
1524
|
+
try {
|
|
1525
|
+
await fsp5.writeFile(path5.join(this.dirFor(id), name), bytes, { flag: "wx", mode: 384 });
|
|
1526
|
+
} catch {
|
|
1527
|
+
throw new FsError("backup-failed", "A backup copy could not be written, so nothing was changed.");
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
async writeManifest(m) {
|
|
1531
|
+
const file = path5.join(this.dirFor(m.id), "manifest.json");
|
|
1532
|
+
const tmp = `${file}.tmp`;
|
|
1533
|
+
try {
|
|
1534
|
+
await fsp5.writeFile(tmp, JSON.stringify(m, null, 2), { mode: 384 });
|
|
1535
|
+
await fsp5.rename(tmp, file);
|
|
1536
|
+
} catch {
|
|
1537
|
+
throw new FsError("backup-failed", "The backup record could not be written.");
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
async readManifest(id) {
|
|
1541
|
+
try {
|
|
1542
|
+
const raw = JSON.parse(await fsp5.readFile(path5.join(this.dirFor(id), "manifest.json"), "utf8"));
|
|
1543
|
+
if (raw.version !== 1 || raw.id !== id || !Array.isArray(raw.entries)) throw new Error("bad manifest");
|
|
1544
|
+
return raw;
|
|
1545
|
+
} catch (err) {
|
|
1546
|
+
if (err instanceof FsError) throw err;
|
|
1547
|
+
if (err.code === "ENOENT") throw new FsError("not-found", `There is no backup with id ${id}.`);
|
|
1548
|
+
throw new FsError("backup-failed", `The backup record for ${id} is unreadable.`);
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
async readContent(id, name) {
|
|
1552
|
+
if (!/^[0-9a-z.]+$/.test(name)) throw new FsError("backup-failed", "Invalid backup file name.");
|
|
1553
|
+
try {
|
|
1554
|
+
return await fsp5.readFile(path5.join(this.dirFor(id), name));
|
|
1555
|
+
} catch (err) {
|
|
1556
|
+
throw fromNodeError(err, `backup ${id}`);
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
async list(limit = 50) {
|
|
1560
|
+
let names;
|
|
1561
|
+
try {
|
|
1562
|
+
names = (await fsp5.readdir(this.#base)).filter((n) => n.startsWith("op-")).sort().reverse().slice(0, limit);
|
|
1563
|
+
} catch {
|
|
1564
|
+
return [];
|
|
1565
|
+
}
|
|
1566
|
+
const out = [];
|
|
1567
|
+
for (const id of names) {
|
|
1568
|
+
try {
|
|
1569
|
+
const m = await this.readManifest(id);
|
|
1570
|
+
out.push({ id, createdAt: m.createdAt, status: m.status, files: m.entries.map((e) => e.path) });
|
|
1571
|
+
} catch {
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
return out;
|
|
1575
|
+
}
|
|
1576
|
+
};
|
|
1577
|
+
|
|
1578
|
+
// src/filesystem/change-applier.ts
|
|
1579
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
1580
|
+
import { promises as fsp6 } from "fs";
|
|
1581
|
+
import path6 from "path";
|
|
1582
|
+
var CATEGORY = { create: "create_file", edit: "edit_file", delete: "delete_file", rename: "rename_file", move: "move_file" };
|
|
1583
|
+
async function hashOf(abs) {
|
|
1584
|
+
try {
|
|
1585
|
+
return sha256(await fsp6.readFile(abs));
|
|
1586
|
+
} catch {
|
|
1587
|
+
return null;
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
async function atomicWrite(abs, data, mode) {
|
|
1591
|
+
const tmp = path6.join(path6.dirname(abs), `.zg-tmp-${randomBytes3(5).toString("hex")}`);
|
|
1592
|
+
try {
|
|
1593
|
+
await fsp6.writeFile(tmp, data, { flag: "wx", mode: mode ?? 420 });
|
|
1594
|
+
if (mode !== void 0) {
|
|
1595
|
+
try {
|
|
1596
|
+
await fsp6.chmod(tmp, mode);
|
|
1597
|
+
} catch {
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
await fsp6.rename(tmp, abs);
|
|
1601
|
+
} catch (err) {
|
|
1602
|
+
await fsp6.rm(tmp, { force: true }).catch(() => void 0);
|
|
1603
|
+
throw err;
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
async function removeEmptyDirs(root, dirs) {
|
|
1607
|
+
for (const rel of [...dirs].reverse()) {
|
|
1608
|
+
try {
|
|
1609
|
+
await fsp6.rmdir(path6.join(root, ...rel.split("/")));
|
|
1610
|
+
} catch {
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
async function applyChangeSet(d, set, approval) {
|
|
1615
|
+
if (!(approval instanceof UserApproval) || approval.changeSetId !== set.id) throw new FsError("not-approved", "These changes were not approved by you, so nothing was changed.");
|
|
1616
|
+
if (set.needsDeleteConfirmation && !approval.confirmedDeletion) throw new FsError("not-approved", "Deleting files needs your explicit confirmation, so nothing was changed.");
|
|
1617
|
+
if (set.root !== d.v.root) throw new FsError("stale", "The project root changed since these changes were prepared.");
|
|
1618
|
+
for (const c of set.changes) d.perms.require(CATEGORY[c.kind]);
|
|
1619
|
+
const max = d.settings().maxFileBytes;
|
|
1620
|
+
const prepared = [];
|
|
1621
|
+
for (const c of set.changes) {
|
|
1622
|
+
if (c.kind === "create") {
|
|
1623
|
+
const r = await d.v.resolveForWrite(c.path, { mustExist: false });
|
|
1624
|
+
if (r.exists) throw new FsError("stale", `${c.path} was created by something else since you reviewed the changes. Nothing was changed.`);
|
|
1625
|
+
prepared.push({ change: c, abs: r.abs });
|
|
1626
|
+
} else if (c.kind === "edit" || c.kind === "delete") {
|
|
1627
|
+
const r = await d.v.resolveForWrite(c.path, { mustExist: true });
|
|
1628
|
+
const buf = await fsp6.readFile(r.abs).catch((e) => Promise.reject(fromNodeError(e, c.path)));
|
|
1629
|
+
if (buf.length > max) throw new FsError("too-large", `${c.path} grew beyond the size limit since the preview.`);
|
|
1630
|
+
if (sha256(buf) !== c.baseHash) throw new FsError("stale", `${c.path} changed since you reviewed it (by you or another program). Nothing was changed.`, "Ask for the change again so it is based on the current file.");
|
|
1631
|
+
prepared.push({ change: c, abs: r.abs, original: buf });
|
|
1632
|
+
} else {
|
|
1633
|
+
const from = await d.v.resolveForWrite(c.from, { mustExist: true });
|
|
1634
|
+
const to = await d.v.resolveForWrite(c.path, { mustExist: false });
|
|
1635
|
+
if (to.exists) throw new FsError("stale", `${c.path} now exists. Nothing was moved onto it.`);
|
|
1636
|
+
const h = await hashOf(from.abs);
|
|
1637
|
+
if (h !== c.baseHash) throw new FsError("stale", `${c.from} changed since you reviewed it. Nothing was changed.`);
|
|
1638
|
+
prepared.push({ change: c, abs: to.abs, fromAbs: from.abs });
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
const id = d.backups.newId(d.now());
|
|
1642
|
+
let backup = null;
|
|
1643
|
+
const manifest = { version: 1, id, createdAt: d.now().toISOString(), root: d.v.root, status: "pending", entries: [] };
|
|
1644
|
+
const useBackups = d.settings().backups;
|
|
1645
|
+
if (useBackups) {
|
|
1646
|
+
await d.backups.begin(id);
|
|
1647
|
+
let n = 0;
|
|
1648
|
+
for (const p of prepared) {
|
|
1649
|
+
const c = p.change;
|
|
1650
|
+
const entry = { kind: c.kind, path: c.path };
|
|
1651
|
+
if (c.kind === "edit" || c.kind === "delete") {
|
|
1652
|
+
const name = `${String(++n).padStart(4, "0")}.bak`;
|
|
1653
|
+
await d.backups.saveContent(id, name, p.original);
|
|
1654
|
+
entry.file = name;
|
|
1655
|
+
entry.beforeHash = c.baseHash;
|
|
1656
|
+
entry.mode = c.mode;
|
|
1657
|
+
if (c.kind === "edit") entry.afterHash = c.hash;
|
|
1658
|
+
} else if (c.kind === "create") {
|
|
1659
|
+
entry.afterHash = c.hash;
|
|
1660
|
+
if (c.parentsToCreate.length > 0) entry.createdDirs = c.parentsToCreate;
|
|
1661
|
+
} else {
|
|
1662
|
+
entry.from = c.from;
|
|
1663
|
+
entry.beforeHash = c.baseHash;
|
|
1664
|
+
entry.afterHash = c.baseHash;
|
|
1665
|
+
if (c.parentsToCreate.length > 0) entry.createdDirs = c.parentsToCreate;
|
|
1666
|
+
}
|
|
1667
|
+
manifest.entries.push(entry);
|
|
1668
|
+
}
|
|
1669
|
+
await d.backups.writeManifest(manifest);
|
|
1670
|
+
backup = { id, location: d.backups.dirFor(id) };
|
|
1671
|
+
}
|
|
1672
|
+
const undo = [];
|
|
1673
|
+
const applied = [];
|
|
1674
|
+
try {
|
|
1675
|
+
for (const p of prepared) {
|
|
1676
|
+
const c = p.change;
|
|
1677
|
+
if (c.kind === "move" || c.kind === "rename") {
|
|
1678
|
+
await d.v.resolveForWrite(c.from, { mustExist: true });
|
|
1679
|
+
await d.v.resolveForWrite(c.path, { mustExist: false });
|
|
1680
|
+
} else await d.v.resolveForWrite(c.path, { mustExist: c.kind !== "create" });
|
|
1681
|
+
if (c.kind === "create") {
|
|
1682
|
+
const created = [];
|
|
1683
|
+
for (const dir of c.parentsToCreate) {
|
|
1684
|
+
await fsp6.mkdir(path6.join(d.v.root, ...dir.split("/")), { mode: 493 });
|
|
1685
|
+
created.push(dir);
|
|
1686
|
+
}
|
|
1687
|
+
undo.push(async () => removeEmptyDirs(d.v.root, created));
|
|
1688
|
+
try {
|
|
1689
|
+
await fsp6.writeFile(p.abs, c.content, { flag: "wx", mode: 420 });
|
|
1690
|
+
} catch (err) {
|
|
1691
|
+
throw fromNodeError(err, c.path);
|
|
1692
|
+
}
|
|
1693
|
+
undo.push(async () => {
|
|
1694
|
+
if (await hashOf(p.abs) === c.hash) await fsp6.unlink(p.abs);
|
|
1695
|
+
});
|
|
1696
|
+
if (await hashOf(p.abs) !== c.hash) throw new FsError("verify-failed", `${c.path} did not contain the expected content after writing.`);
|
|
1697
|
+
applied.push({ kind: "create", path: c.path, added: c.added, removed: 0, bytes: c.bytes });
|
|
1698
|
+
} else if (c.kind === "edit") {
|
|
1699
|
+
const original = p.original;
|
|
1700
|
+
if (await hashOf(p.abs) !== c.baseHash) throw new FsError("stale", `${c.path} changed while the edit was being applied.`);
|
|
1701
|
+
await atomicWrite(p.abs, Buffer.concat([c.bom ? Buffer.from([239, 187, 191]) : Buffer.alloc(0), Buffer.from(c.content, "utf8")]), c.mode);
|
|
1702
|
+
undo.push(async () => atomicWrite(p.abs, original, c.mode));
|
|
1703
|
+
if (await hashOf(p.abs) !== c.hash) throw new FsError("verify-failed", `${c.path} did not contain the expected content after writing.`);
|
|
1704
|
+
applied.push({ kind: "edit", path: c.path, added: c.added, removed: c.removed, bytes: c.bytes });
|
|
1705
|
+
} else if (c.kind === "delete") {
|
|
1706
|
+
const original = p.original;
|
|
1707
|
+
if (await hashOf(p.abs) !== c.baseHash) throw new FsError("stale", `${c.path} changed before it could be deleted.`);
|
|
1708
|
+
await fsp6.unlink(p.abs);
|
|
1709
|
+
undo.push(async () => {
|
|
1710
|
+
await fsp6.writeFile(p.abs, original, { flag: "wx", mode: c.mode });
|
|
1711
|
+
});
|
|
1712
|
+
applied.push({ kind: "delete", path: c.path, added: 0, removed: c.removed });
|
|
1713
|
+
} else {
|
|
1714
|
+
const created = [];
|
|
1715
|
+
for (const dir of c.parentsToCreate) {
|
|
1716
|
+
await fsp6.mkdir(path6.join(d.v.root, ...dir.split("/")), { mode: 493 });
|
|
1717
|
+
created.push(dir);
|
|
1718
|
+
}
|
|
1719
|
+
undo.push(async () => removeEmptyDirs(d.v.root, created));
|
|
1720
|
+
try {
|
|
1721
|
+
await fsp6.rename(p.fromAbs, p.abs);
|
|
1722
|
+
} catch (err) {
|
|
1723
|
+
throw fromNodeError(err, c.path);
|
|
1724
|
+
}
|
|
1725
|
+
undo.push(async () => {
|
|
1726
|
+
await fsp6.rename(p.abs, p.fromAbs);
|
|
1727
|
+
});
|
|
1728
|
+
if (await hashOf(p.abs) !== c.baseHash) throw new FsError("verify-failed", `${c.path} did not contain the expected content after the move.`);
|
|
1729
|
+
applied.push({ kind: c.kind, path: c.path, from: c.from, added: 0, removed: 0 });
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
} catch (err) {
|
|
1733
|
+
const failures = [];
|
|
1734
|
+
for (const u of undo.reverse()) {
|
|
1735
|
+
try {
|
|
1736
|
+
await u();
|
|
1737
|
+
} catch (e) {
|
|
1738
|
+
failures.push(e instanceof Error ? e.message : "restore step failed");
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
if (useBackups) {
|
|
1742
|
+
manifest.status = "rolled-back";
|
|
1743
|
+
await d.backups.writeManifest(manifest).catch(() => void 0);
|
|
1744
|
+
}
|
|
1745
|
+
const base = err instanceof FsError ? err : fromNodeError(err, "the project");
|
|
1746
|
+
const tail = failures.length === 0 ? " Everything that had been changed was put back." : ` Some changes could not be undone automatically${backup ? ` (originals are in backup ${backup.id}; /restore ${backup.id})` : ""}.`;
|
|
1747
|
+
throw new FsError(base.code, `${base.message}${tail}`, base.hint);
|
|
1748
|
+
}
|
|
1749
|
+
if (useBackups) {
|
|
1750
|
+
manifest.status = "applied";
|
|
1751
|
+
await d.backups.writeManifest(manifest).catch(() => void 0);
|
|
1752
|
+
}
|
|
1753
|
+
return { operationId: id, applied, backup };
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
// src/filesystem/change-planner.ts
|
|
1757
|
+
import { promises as fsp7 } from "fs";
|
|
1758
|
+
import path7 from "path";
|
|
1759
|
+
|
|
1760
|
+
// src/filesystem/code-editor.ts
|
|
1761
|
+
import { z as z2 } from "zod";
|
|
1762
|
+
var text2 = z2.string().max(5e5);
|
|
1763
|
+
var lineNo = z2.number().int().min(1).max(1e7);
|
|
1764
|
+
var EditSchema = z2.discriminatedUnion("type", [
|
|
1765
|
+
z2.object({ type: z2.literal("replace-text"), find: z2.string().min(1).max(1e5), replace: text2, all: z2.boolean().optional() }).strict(),
|
|
1766
|
+
z2.object({ type: z2.literal("replace-lines"), startLine: lineNo, endLine: lineNo, expected: z2.string().min(1).max(1e5), text: text2 }).strict(),
|
|
1767
|
+
z2.object({ type: z2.literal("insert-lines"), afterLine: z2.number().int().min(0).max(1e7), text: z2.string().min(1).max(5e5) }).strict(),
|
|
1768
|
+
z2.object({ type: z2.literal("delete-lines"), startLine: lineNo, endLine: lineNo, expected: z2.string().min(1).max(1e5) }).strict(),
|
|
1769
|
+
z2.object({ type: z2.literal("replace-file"), content: z2.string().min(1).max(5e5) }).strict()
|
|
1770
|
+
]);
|
|
1771
|
+
var MAX_EDITS = 50;
|
|
1772
|
+
function lineOf(textBefore, index) {
|
|
1773
|
+
let n = 1;
|
|
1774
|
+
for (let i = 0; i < index; i++) if (textBefore.charCodeAt(i) === 10) n++;
|
|
1775
|
+
return n;
|
|
1776
|
+
}
|
|
1777
|
+
function asBlock(t) {
|
|
1778
|
+
const body = t.endsWith("\n") ? t.slice(0, -1) : t;
|
|
1779
|
+
return body.split("\n");
|
|
1780
|
+
}
|
|
1781
|
+
function applyEdits(original, edits) {
|
|
1782
|
+
if (edits.length === 0) throw new FsError("invalid-operation", "No edits were given.");
|
|
1783
|
+
if (edits.length > MAX_EDITS) throw new FsError("invalid-operation", `At most ${MAX_EDITS} edits are allowed in one operation.`);
|
|
1784
|
+
const whole = edits.filter((e) => e.type === "replace-file");
|
|
1785
|
+
if (whole.length > 0) {
|
|
1786
|
+
if (edits.length > 1) throw new FsError("unsupported", "A full-file replacement cannot be combined with other edits.");
|
|
1787
|
+
const e = whole[0];
|
|
1788
|
+
if (e.content.trim() === "" && original.trim() !== "") throw new FsError("empty-replacement", "Replacing a file that has content with an empty file is refused.", "To remove a file, delete it (with approval) instead.");
|
|
1789
|
+
return e.content.replace(/\r\n/g, "\n");
|
|
1790
|
+
}
|
|
1791
|
+
const textEdits = edits.filter((e) => e.type === "replace-text");
|
|
1792
|
+
const lineEdits = edits.filter((e) => e.type !== "replace-text");
|
|
1793
|
+
if (textEdits.length > 0 && lineEdits.length > 0) throw new FsError("unsupported", "Text replacements and line edits cannot be mixed in one operation.", "Use separate operations, or only one kind.");
|
|
1794
|
+
let out = original;
|
|
1795
|
+
if (textEdits.length > 0) {
|
|
1796
|
+
for (const e of textEdits) {
|
|
1797
|
+
const find = e.find.replace(/\r\n/g, "\n");
|
|
1798
|
+
const rep = e.replace.replace(/\r\n/g, "\n");
|
|
1799
|
+
const first = out.indexOf(find);
|
|
1800
|
+
if (first === -1) throw new FsError("no-match", `The text to replace was not found: "${preview(find)}".`, "The file may have changed, or the expected text is not exact.");
|
|
1801
|
+
let count = 0;
|
|
1802
|
+
for (let at = out.indexOf(find); at !== -1; at = out.indexOf(find, at + find.length)) count++;
|
|
1803
|
+
if (count > 1 && !e.all) throw new FsError("ambiguous", `The text "${preview(find)}" occurs ${count} times (first at line ${lineOf(out, first)}).`, "Include more surrounding text so it matches once, or set all: true.");
|
|
1804
|
+
out = e.all ? out.split(find).join(rep) : out.slice(0, first) + rep + out.slice(first + find.length);
|
|
1805
|
+
}
|
|
1806
|
+
return finish(original, out);
|
|
1807
|
+
}
|
|
1808
|
+
const lines = splitLines(original);
|
|
1809
|
+
const trailingNewline = original.endsWith("\n");
|
|
1810
|
+
const ranges = lineEdits.map((e) => {
|
|
1811
|
+
if (e.type === "insert-lines") return { s: e.afterLine + 1, e: e.afterLine, edit: e };
|
|
1812
|
+
const le = e;
|
|
1813
|
+
return { s: le.startLine, e: le.endLine, edit: le };
|
|
1814
|
+
});
|
|
1815
|
+
for (const r of ranges) {
|
|
1816
|
+
if (r.edit.type !== "insert-lines" && r.e < r.s) throw new FsError("invalid-operation", "endLine must not be before startLine.");
|
|
1817
|
+
if (r.edit.type === "insert-lines" ? r.edit.afterLine > lines.length : r.e > lines.length) throw new FsError("no-match", `The file has ${lines.length} line${lines.length === 1 ? "" : "s"}; line ${r.edit.type === "insert-lines" ? r.edit.afterLine : r.e} does not exist.`);
|
|
1818
|
+
}
|
|
1819
|
+
const sorted = [...ranges].sort((x, y) => x.s - y.s || x.e - y.e);
|
|
1820
|
+
for (let i = 1; i < sorted.length; i++) {
|
|
1821
|
+
const prev = sorted[i - 1];
|
|
1822
|
+
const cur = sorted[i];
|
|
1823
|
+
const curInsert = cur.edit.type === "insert-lines";
|
|
1824
|
+
if (prev.edit.type !== "insert-lines" && !curInsert && cur.s <= prev.e) throw new FsError("invalid-operation", "Line edits overlap.");
|
|
1825
|
+
}
|
|
1826
|
+
for (const r of ranges) {
|
|
1827
|
+
if (r.edit.type === "replace-lines" || r.edit.type === "delete-lines") {
|
|
1828
|
+
const actual = lines.slice(r.s - 1, r.e).join("\n");
|
|
1829
|
+
if (actual !== r.edit.expected.replace(/\r\n/g, "\n").replace(/\n$/, "")) throw new FsError("no-match", `The lines ${r.s}-${r.e} do not contain the expected text.`, "Read the file again before editing it.");
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
const result = [...lines];
|
|
1833
|
+
const ordered = ranges.map((r, idx) => ({ ...r, idx })).sort((x, y) => y.s - x.s || y.idx - x.idx);
|
|
1834
|
+
for (const r of ordered) {
|
|
1835
|
+
if (r.edit.type === "insert-lines") result.splice(r.edit.afterLine, 0, ...asBlock(r.edit.text.replace(/\r\n/g, "\n")));
|
|
1836
|
+
else if (r.edit.type === "replace-lines") result.splice(r.s - 1, r.e - r.s + 1, ...r.edit.text === "" ? [] : asBlock(r.edit.text.replace(/\r\n/g, "\n")));
|
|
1837
|
+
else result.splice(r.s - 1, r.e - r.s + 1);
|
|
1838
|
+
}
|
|
1839
|
+
const joined = result.join("\n");
|
|
1840
|
+
return finish(original, result.length === 0 ? "" : trailingNewline || original === "" ? `${joined}
|
|
1841
|
+
` : joined);
|
|
1842
|
+
}
|
|
1843
|
+
function finish(original, next) {
|
|
1844
|
+
if (next === original) throw new FsError("no-change", "The edit would not change the file.");
|
|
1845
|
+
if (next.trim() === "" && original.trim() !== "") throw new FsError("empty-replacement", "The edit would leave the file empty, which is refused.", "To remove a file, delete it (with approval) instead.");
|
|
1846
|
+
return next;
|
|
1847
|
+
}
|
|
1848
|
+
function preview(s) {
|
|
1849
|
+
const one = s.replace(/\s+/g, " ").trim();
|
|
1850
|
+
return one.length > 60 ? `${one.slice(0, 57)}...` : one;
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
// src/filesystem/diff-engine.ts
|
|
1854
|
+
var MAX_D = 1500;
|
|
1855
|
+
function myers(a, b) {
|
|
1856
|
+
const n = a.length;
|
|
1857
|
+
const m = b.length;
|
|
1858
|
+
if (n === 0) return b.map((line) => ({ t: "add", line }));
|
|
1859
|
+
if (m === 0) return a.map((line) => ({ t: "del", line }));
|
|
1860
|
+
const max = Math.min(n + m, MAX_D);
|
|
1861
|
+
const offset = max;
|
|
1862
|
+
const v = new Int32Array(2 * max + 2);
|
|
1863
|
+
const trace = [];
|
|
1864
|
+
let found = -1;
|
|
1865
|
+
outer: for (let d = 0; d <= max; d++) {
|
|
1866
|
+
trace.push(v.slice());
|
|
1867
|
+
for (let k = -d; k <= d; k += 2) {
|
|
1868
|
+
let x2;
|
|
1869
|
+
if (k === -d || k !== d && v[offset + k - 1] < v[offset + k + 1]) x2 = v[offset + k + 1];
|
|
1870
|
+
else x2 = v[offset + k - 1] + 1;
|
|
1871
|
+
let y2 = x2 - k;
|
|
1872
|
+
while (x2 < n && y2 < m && a[x2] === b[y2]) {
|
|
1873
|
+
x2++;
|
|
1874
|
+
y2++;
|
|
1875
|
+
}
|
|
1876
|
+
v[offset + k] = x2;
|
|
1877
|
+
if (x2 >= n && y2 >= m) {
|
|
1878
|
+
found = d;
|
|
1879
|
+
break outer;
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
if (found === -1) {
|
|
1884
|
+
return [...a.map((line) => ({ t: "del", line })), ...b.map((line) => ({ t: "add", line }))];
|
|
1885
|
+
}
|
|
1886
|
+
const ops = [];
|
|
1887
|
+
let x = n;
|
|
1888
|
+
let y = m;
|
|
1889
|
+
for (let d = found; d > 0; d--) {
|
|
1890
|
+
const prev = trace[d];
|
|
1891
|
+
const k = x - y;
|
|
1892
|
+
let pk;
|
|
1893
|
+
if (k === -d || k !== d && prev[offset + k - 1] < prev[offset + k + 1]) pk = k + 1;
|
|
1894
|
+
else pk = k - 1;
|
|
1895
|
+
const px = prev[offset + pk];
|
|
1896
|
+
const py = px - pk;
|
|
1897
|
+
while (x > px && y > py) {
|
|
1898
|
+
ops.push({ t: "eq", line: a[x - 1] });
|
|
1899
|
+
x--;
|
|
1900
|
+
y--;
|
|
1901
|
+
}
|
|
1902
|
+
if (x === px) ops.push({ t: "add", line: b[y - 1] });
|
|
1903
|
+
else ops.push({ t: "del", line: a[x - 1] });
|
|
1904
|
+
x = px;
|
|
1905
|
+
y = py;
|
|
1906
|
+
}
|
|
1907
|
+
while (x > 0 && y > 0) {
|
|
1908
|
+
ops.push({ t: "eq", line: a[x - 1] });
|
|
1909
|
+
x--;
|
|
1910
|
+
y--;
|
|
1911
|
+
}
|
|
1912
|
+
return ops.reverse();
|
|
1913
|
+
}
|
|
1914
|
+
function diffLines(oldLines, newLines) {
|
|
1915
|
+
let start = 0;
|
|
1916
|
+
while (start < oldLines.length && start < newLines.length && oldLines[start] === newLines[start]) start++;
|
|
1917
|
+
let endOld = oldLines.length;
|
|
1918
|
+
let endNew = newLines.length;
|
|
1919
|
+
while (endOld > start && endNew > start && oldLines[endOld - 1] === newLines[endNew - 1]) {
|
|
1920
|
+
endOld--;
|
|
1921
|
+
endNew--;
|
|
1922
|
+
}
|
|
1923
|
+
return [
|
|
1924
|
+
...oldLines.slice(0, start).map((line) => ({ t: "eq", line })),
|
|
1925
|
+
...myers(oldLines.slice(start, endOld), newLines.slice(start, endNew)),
|
|
1926
|
+
...oldLines.slice(endOld).map((line) => ({ t: "eq", line }))
|
|
1927
|
+
];
|
|
1928
|
+
}
|
|
1929
|
+
var NOEOL = "\0<no-eol>";
|
|
1930
|
+
function toLines(text3) {
|
|
1931
|
+
if (text3 === "") return [];
|
|
1932
|
+
const lines = text3.split("\n");
|
|
1933
|
+
if (lines[lines.length - 1] === "") {
|
|
1934
|
+
lines.pop();
|
|
1935
|
+
return lines;
|
|
1936
|
+
}
|
|
1937
|
+
lines[lines.length - 1] = `${lines[lines.length - 1]}${NOEOL}`;
|
|
1938
|
+
return lines;
|
|
1939
|
+
}
|
|
1940
|
+
var plain = (l) => l.endsWith(NOEOL) ? l.slice(0, -NOEOL.length) : l;
|
|
1941
|
+
var marker = (l) => l.endsWith(NOEOL) ? ["\"] : [];
|
|
1942
|
+
function unifiedDiff(oldText, newText, opts) {
|
|
1943
|
+
const ops = diffLines(toLines(oldText), toLines(newText));
|
|
1944
|
+
const added = ops.filter((o) => o.t === "add").length;
|
|
1945
|
+
const removed = ops.filter((o) => o.t === "del").length;
|
|
1946
|
+
if (added === 0 && removed === 0) return { text: "", added, removed, changed: false };
|
|
1947
|
+
const ctx = opts.context ?? 3;
|
|
1948
|
+
const out = [`--- ${opts.oldLabel}`, `+++ ${opts.newLabel}`];
|
|
1949
|
+
const keep = new Array(ops.length).fill(false);
|
|
1950
|
+
ops.forEach((o, i2) => {
|
|
1951
|
+
if (o.t !== "eq") for (let j = Math.max(0, i2 - ctx); j <= Math.min(ops.length - 1, i2 + ctx); j++) keep[j] = true;
|
|
1952
|
+
});
|
|
1953
|
+
let oldNo = 1;
|
|
1954
|
+
let newNo = 1;
|
|
1955
|
+
let i = 0;
|
|
1956
|
+
while (i < ops.length) {
|
|
1957
|
+
if (!keep[i]) {
|
|
1958
|
+
const o = ops[i];
|
|
1959
|
+
if (o.t !== "add") oldNo++;
|
|
1960
|
+
if (o.t !== "del") newNo++;
|
|
1961
|
+
i++;
|
|
1962
|
+
continue;
|
|
1963
|
+
}
|
|
1964
|
+
const hunkOldStart = oldNo;
|
|
1965
|
+
const hunkNewStart = newNo;
|
|
1966
|
+
const body = [];
|
|
1967
|
+
let oldLen = 0;
|
|
1968
|
+
let newLen = 0;
|
|
1969
|
+
while (i < ops.length && keep[i]) {
|
|
1970
|
+
const o = ops[i];
|
|
1971
|
+
if (o.t === "eq") {
|
|
1972
|
+
body.push(` ${plain(o.line)}`, ...marker(o.line));
|
|
1973
|
+
oldNo++;
|
|
1974
|
+
newNo++;
|
|
1975
|
+
oldLen++;
|
|
1976
|
+
newLen++;
|
|
1977
|
+
} else if (o.t === "del") {
|
|
1978
|
+
body.push(`-${plain(o.line)}`, ...marker(o.line));
|
|
1979
|
+
oldNo++;
|
|
1980
|
+
oldLen++;
|
|
1981
|
+
} else {
|
|
1982
|
+
body.push(`+${plain(o.line)}`, ...marker(o.line));
|
|
1983
|
+
newNo++;
|
|
1984
|
+
newLen++;
|
|
1985
|
+
}
|
|
1986
|
+
i++;
|
|
1987
|
+
}
|
|
1988
|
+
out.push(`@@ -${oldLen === 0 ? hunkOldStart - 1 : hunkOldStart},${oldLen} +${newLen === 0 ? hunkNewStart - 1 : hunkNewStart},${newLen} @@`, ...body);
|
|
1989
|
+
}
|
|
1990
|
+
let lines = out;
|
|
1991
|
+
if (opts.maxLines && out.length > opts.maxLines) lines = [...out.slice(0, opts.maxLines), `... ${out.length - opts.maxLines} more diff lines not shown ...`];
|
|
1992
|
+
return { text: lines.join("\n"), added, removed, changed: true };
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
// src/filesystem/operations.ts
|
|
1996
|
+
import { z as z3 } from "zod";
|
|
1997
|
+
var relPath = z3.string().min(1).max(1e3);
|
|
1998
|
+
var FileOperationSchema = z3.discriminatedUnion("op", [
|
|
1999
|
+
z3.object({ op: z3.literal("create"), path: relPath, content: z3.string().max(5e5), createParents: z3.boolean().optional() }).strict(),
|
|
2000
|
+
z3.object({ op: z3.literal("edit"), path: relPath, edits: z3.array(EditSchema).min(1).max(50) }).strict(),
|
|
2001
|
+
z3.object({ op: z3.literal("delete"), path: relPath }).strict(),
|
|
2002
|
+
z3.object({ op: z3.literal("rename"), from: relPath, to: relPath }).strict(),
|
|
2003
|
+
z3.object({ op: z3.literal("move"), from: relPath, to: relPath, createParents: z3.boolean().optional() }).strict()
|
|
2004
|
+
]);
|
|
2005
|
+
var FileOperationsSchema = z3.array(FileOperationSchema).min(1).max(20);
|
|
2006
|
+
function totalsOf(changes) {
|
|
2007
|
+
const t = { created: 0, modified: 0, deleted: 0, renamed: 0, moved: 0, added: 0, removed: 0 };
|
|
2008
|
+
for (const c of changes) {
|
|
2009
|
+
if (c.kind === "create") t.created++;
|
|
2010
|
+
else if (c.kind === "edit") t.modified++;
|
|
2011
|
+
else if (c.kind === "delete") t.deleted++;
|
|
2012
|
+
else if (c.kind === "rename") t.renamed++;
|
|
2013
|
+
else t.moved++;
|
|
2014
|
+
t.added += c.added;
|
|
2015
|
+
t.removed += c.removed;
|
|
2016
|
+
}
|
|
2017
|
+
return t;
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
// src/filesystem/change-planner.ts
|
|
2021
|
+
var MAX_TOTAL_BYTES = 2e6;
|
|
2022
|
+
async function readForEdit(abs, rel, max) {
|
|
2023
|
+
let handle;
|
|
2024
|
+
try {
|
|
2025
|
+
handle = await fsp7.open(abs, "r");
|
|
2026
|
+
} catch (err) {
|
|
2027
|
+
throw fromNodeError(err, rel);
|
|
2028
|
+
}
|
|
2029
|
+
try {
|
|
2030
|
+
const st = await handle.stat();
|
|
2031
|
+
if (!st.isFile()) throw new FsError("not-a-file", `${rel} is not a regular file.`);
|
|
2032
|
+
if (st.size > max) throw new FsError("too-large", `${rel} is ${st.size.toLocaleString("en-US")} bytes, over the ${max.toLocaleString("en-US")}-byte limit for changes.`);
|
|
2033
|
+
const buf = Buffer.alloc(st.size);
|
|
2034
|
+
let off = 0;
|
|
2035
|
+
while (off < st.size) {
|
|
2036
|
+
const { bytesRead } = await handle.read(buf, off, st.size - off, off);
|
|
2037
|
+
if (bytesRead === 0) break;
|
|
2038
|
+
off += bytesRead;
|
|
2039
|
+
}
|
|
2040
|
+
return buf.subarray(0, off);
|
|
2041
|
+
} finally {
|
|
2042
|
+
await handle.close();
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
function checkContent(rel, content) {
|
|
2046
|
+
if (content.includes("\0")) throw new FsError("binary", `The new content for ${rel} contains NUL characters; only text files can be written.`);
|
|
2047
|
+
if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(content)) throw new FsError("invalid-encoding", `The new content for ${rel} is not valid Unicode text.`);
|
|
2048
|
+
}
|
|
2049
|
+
function zodMessage(err) {
|
|
2050
|
+
return err.issues.slice(0, 4).map((i) => `${i.path.join(".") || "operations"}: ${i.message}`).join("; ");
|
|
2051
|
+
}
|
|
2052
|
+
async function planChangeSet(d, raw) {
|
|
2053
|
+
const parsed = FileOperationsSchema.safeParse(raw);
|
|
2054
|
+
if (!parsed.success) throw new FsError("invalid-operation", `The proposed file operations are not valid (${zodMessage(parsed.error)}).`);
|
|
2055
|
+
const max = d.settings().maxFileBytes;
|
|
2056
|
+
const changes = [];
|
|
2057
|
+
const touched = /* @__PURE__ */ new Set();
|
|
2058
|
+
const touch = (rel) => {
|
|
2059
|
+
const key = rel.toLowerCase();
|
|
2060
|
+
if (touched.has(key)) throw new FsError("invalid-operation", `${rel} is touched by more than one operation.`, "Combine the changes to one file into a single edit operation.");
|
|
2061
|
+
touched.add(key);
|
|
2062
|
+
};
|
|
2063
|
+
let totalBytes = 0;
|
|
2064
|
+
for (const op of parsed.data) {
|
|
2065
|
+
if (op.op === "create") {
|
|
2066
|
+
d.perms.require("create_file");
|
|
2067
|
+
const r = await d.v.resolveForWrite(op.path, { mustExist: false });
|
|
2068
|
+
if (r.exists) throw new FsError("exists", `${r.rel} already exists, so it was not overwritten.`, "Use an edit operation to change an existing file.");
|
|
2069
|
+
touch(r.rel);
|
|
2070
|
+
checkContent(r.rel, op.content);
|
|
2071
|
+
const bytes = Buffer.byteLength(op.content, "utf8");
|
|
2072
|
+
if (bytes > max) throw new FsError("too-large", `The new file ${r.rel} would be ${bytes.toLocaleString("en-US")} bytes, over the ${max.toLocaleString("en-US")}-byte limit.`);
|
|
2073
|
+
totalBytes += bytes;
|
|
2074
|
+
const parents = await d.v.missingParents(r.rel);
|
|
2075
|
+
if (parents.length > 0 && !op.createParents) throw new FsError("invalid-operation", `The folder ${parents[0]} does not exist. Creating folders needs createParents: true, which is shown to you before approval.`);
|
|
2076
|
+
const dif = unifiedDiff("", toLf(op.content), { oldLabel: "/dev/null", newLabel: `b/${r.rel}` });
|
|
2077
|
+
changes.push({ kind: "create", path: r.rel, content: op.content, hash: sha256(Buffer.from(op.content, "utf8")), bytes, parentsToCreate: parents, diff: dif.text || `(empty file)`, added: dif.added, removed: 0 });
|
|
2078
|
+
} else if (op.op === "edit") {
|
|
2079
|
+
d.perms.require("edit_file");
|
|
2080
|
+
const r = await d.v.resolveForWrite(op.path, { mustExist: true });
|
|
2081
|
+
touch(r.rel);
|
|
2082
|
+
const buf = await readForEdit(r.abs, r.rel, max);
|
|
2083
|
+
if (looksBinary(buf)) throw new FsError("binary", `${r.rel} looks like a binary file; it was not edited.`);
|
|
2084
|
+
const dec = decodeUtf8(buf);
|
|
2085
|
+
if (!dec) throw new FsError("invalid-encoding", `${r.rel} is not valid UTF-8, so it was not edited.`);
|
|
2086
|
+
const eol = detectLineEnding(dec.text);
|
|
2087
|
+
const oldLf = toLf(dec.text);
|
|
2088
|
+
const newLf = applyEdits(oldLf, op.edits);
|
|
2089
|
+
checkContent(r.rel, newLf);
|
|
2090
|
+
const newText = fromLf(newLf, eol);
|
|
2091
|
+
const outBytes = encodeUtf8(newText, dec.bom);
|
|
2092
|
+
if (outBytes.length > max) throw new FsError("too-large", `The edited ${r.rel} would exceed the ${max.toLocaleString("en-US")}-byte limit.`);
|
|
2093
|
+
totalBytes += outBytes.length;
|
|
2094
|
+
const dif = unifiedDiff(oldLf, newLf, { oldLabel: `a/${r.rel}`, newLabel: `b/${r.rel}` });
|
|
2095
|
+
const st = await fsp7.stat(r.abs);
|
|
2096
|
+
changes.push({ kind: "edit", path: r.rel, baseHash: sha256(buf), content: newText, hash: sha256(outBytes), mode: st.mode & 511, bom: dec.bom, bytes: outBytes.length, diff: dif.text, added: dif.added, removed: dif.removed });
|
|
2097
|
+
} else if (op.op === "delete") {
|
|
2098
|
+
d.perms.require("delete_file");
|
|
2099
|
+
const r = await d.v.resolveForWrite(op.path, { mustExist: true });
|
|
2100
|
+
touch(r.rel);
|
|
2101
|
+
const st = await fsp7.lstat(r.abs);
|
|
2102
|
+
if (!st.isFile()) throw new FsError("not-a-file", `${r.rel} is not a regular file. zg deletes single files only, never folders.`);
|
|
2103
|
+
if (st.size > max) throw new FsError("too-large", `${r.rel} is too large to delete safely (it could not be backed up within the ${max.toLocaleString("en-US")}-byte limit). Delete it yourself.`);
|
|
2104
|
+
const buf = await readForEdit(r.abs, r.rel, max);
|
|
2105
|
+
const dec = looksBinary(buf) ? null : decodeUtf8(buf);
|
|
2106
|
+
const dif = dec ? unifiedDiff(toLf(dec.text), "", { oldLabel: `a/${r.rel}`, newLabel: "/dev/null" }) : null;
|
|
2107
|
+
changes.push({ kind: "delete", path: r.rel, baseHash: sha256(buf), size: buf.length, mode: st.mode & 511, diff: dif?.text || `(${dec ? "empty" : "binary"} file, ${buf.length} bytes)`, added: 0, removed: dif?.removed ?? 0 });
|
|
2108
|
+
} else {
|
|
2109
|
+
const kind = op.op;
|
|
2110
|
+
d.perms.require(kind === "rename" ? "rename_file" : "move_file");
|
|
2111
|
+
const from = await d.v.resolveForWrite(op.from, { mustExist: true });
|
|
2112
|
+
const to = await d.v.resolveForWrite(op.to, { mustExist: false });
|
|
2113
|
+
if (from.rel.toLowerCase() === to.rel.toLowerCase()) throw new FsError("invalid-operation", "The source and destination are the same.");
|
|
2114
|
+
const sameDir = path7.posix.dirname(from.rel) === path7.posix.dirname(to.rel);
|
|
2115
|
+
if (kind === "rename" && !sameDir) throw new FsError("invalid-operation", "A rename keeps the file in its folder. Use a move to change folders.");
|
|
2116
|
+
if (kind === "move" && sameDir) throw new FsError("invalid-operation", "The destination is in the same folder. Use a rename.");
|
|
2117
|
+
if (to.exists) throw new FsError("exists", `${to.rel} already exists, so nothing was moved onto it.`);
|
|
2118
|
+
touch(from.rel);
|
|
2119
|
+
touch(to.rel);
|
|
2120
|
+
const st = await fsp7.lstat(from.abs);
|
|
2121
|
+
if (!st.isFile()) throw new FsError("not-a-file", `${from.rel} is not a regular file. zg moves single files only.`);
|
|
2122
|
+
const parents = await d.v.missingParents(to.rel);
|
|
2123
|
+
const wantsParents = op.op === "move" && op.createParents === true;
|
|
2124
|
+
if (parents.length > 0 && !wantsParents) throw new FsError("invalid-operation", `The folder ${parents[0]} does not exist. Creating folders needs createParents: true on a move.`);
|
|
2125
|
+
const buf = await readForEdit(from.abs, from.rel, Math.max(max, st.size));
|
|
2126
|
+
changes.push({ kind, path: to.rel, from: from.rel, baseHash: sha256(buf), parentsToCreate: parents, diff: `${kind} ${from.rel} -> ${to.rel}`, added: 0, removed: 0 });
|
|
2127
|
+
}
|
|
2128
|
+
if (totalBytes > MAX_TOTAL_BYTES) throw new FsError("too-large", "The proposed changes are too large to review in one go (over 2 MB in total).");
|
|
2129
|
+
}
|
|
2130
|
+
return { id: d.newId(), createdAt: d.now(), root: d.v.root, changes, totals: totalsOf(changes), needsDeleteConfirmation: changes.some((c) => c.kind === "delete") };
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
// src/filesystem/directory-tree.ts
|
|
2134
|
+
function renderTree(entries, rootName, style) {
|
|
2135
|
+
const root = { name: rootName, entry: null, children: /* @__PURE__ */ new Map() };
|
|
2136
|
+
for (const e of entries) {
|
|
2137
|
+
let node = root;
|
|
2138
|
+
const parts = e.rel.split("/");
|
|
2139
|
+
parts.forEach((part2, i) => {
|
|
2140
|
+
let child = node.children.get(part2);
|
|
2141
|
+
if (!child) {
|
|
2142
|
+
child = { name: part2, entry: null, children: /* @__PURE__ */ new Map() };
|
|
2143
|
+
node.children.set(part2, child);
|
|
2144
|
+
}
|
|
2145
|
+
if (i === parts.length - 1) child.entry = e;
|
|
2146
|
+
node = child;
|
|
2147
|
+
});
|
|
2148
|
+
}
|
|
2149
|
+
const tee = style.unicode ? "\u251C\u2500\u2500 " : "|-- ";
|
|
2150
|
+
const last = style.unicode ? "\u2514\u2500\u2500 " : "`-- ";
|
|
2151
|
+
const bar = style.unicode ? "\u2502 " : "| ";
|
|
2152
|
+
const lines = [`${rootName}/`];
|
|
2153
|
+
const draw = (node, prefix) => {
|
|
2154
|
+
const kids = [...node.children.values()].sort((a, b) => {
|
|
2155
|
+
const ad = a.children.size > 0 || a.entry?.kind === "dir" ? 0 : 1;
|
|
2156
|
+
const bd = b.children.size > 0 || b.entry?.kind === "dir" ? 0 : 1;
|
|
2157
|
+
return ad - bd || (a.name < b.name ? -1 : 1);
|
|
2158
|
+
});
|
|
2159
|
+
kids.forEach((k, i) => {
|
|
2160
|
+
const isLast = i === kids.length - 1;
|
|
2161
|
+
const dir = k.children.size > 0 || k.entry?.kind === "dir";
|
|
2162
|
+
const label = `${k.name}${dir ? "/" : ""}${k.entry?.kind === "symlink" ? " (link, not followed)" : ""}${k.entry?.protected ? " (protected)" : ""}`;
|
|
2163
|
+
lines.push(`${prefix}${isLast ? last : tee}${label}`);
|
|
2164
|
+
draw(k, prefix + (isLast ? " " : bar));
|
|
2165
|
+
});
|
|
2166
|
+
};
|
|
2167
|
+
draw(root, "");
|
|
2168
|
+
return lines;
|
|
2169
|
+
}
|
|
2170
|
+
|
|
2171
|
+
// src/filesystem/file-search.ts
|
|
2172
|
+
import { promises as fsp8 } from "fs";
|
|
2173
|
+
import path8 from "path";
|
|
2174
|
+
var MAX_LINE2 = 200;
|
|
2175
|
+
function globToRegex(glob, caseSensitive) {
|
|
2176
|
+
const body = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
2177
|
+
return new RegExp(`^${body}$`, caseSensitive ? "" : "i");
|
|
2178
|
+
}
|
|
2179
|
+
async function searchFiles(v, rules, opts) {
|
|
2180
|
+
const query = opts.query.trim();
|
|
2181
|
+
if (query === "") throw new FsError("invalid-operation", "The search text is empty.");
|
|
2182
|
+
if (query.length > 200) throw new FsError("invalid-operation", "The search text is too long (200 characters at most).");
|
|
2183
|
+
const skipped = { binary: 0, tooLarge: 0, protected: 0 };
|
|
2184
|
+
const matches = [];
|
|
2185
|
+
let scanned = 0;
|
|
2186
|
+
let truncated = false;
|
|
2187
|
+
const { entries, truncated: walkCut } = await walk(v, rules, { ...opts.under ? { startRel: opts.under } : {}, maxDepth: 30, maxEntries: opts.maxFilesScanned * 2 });
|
|
2188
|
+
if (walkCut) truncated = true;
|
|
2189
|
+
const excludes = (opts.exclude ?? []).map((g) => globToRegex(g, false));
|
|
2190
|
+
const needle = opts.caseSensitive ? query : query.toLowerCase();
|
|
2191
|
+
const ext = query.startsWith(".") ? query : `.${query}`;
|
|
2192
|
+
const nameRe = /[*?]/.test(query) ? globToRegex(query, opts.caseSensitive) : null;
|
|
2193
|
+
for (const e of entries) {
|
|
2194
|
+
if (e.kind !== "file") continue;
|
|
2195
|
+
if (excludes.some((re) => re.test(e.rel) || re.test(path8.posix.basename(e.rel)))) continue;
|
|
2196
|
+
if (opts.mode === "text" && scanned >= opts.maxFilesScanned) {
|
|
2197
|
+
truncated = true;
|
|
2198
|
+
break;
|
|
2199
|
+
}
|
|
2200
|
+
const base = path8.posix.basename(e.rel);
|
|
2201
|
+
if (opts.mode === "name") {
|
|
2202
|
+
scanned += 1;
|
|
2203
|
+
const hay = opts.caseSensitive ? base : base.toLowerCase();
|
|
2204
|
+
if (nameRe ? nameRe.test(base) : hay.includes(needle)) {
|
|
2205
|
+
matches.push({ path: e.rel });
|
|
2206
|
+
if (matches.length >= opts.maxResults) return { matches, filesScanned: scanned, truncated: true, skipped };
|
|
2207
|
+
}
|
|
2208
|
+
continue;
|
|
2209
|
+
}
|
|
2210
|
+
if (opts.mode === "ext") {
|
|
2211
|
+
scanned += 1;
|
|
2212
|
+
const a = opts.caseSensitive ? base : base.toLowerCase();
|
|
2213
|
+
const b = opts.caseSensitive ? ext : ext.toLowerCase();
|
|
2214
|
+
if (a.endsWith(b) && a.length > b.length) {
|
|
2215
|
+
matches.push({ path: e.rel });
|
|
2216
|
+
if (matches.length >= opts.maxResults) return { matches, filesScanned: scanned, truncated: true, skipped };
|
|
2217
|
+
}
|
|
2218
|
+
continue;
|
|
2219
|
+
}
|
|
2220
|
+
if (e.protected) {
|
|
2221
|
+
skipped.protected += 1;
|
|
2222
|
+
continue;
|
|
2223
|
+
}
|
|
2224
|
+
if ((e.size ?? 0) > opts.maxFileBytes) {
|
|
2225
|
+
skipped.tooLarge += 1;
|
|
2226
|
+
continue;
|
|
2227
|
+
}
|
|
2228
|
+
let buf;
|
|
2229
|
+
try {
|
|
2230
|
+
const real = await v.resolveExisting(e.rel);
|
|
2231
|
+
buf = await fsp8.readFile(real.abs);
|
|
2232
|
+
} catch {
|
|
2233
|
+
continue;
|
|
2234
|
+
}
|
|
2235
|
+
if (buf.length > opts.maxFileBytes) {
|
|
2236
|
+
skipped.tooLarge += 1;
|
|
2237
|
+
continue;
|
|
2238
|
+
}
|
|
2239
|
+
if (looksBinary(buf)) {
|
|
2240
|
+
skipped.binary += 1;
|
|
2241
|
+
continue;
|
|
2242
|
+
}
|
|
2243
|
+
scanned += 1;
|
|
2244
|
+
const lines = buf.toString("utf8").split(/\r?\n/);
|
|
2245
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2246
|
+
const line = lines[i];
|
|
2247
|
+
if ((opts.caseSensitive ? line : line.toLowerCase()).includes(needle)) {
|
|
2248
|
+
const shown = redactSecrets(line.trim());
|
|
2249
|
+
matches.push({ path: e.rel, line: i + 1, text: shown.length > MAX_LINE2 ? `${shown.slice(0, MAX_LINE2 - 3)}...` : shown });
|
|
2250
|
+
if (matches.length >= opts.maxResults) return { matches, filesScanned: scanned, truncated: true, skipped };
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
return { matches, filesScanned: scanned, truncated, skipped };
|
|
2255
|
+
}
|
|
2256
|
+
|
|
2257
|
+
// src/filesystem/filesystem-manager.ts
|
|
2258
|
+
var FilesystemManager = class _FilesystemManager {
|
|
2259
|
+
root;
|
|
2260
|
+
validator;
|
|
2261
|
+
permissions;
|
|
2262
|
+
backups;
|
|
2263
|
+
#settings;
|
|
2264
|
+
#now;
|
|
2265
|
+
#security = null;
|
|
2266
|
+
#hooks = null;
|
|
2267
|
+
constructor(v, opts) {
|
|
2268
|
+
this.root = v.root;
|
|
2269
|
+
this.validator = v;
|
|
2270
|
+
this.#settings = opts.settings;
|
|
2271
|
+
this.#now = opts.now ?? (() => /* @__PURE__ */ new Date());
|
|
2272
|
+
this.permissions = new FsPermissions(opts.settings, opts.approvalMode);
|
|
2273
|
+
this.backups = new BackupManager(opts.dataDir, v.root);
|
|
2274
|
+
}
|
|
2275
|
+
static async open(opts) {
|
|
2276
|
+
return new _FilesystemManager(await PathValidator.create(opts.root), opts);
|
|
2277
|
+
}
|
|
2278
|
+
get settings() {
|
|
2279
|
+
return this.#settings();
|
|
2280
|
+
}
|
|
2281
|
+
async #rules() {
|
|
2282
|
+
const s = this.#settings();
|
|
2283
|
+
return loadIgnoreRules(this.root, { dirs: s.ignoredDirs, patterns: s.ignoredPatterns });
|
|
2284
|
+
}
|
|
2285
|
+
project() {
|
|
2286
|
+
return detectProject(this.root);
|
|
2287
|
+
}
|
|
2288
|
+
async tree(opts) {
|
|
2289
|
+
this.permissions.require("read_file");
|
|
2290
|
+
const rules = await this.#rules();
|
|
2291
|
+
const w = await walk(this.validator, rules, { ...opts.under ? { startRel: this.validator.lexical(opts.under, { allowRoot: true }) } : {}, maxDepth: opts.maxDepth ?? 4, maxEntries: opts.maxEntries ?? 400 });
|
|
2292
|
+
const rootName = opts.under ? this.validator.lexical(opts.under, { allowRoot: true }) || path9.basename(this.root) : path9.basename(this.root);
|
|
2293
|
+
const entries = opts.under ? w.entries.map((e) => ({ ...e, rel: e.rel.slice(this.validator.lexical(opts.under, { allowRoot: true }).length + 1) })).filter((e) => e.rel !== "") : w.entries;
|
|
2294
|
+
return { lines: renderTree(entries, rootName, { unicode: opts.unicode }), entries: w.entries.length, truncated: w.truncated };
|
|
2295
|
+
}
|
|
2296
|
+
async read(input, opts = {}) {
|
|
2297
|
+
this.permissions.require("read_file");
|
|
2298
|
+
return readTextFile(this.validator, input, { maxBytes: this.#settings().maxFileBytes, numbered: true, ...opts.range ? { range: opts.range } : {}, ...opts.allowSensitive ? { allowSensitive: true } : {} });
|
|
2299
|
+
}
|
|
2300
|
+
/** Plain (unnumbered) read used to give file text to the model. Never allows protected files. */
|
|
2301
|
+
async readForModel(input) {
|
|
2302
|
+
this.permissions.require("read_file");
|
|
2303
|
+
if (this.#security) {
|
|
2304
|
+
const rel = this.validator.lexical(input);
|
|
2305
|
+
await this.#security.authorize(fileRequest(rel, "read"));
|
|
2306
|
+
}
|
|
2307
|
+
return readTextFile(this.validator, input, { maxBytes: this.#settings().maxFileBytes, numbered: false });
|
|
2308
|
+
}
|
|
2309
|
+
async search(query, opts) {
|
|
2310
|
+
this.permissions.require("search_files");
|
|
2311
|
+
const s = this.#settings();
|
|
2312
|
+
const rules = await this.#rules();
|
|
2313
|
+
return searchFiles(this.validator, rules, {
|
|
2314
|
+
mode: opts.mode,
|
|
2315
|
+
query,
|
|
2316
|
+
caseSensitive: opts.caseSensitive === true,
|
|
2317
|
+
maxResults: Math.min(opts.maxResults ?? s.search.maxResults, s.search.maxResults),
|
|
2318
|
+
maxFilesScanned: s.search.maxFilesScanned,
|
|
2319
|
+
maxFileBytes: s.maxFileBytes,
|
|
2320
|
+
...opts.under ? { under: this.validator.lexical(opts.under, { allowRoot: true }) } : {},
|
|
2321
|
+
...opts.exclude ? { exclude: opts.exclude } : {}
|
|
2322
|
+
});
|
|
2323
|
+
}
|
|
2324
|
+
plan(rawOperations) {
|
|
2325
|
+
return planChangeSet({ v: this.validator, perms: this.permissions, settings: this.#settings, now: this.#now, newId: () => `cs-${randomBytes4(4).toString("hex")}` }, rawOperations);
|
|
2326
|
+
}
|
|
2327
|
+
/** Lets another module (Git review) learn which files an approved edit touched. Failures in hooks never block an edit. */
|
|
2328
|
+
setApplyHooks(hooks) {
|
|
2329
|
+
this.#hooks = hooks;
|
|
2330
|
+
}
|
|
2331
|
+
/** Attach the central security engine. Every apply and restore is then checked (and audited) before anything is written. */
|
|
2332
|
+
setSecurity(guard) {
|
|
2333
|
+
this.#security = guard;
|
|
2334
|
+
}
|
|
2335
|
+
async apply(set, approval) {
|
|
2336
|
+
const decisions = [];
|
|
2337
|
+
if (this.#security) {
|
|
2338
|
+
try {
|
|
2339
|
+
for (const c of set.changes) {
|
|
2340
|
+
const targets = c.kind === "rename" || c.kind === "move" ? [c.from, c.path] : [c.path];
|
|
2341
|
+
for (const t of targets) decisions.push(await this.#security.authorize(fileRequest(t, c.kind), { approved: true }));
|
|
2342
|
+
}
|
|
2343
|
+
} catch (err) {
|
|
2344
|
+
for (const d of decisions) await this.#security.complete(d, "failed", "not applied: another file in the same change was refused");
|
|
2345
|
+
throw err;
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
try {
|
|
2349
|
+
const result = await this.#applyChecked(set, approval);
|
|
2350
|
+
for (const d of decisions) await this.#security?.complete(d, "completed");
|
|
2351
|
+
return result;
|
|
2352
|
+
} catch (err) {
|
|
2353
|
+
for (const d of decisions) await this.#security?.complete(d, "failed", err instanceof Error ? err.message.slice(0, 120) : "failed");
|
|
2354
|
+
throw err;
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
async #applyChecked(set, approval) {
|
|
2358
|
+
const touched = set.changes.flatMap((c) => c.kind === "rename" || c.kind === "move" ? [c.path, c.from] : [c.path]);
|
|
2359
|
+
try {
|
|
2360
|
+
await this.#hooks?.before?.(touched);
|
|
2361
|
+
} catch {
|
|
2362
|
+
}
|
|
2363
|
+
const result = await applyChangeSet({ v: this.validator, perms: this.permissions, settings: this.#settings, backups: this.backups, now: this.#now }, set, approval);
|
|
2364
|
+
try {
|
|
2365
|
+
this.#hooks?.after?.(result.applied.flatMap((a) => a.from ? [a.path, a.from] : [a.path]));
|
|
2366
|
+
} catch {
|
|
2367
|
+
}
|
|
2368
|
+
return result;
|
|
2369
|
+
}
|
|
2370
|
+
/**
|
|
2371
|
+
* Put back what an earlier operation changed. Without `confirmed` it only reports what would happen.
|
|
2372
|
+
* A file that has changed since the operation is a conflict, and then NOTHING is restored.
|
|
2373
|
+
*/
|
|
2374
|
+
async restore(id, confirmed) {
|
|
2375
|
+
this.permissions.require("edit_file");
|
|
2376
|
+
const m = await this.backups.readManifest(id);
|
|
2377
|
+
if (m.root !== this.root) throw new FsError("denied", "That backup belongs to a different project.");
|
|
2378
|
+
if (m.status !== "applied") throw new FsError("invalid-operation", m.status === "restored" ? `Backup ${id} was already restored.` : `Backup ${id} has nothing to restore (its status is ${m.status}).`);
|
|
2379
|
+
if (confirmed && this.#security) for (const e of m.entries) await this.#security.authorize(fileRequest(e.path, "edit"), { approved: true });
|
|
2380
|
+
const actions = [];
|
|
2381
|
+
const todo = [];
|
|
2382
|
+
for (const e of [...m.entries].reverse()) {
|
|
2383
|
+
const rel = e.path;
|
|
2384
|
+
const w = await this.validator.resolveForWrite(rel, { mustExist: false }).catch((err) => {
|
|
2385
|
+
throw err instanceof FsError ? err : fromNodeError(err, rel);
|
|
2386
|
+
});
|
|
2387
|
+
const cur = w.exists ? await hashOf(w.abs) : null;
|
|
2388
|
+
if (e.kind === "edit") {
|
|
2389
|
+
const a = { path: rel, action: "restore" };
|
|
2390
|
+
if (cur !== e.afterHash) a.conflict = w.exists ? "the file was changed after the operation" : "the file no longer exists";
|
|
2391
|
+
actions.push(a);
|
|
2392
|
+
todo.push(async () => atomicWrite(w.abs, await this.backups.readContent(id, e.file), e.mode));
|
|
2393
|
+
} else if (e.kind === "create") {
|
|
2394
|
+
const a = { path: rel, action: "remove" };
|
|
2395
|
+
if (cur !== e.afterHash) a.conflict = w.exists ? "the file was changed after it was created" : "the file no longer exists";
|
|
2396
|
+
actions.push(a);
|
|
2397
|
+
todo.push(async () => {
|
|
2398
|
+
await fsp9.unlink(w.abs);
|
|
2399
|
+
await removeEmptyDirs(this.root, e.createdDirs ?? []);
|
|
2400
|
+
});
|
|
2401
|
+
} else if (e.kind === "delete") {
|
|
2402
|
+
const a = { path: rel, action: "recreate" };
|
|
2403
|
+
if (w.exists) a.conflict = "a file exists at this path now";
|
|
2404
|
+
actions.push(a);
|
|
2405
|
+
todo.push(async () => {
|
|
2406
|
+
await fsp9.writeFile(w.abs, await this.backups.readContent(id, e.file), { flag: "wx", mode: e.mode ?? 420 });
|
|
2407
|
+
});
|
|
2408
|
+
} else {
|
|
2409
|
+
const from = await this.validator.resolveForWrite(e.from, { mustExist: false });
|
|
2410
|
+
const a = { path: rel, action: "move-back" };
|
|
2411
|
+
if (from.exists) a.conflict = `a file exists at ${e.from}`;
|
|
2412
|
+
else if (cur !== e.beforeHash) a.conflict = "the moved file was changed or removed";
|
|
2413
|
+
actions.push(a);
|
|
2414
|
+
todo.push(async () => {
|
|
2415
|
+
await fsp9.rename(w.abs, from.abs);
|
|
2416
|
+
await removeEmptyDirs(this.root, e.createdDirs ?? []);
|
|
2417
|
+
});
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
const conflicts = actions.filter((a) => a.conflict).length;
|
|
2421
|
+
if (!confirmed || conflicts > 0) return { id, actions, restored: false, conflicts };
|
|
2422
|
+
for (const t of todo) await t();
|
|
2423
|
+
m.status = "restored";
|
|
2424
|
+
await this.backups.writeManifest(m);
|
|
2425
|
+
return { id, actions, restored: true, conflicts: 0 };
|
|
2426
|
+
}
|
|
2427
|
+
};
|
|
2428
|
+
|
|
2429
|
+
// src/filesystem/workspace.ts
|
|
2430
|
+
async function openWorkspace(input, settings, approvalMode, now) {
|
|
2431
|
+
const configured = settings().projectRoot;
|
|
2432
|
+
const explicit = configured !== null;
|
|
2433
|
+
let root;
|
|
2434
|
+
let detected = false;
|
|
2435
|
+
if (explicit) root = path10.resolve(input.cwd, configured);
|
|
2436
|
+
else {
|
|
2437
|
+
const found = await findProjectRoot(input.cwd, input.homedir);
|
|
2438
|
+
root = found.root;
|
|
2439
|
+
detected = found.detected;
|
|
2440
|
+
}
|
|
2441
|
+
const isFsRoot = path10.parse(root).root === root;
|
|
2442
|
+
const isHome = path10.resolve(input.homedir) === root;
|
|
2443
|
+
if (!explicit && (isFsRoot || isHome)) {
|
|
2444
|
+
return { manager: null, root, detected, explicit, problem: `zg does not use ${isHome ? "your home folder" : "the filesystem root"} as a project automatically. Start zg inside a project folder, or choose one with: zg config set filesystem.projectRoot <folder>` };
|
|
2445
|
+
}
|
|
2446
|
+
try {
|
|
2447
|
+
const manager = await FilesystemManager.open({ root, settings, approvalMode, dataDir: input.dataDir, ...now ? { now } : {} });
|
|
2448
|
+
return { manager, root: manager.root, detected, explicit, problem: null };
|
|
2449
|
+
} catch (err) {
|
|
2450
|
+
return { manager: null, root, detected, explicit, problem: err instanceof FsError ? `${err.message}${err.hint ? ` ${err.hint}` : ""}` : "The project folder could not be opened." };
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
// src/git/git-manager.ts
|
|
2455
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
2456
|
+
|
|
2457
|
+
// src/git/git-branch.ts
|
|
2458
|
+
var FMT = "--format=%(HEAD) %(refname:short) %(upstream:short) %(objectname:short) %(contents:subject)";
|
|
2459
|
+
function parseBranches(stdout, remote) {
|
|
2460
|
+
const out = [];
|
|
2461
|
+
for (const line of stdout.split("\n")) {
|
|
2462
|
+
if (line === "") continue;
|
|
2463
|
+
const [head = "", name = "", upstream = "", short = "", ...subjectParts] = line.split(" ");
|
|
2464
|
+
const subject = subjectParts.join(" ");
|
|
2465
|
+
if (name === "" || name.startsWith("(") || remote && name.endsWith("/HEAD")) continue;
|
|
2466
|
+
out.push({ name: safeText(name), current: head === "*", remote, upstream: upstream === "" ? null : safeText(upstream), shortHash: short, subject: clip(safeText(subject), 120) });
|
|
2467
|
+
}
|
|
2468
|
+
return out;
|
|
2469
|
+
}
|
|
2470
|
+
async function readBranches(runner, includeRemote) {
|
|
2471
|
+
const local = await runner.read(["branch", "--list", "--no-color", FMT], { purpose: "List local branches", maxBytes: 5e5 });
|
|
2472
|
+
if (!local.ok) {
|
|
2473
|
+
const e = explainGitFailure(local.stderr, "Git could not list branches.");
|
|
2474
|
+
throw new GitError("failed", e.message, e.hint);
|
|
2475
|
+
}
|
|
2476
|
+
const branches = parseBranches(local.stdout, false);
|
|
2477
|
+
if (includeRemote) {
|
|
2478
|
+
const remote = await runner.read(["branch", "--list", "-r", "--no-color", FMT], { purpose: "List remote-tracking branches", maxBytes: 5e5 });
|
|
2479
|
+
if (remote.ok) branches.push(...parseBranches(remote.stdout, true));
|
|
2480
|
+
}
|
|
2481
|
+
return branches;
|
|
2482
|
+
}
|
|
2483
|
+
async function changedTracked(ctx) {
|
|
2484
|
+
const s = await ctx.status();
|
|
2485
|
+
const tracked = s.entries.filter((e) => e.kind !== "untracked");
|
|
2486
|
+
return { tracked: tracked.length, total: s.entries.length, conflicted: s.conflicted.length, oid: s.repo.headOid, branch: s.repo.branch, names: tracked.slice(0, 10).map((e) => safeText(e.path)) };
|
|
2487
|
+
}
|
|
2488
|
+
async function planBranchCreate(ctx, rawName) {
|
|
2489
|
+
ctx.permissions.require("branch");
|
|
2490
|
+
const name = validateBranchName(rawName);
|
|
2491
|
+
const branches = await readBranches(ctx.runner, false);
|
|
2492
|
+
if (branches.some((b) => b.name === name)) throw new GitError("exists", `A branch named ${safeText(name)} already exists.`, "Choose another name, or switch to it with /git switch.");
|
|
2493
|
+
const st = await changedTracked(ctx);
|
|
2494
|
+
if (st.conflicted > 0) throw new GitError("conflicts", "There are unresolved merge conflicts; finish the merge first.");
|
|
2495
|
+
const prepared = await ctx.runner.prepareWrite("switch-create", ["switch", "-c", name], "Create and switch to the branch you approved", "Creates a new branch at the current commit and switches to it; your uncommitted changes come with you unchanged");
|
|
2496
|
+
const lines = [`New branch: ${safeText(name)}`, `Starts from: ${st.branch ? safeText(st.branch) : "the current commit (detached HEAD)"}${st.oid ? ` (${st.oid.slice(0, 7)})` : ""}`];
|
|
2497
|
+
const warnings = st.total > 0 ? [`${st.total} uncommitted change(s) stay in your working tree and move with you to the new branch.`] : [];
|
|
2498
|
+
return {
|
|
2499
|
+
id: ctx.newId(),
|
|
2500
|
+
kind: "branch-create",
|
|
2501
|
+
title: `Create branch ${name}`,
|
|
2502
|
+
lines,
|
|
2503
|
+
warnings,
|
|
2504
|
+
command: prepared.display,
|
|
2505
|
+
prepared,
|
|
2506
|
+
createdAt: Date.now(),
|
|
2507
|
+
guard: async () => {
|
|
2508
|
+
const now = await ctx.status();
|
|
2509
|
+
if (now.repo.headOid !== st.oid || (await readBranches(ctx.runner, false)).some((b) => b.name === name)) throw new GitError("stale", "The repository changed since you reviewed this, so no branch was created.");
|
|
2510
|
+
},
|
|
2511
|
+
describeResult: async (out) => {
|
|
2512
|
+
if (!out.ok) {
|
|
2513
|
+
const e = explainGitFailure(out.stderr, "Git could not create the branch.");
|
|
2514
|
+
throw new GitError("failed", e.message, e.hint);
|
|
2515
|
+
}
|
|
2516
|
+
return [`Created and switched to ${safeText(name)}. Nothing was pushed.`];
|
|
2517
|
+
}
|
|
2518
|
+
};
|
|
2519
|
+
}
|
|
2520
|
+
async function planSwitch(ctx, rawName) {
|
|
2521
|
+
ctx.permissions.require("branch");
|
|
2522
|
+
const name = validateBranchName(rawName);
|
|
2523
|
+
const branches = await readBranches(ctx.runner, false);
|
|
2524
|
+
const target = branches.find((b) => b.name === name);
|
|
2525
|
+
if (!target) throw new GitError("not-found", `There is no local branch named ${safeText(name)}.`, "Use /git branches to see them. zg does not create branches from remote ones automatically.");
|
|
2526
|
+
if (target.current) throw new GitError("nothing-to-do", `You are already on ${safeText(name)}.`);
|
|
2527
|
+
const st = await changedTracked(ctx);
|
|
2528
|
+
if (st.conflicted > 0) throw new GitError("conflicts", "There are unresolved merge conflicts; finish the merge first.");
|
|
2529
|
+
if (st.tracked > 0) {
|
|
2530
|
+
throw new GitError(
|
|
2531
|
+
"dirty-tree",
|
|
2532
|
+
`You have uncommitted changes to ${st.tracked} tracked file(s) (${st.names.join(", ")}${st.tracked > st.names.length ? ", ..." : ""}), so switching branches could lose or mix up your work.`,
|
|
2533
|
+
"Commit them (/git review), or stash or discard them yourself first. zg never forces a switch."
|
|
2534
|
+
);
|
|
2535
|
+
}
|
|
2536
|
+
const prepared = await ctx.runner.prepareWrite("switch", ["switch", name], "Switch to the branch you approved", "Moves HEAD and the working tree to that branch; no files with changes are overwritten");
|
|
2537
|
+
return {
|
|
2538
|
+
id: ctx.newId(),
|
|
2539
|
+
kind: "branch-switch",
|
|
2540
|
+
title: `Switch to ${name}`,
|
|
2541
|
+
lines: [`From: ${st.branch ? safeText(st.branch) : "detached HEAD"}`, `To: ${safeText(name)} (${target.shortHash})`, "Your working tree has no uncommitted changes to tracked files."],
|
|
2542
|
+
warnings: st.total > 0 ? [`${st.total} untracked file(s) stay where they are (Git stops the switch if one would be overwritten).`] : [],
|
|
2543
|
+
command: prepared.display,
|
|
2544
|
+
prepared,
|
|
2545
|
+
createdAt: Date.now(),
|
|
2546
|
+
guard: async () => {
|
|
2547
|
+
const now = await changedTracked(ctx);
|
|
2548
|
+
if (now.tracked > 0 || now.oid !== st.oid) throw new GitError("stale", "The repository changed since you reviewed this, so the branch was not switched.");
|
|
2549
|
+
},
|
|
2550
|
+
describeResult: async (out) => {
|
|
2551
|
+
if (!out.ok) {
|
|
2552
|
+
const e = explainGitFailure(out.stderr, "Git could not switch branches.");
|
|
2553
|
+
throw new GitError("failed", e.message, e.hint);
|
|
2554
|
+
}
|
|
2555
|
+
return [`Switched to ${safeText(name)}.`];
|
|
2556
|
+
}
|
|
2557
|
+
};
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
// src/git/git-log.ts
|
|
2561
|
+
var RS = "";
|
|
2562
|
+
var US = "";
|
|
2563
|
+
var LOG_FORMAT = `--format=%x1e%H%x1f%h%x1f%an%x1f%aI%x1f%s`;
|
|
2564
|
+
function shortDate(iso) {
|
|
2565
|
+
const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/.exec(iso);
|
|
2566
|
+
return m ? `${m[1]} ${m[2]}` : safeText(iso).slice(0, 16);
|
|
2567
|
+
}
|
|
2568
|
+
function parseLog(stdout) {
|
|
2569
|
+
const out = [];
|
|
2570
|
+
for (const rec of stdout.split(RS)) {
|
|
2571
|
+
if (rec.trim() === "") continue;
|
|
2572
|
+
const [first = "", ...rest] = rec.split("\n");
|
|
2573
|
+
const [hash = "", short = "", author = "", date = "", subject = ""] = first.split(US);
|
|
2574
|
+
if (!/^[0-9a-f]{40,64}$/.test(hash)) continue;
|
|
2575
|
+
const info = { hash, shortHash: short, author: clip(safeText(author), 80), date: shortDate(date), subject: clip(safeText(subject), 200) };
|
|
2576
|
+
const stat = /(\d+) files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?/.exec(rest.join("\n"));
|
|
2577
|
+
if (stat) {
|
|
2578
|
+
info.filesChanged = Number(stat[1]);
|
|
2579
|
+
info.insertions = Number(stat[2] ?? 0);
|
|
2580
|
+
info.deletions = Number(stat[3] ?? 0);
|
|
2581
|
+
}
|
|
2582
|
+
out.push(info);
|
|
2583
|
+
}
|
|
2584
|
+
return out;
|
|
2585
|
+
}
|
|
2586
|
+
async function readLog(runner, settings, opts = {}) {
|
|
2587
|
+
const limit = Math.min(Math.max(1, Math.floor(opts.limit ?? settings.logLimit)), 200);
|
|
2588
|
+
const args = ["log", `--max-count=${limit}`, "--no-color", "--no-ext-diff", "--shortstat", LOG_FORMAT];
|
|
2589
|
+
if (opts.rev) args.push(validateRevision(opts.rev));
|
|
2590
|
+
args.push("--");
|
|
2591
|
+
if (opts.path) args.push(validateRelPath(opts.path));
|
|
2592
|
+
const r = await runner.read(args, { purpose: "Read the commit history", maxBytes: 1e6 });
|
|
2593
|
+
if (!r.ok) {
|
|
2594
|
+
if (/does not have any commits yet|unknown revision/i.test(r.stderr)) return { commits: [], limit };
|
|
2595
|
+
const e = explainGitFailure(r.stderr, "Git could not read the history.");
|
|
2596
|
+
throw new GitError("failed", e.message, e.hint);
|
|
2597
|
+
}
|
|
2598
|
+
return { commits: parseLog(r.stdout), limit };
|
|
2599
|
+
}
|
|
2600
|
+
async function readCommit(runner, rev) {
|
|
2601
|
+
const r = await runner.read(["show", "--no-ext-diff", "--no-textconv", "--no-color", "--numstat", "--format=%x1e%H%x1f%h%x1f%an%x1f%aI%x1f%s%x1f%b", validateRevision(rev), "--"], { purpose: "Read one commit", maxBytes: 5e5 });
|
|
2602
|
+
if (!r.ok) {
|
|
2603
|
+
const e = explainGitFailure(r.stderr, "Git could not read that commit.");
|
|
2604
|
+
throw new GitError("failed", e.message, e.hint);
|
|
2605
|
+
}
|
|
2606
|
+
const rec = r.stdout.split(RS).find((x) => x.trim() !== "") ?? "";
|
|
2607
|
+
const lines = rec.split("\n");
|
|
2608
|
+
const [hash = "", short = "", author = "", date = "", subject = "", ...bodyFirst] = (lines[0] ?? "").split(US);
|
|
2609
|
+
if (!/^[0-9a-f]{40,64}$/.test(hash)) throw new GitError("not-found", "That commit was not found.");
|
|
2610
|
+
const bodyLines = [];
|
|
2611
|
+
const files = [];
|
|
2612
|
+
for (const l of [bodyFirst.join(US), ...lines.slice(1)]) {
|
|
2613
|
+
const m = /^(\d+|-)\t(\d+|-)\t(.+)$/.exec(l);
|
|
2614
|
+
if (m) files.push({ path: safeText(m[3]), insertions: m[1] === "-" ? null : Number(m[1]), deletions: m[2] === "-" ? null : Number(m[2]) });
|
|
2615
|
+
else bodyLines.push(l);
|
|
2616
|
+
}
|
|
2617
|
+
const body = bodyLines.map((l) => safeText(l)).join("\n").trim();
|
|
2618
|
+
return {
|
|
2619
|
+
hash,
|
|
2620
|
+
shortHash: short,
|
|
2621
|
+
author: clip(safeText(author), 80),
|
|
2622
|
+
date: shortDate(date),
|
|
2623
|
+
subject: clip(safeText(subject), 200),
|
|
2624
|
+
...body ? { body: clip(body, 2e3) } : {},
|
|
2625
|
+
filesChanged: files.length,
|
|
2626
|
+
insertions: files.reduce((n, f) => n + (f.insertions ?? 0), 0),
|
|
2627
|
+
deletions: files.reduce((n, f) => n + (f.deletions ?? 0), 0),
|
|
2628
|
+
files: files.slice(0, 200)
|
|
2629
|
+
};
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
// src/git/git-detection.ts
|
|
2633
|
+
var MIN_GIT = [2, 31];
|
|
2634
|
+
function parseGitVersion(text3) {
|
|
2635
|
+
const m = /git version (\d+)\.(\d+)(?:\.(\d+))?/.exec(text3);
|
|
2636
|
+
if (!m) return null;
|
|
2637
|
+
return { version: `${m[1]}.${m[2]}${m[3] ? `.${m[3]}` : ""}`, major: Number(m[1]), minor: Number(m[2]) };
|
|
2638
|
+
}
|
|
2639
|
+
function parseBranchHeader(stdout) {
|
|
2640
|
+
let branch = null;
|
|
2641
|
+
let detached = false;
|
|
2642
|
+
let oid = null;
|
|
2643
|
+
let unborn = false;
|
|
2644
|
+
let upstream = null;
|
|
2645
|
+
let ahead = null;
|
|
2646
|
+
let behind = null;
|
|
2647
|
+
for (const line of stdout.split("\n")) {
|
|
2648
|
+
if (!line.startsWith("# ")) continue;
|
|
2649
|
+
const [key = "", ...rest] = line.slice(2).split(" ");
|
|
2650
|
+
const value = rest.join(" ");
|
|
2651
|
+
if (key === "branch.oid") {
|
|
2652
|
+
unborn = value === "(initial)";
|
|
2653
|
+
oid = unborn ? null : value;
|
|
2654
|
+
} else if (key === "branch.head") {
|
|
2655
|
+
detached = value === "(detached)";
|
|
2656
|
+
branch = detached ? null : value;
|
|
2657
|
+
} else if (key === "branch.upstream") upstream = value;
|
|
2658
|
+
else if (key === "branch.ab") {
|
|
2659
|
+
const m = /^\+(\d+) -(\d+)$/.exec(value);
|
|
2660
|
+
if (m) {
|
|
2661
|
+
ahead = Number(m[1]);
|
|
2662
|
+
behind = Number(m[2]);
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
return { branch, detached, oid, unborn, upstream, ahead, behind };
|
|
2667
|
+
}
|
|
2668
|
+
async function detectRepository(runner, projectRoot) {
|
|
2669
|
+
let versionText;
|
|
2670
|
+
try {
|
|
2671
|
+
const v2 = await runner.read(["--version"], { purpose: "Check that Git is installed" });
|
|
2672
|
+
versionText = v2.stdout;
|
|
2673
|
+
} catch (err) {
|
|
2674
|
+
if (err instanceof GitError && err.code === "not-installed") return { state: "git-missing", reason: err.message };
|
|
2675
|
+
if (err instanceof GitError && (err.code === "denied" || err.code === "blocked" || err.code === "no-workspace")) throw err;
|
|
2676
|
+
return { state: "git-missing", reason: err instanceof GitError ? err.message : "Git could not be started." };
|
|
2677
|
+
}
|
|
2678
|
+
const v = parseGitVersion(versionText);
|
|
2679
|
+
if (!v) return { state: "git-missing", reason: "The program called git did not answer like Git." };
|
|
2680
|
+
if (v.major < MIN_GIT[0] || v.major === MIN_GIT[0] && v.minor < MIN_GIT[1]) {
|
|
2681
|
+
return { state: "git-too-old", version: v.version, reason: `Git ${v.version} is too old; zg needs Git ${MIN_GIT[0]}.${MIN_GIT[1]} or newer to apply its safety settings.` };
|
|
2682
|
+
}
|
|
2683
|
+
const probe = await runner.read(["rev-parse", "--is-bare-repository", "--is-inside-work-tree"], { purpose: "Check whether this folder is in a Git repository" });
|
|
2684
|
+
if (!probe.ok) {
|
|
2685
|
+
if (/not a git repository/i.test(probe.stderr)) return { state: "not-a-repo" };
|
|
2686
|
+
if (/dubious ownership|safe\.directory/i.test(probe.stderr)) return { state: "invalid", reason: "Git refuses to use this folder because it is owned by another user (safe.directory)." };
|
|
2687
|
+
return { state: "invalid", reason: "Git could not read this repository." };
|
|
2688
|
+
}
|
|
2689
|
+
const [bare = "", inside = ""] = probe.stdout.split("\n").map((l) => l.trim());
|
|
2690
|
+
if (bare === "true") return { state: "bare" };
|
|
2691
|
+
if (inside !== "true") return { state: "invalid", reason: "This folder is inside the .git directory, not in a working tree." };
|
|
2692
|
+
const where = await runner.read(["rev-parse", "--path-format=absolute", "--show-toplevel", "--show-prefix", "--git-dir", "--git-common-dir"], { purpose: "Find the repository root" });
|
|
2693
|
+
const lines = where.stdout.split("\n");
|
|
2694
|
+
const root = unquoteGitPath((lines[0] ?? "").trim());
|
|
2695
|
+
if (!where.ok || root === "") return { state: "invalid", reason: "Git did not report where the repository root is." };
|
|
2696
|
+
const prefix = (lines[1] ?? "").trim();
|
|
2697
|
+
const gitDir = (lines[2] ?? "").trim();
|
|
2698
|
+
const common = (lines[3] ?? "").trim();
|
|
2699
|
+
const head = await runner.read(["status", "--porcelain=v2", "--branch", "--untracked-files=no", "--", "."], { purpose: "Read the current branch", maxBytes: 1e5 });
|
|
2700
|
+
if (!head.ok) return { state: "invalid", reason: "Git could not read the repository status." };
|
|
2701
|
+
const h = parseBranchHeader(head.stdout);
|
|
2702
|
+
const repo = {
|
|
2703
|
+
root,
|
|
2704
|
+
prefix,
|
|
2705
|
+
branch: h.branch,
|
|
2706
|
+
detached: h.detached,
|
|
2707
|
+
headOid: h.oid,
|
|
2708
|
+
unborn: h.unborn,
|
|
2709
|
+
worktree: gitDir !== "" && common !== "" && gitDir !== common,
|
|
2710
|
+
gitVersion: v.version
|
|
2711
|
+
};
|
|
2712
|
+
void projectRoot;
|
|
2713
|
+
return { state: "ok", repo };
|
|
2714
|
+
}
|
|
2715
|
+
|
|
2716
|
+
// src/git/git-status.ts
|
|
2717
|
+
function stripPrefix(path15, prefix) {
|
|
2718
|
+
return prefix !== "" && path15.startsWith(prefix) ? path15.slice(prefix.length) : path15;
|
|
2719
|
+
}
|
|
2720
|
+
function kindOf(x, y) {
|
|
2721
|
+
const c = x !== "." ? x : y;
|
|
2722
|
+
switch (c) {
|
|
2723
|
+
case "A":
|
|
2724
|
+
return "added";
|
|
2725
|
+
case "D":
|
|
2726
|
+
return "deleted";
|
|
2727
|
+
case "R":
|
|
2728
|
+
return "renamed";
|
|
2729
|
+
case "C":
|
|
2730
|
+
return "copied";
|
|
2731
|
+
case "T":
|
|
2732
|
+
return "typechange";
|
|
2733
|
+
default:
|
|
2734
|
+
return "modified";
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
var CONFLICT_TEXT = {
|
|
2738
|
+
DD: "both deleted",
|
|
2739
|
+
AU: "added by us",
|
|
2740
|
+
UD: "deleted by them",
|
|
2741
|
+
UA: "added by them",
|
|
2742
|
+
DU: "deleted by us",
|
|
2743
|
+
AA: "both added",
|
|
2744
|
+
UU: "both modified"
|
|
2745
|
+
};
|
|
2746
|
+
function describeConflictCode(code) {
|
|
2747
|
+
return CONFLICT_TEXT[code] ?? "unmerged";
|
|
2748
|
+
}
|
|
2749
|
+
function parseStatus(stdout, prefix) {
|
|
2750
|
+
const header = parseBranchHeader(stdout);
|
|
2751
|
+
const entries = [];
|
|
2752
|
+
for (const line of stdout.split("\n")) {
|
|
2753
|
+
if (line === "" || line.startsWith("# ")) continue;
|
|
2754
|
+
const tag = line[0];
|
|
2755
|
+
if (tag === "?") {
|
|
2756
|
+
entries.push({ path: stripPrefix(unquoteGitPath(line.slice(2)), prefix), index: "?", worktree: "?", kind: "untracked", staged: false, unstaged: true });
|
|
2757
|
+
} else if (tag === "1") {
|
|
2758
|
+
const f = splitFields(line, 8);
|
|
2759
|
+
if (!f) continue;
|
|
2760
|
+
const xy = f[1];
|
|
2761
|
+
const x = xy[0];
|
|
2762
|
+
const y = xy[1];
|
|
2763
|
+
entries.push({ path: stripPrefix(unquoteGitPath(f[8]), prefix), index: x, worktree: y, kind: kindOf(x, y), staged: x !== ".", unstaged: y !== "." });
|
|
2764
|
+
} else if (tag === "2") {
|
|
2765
|
+
const f = splitFields(line, 9);
|
|
2766
|
+
if (!f) continue;
|
|
2767
|
+
const xy = f[1];
|
|
2768
|
+
const x = xy[0];
|
|
2769
|
+
const y = xy[1];
|
|
2770
|
+
const [p = "", orig = ""] = f[9].split(" ");
|
|
2771
|
+
entries.push({ path: stripPrefix(unquoteGitPath(p), prefix), origPath: stripPrefix(unquoteGitPath(orig), prefix), index: x, worktree: y, kind: kindOf(x, y), staged: x !== ".", unstaged: y !== "." });
|
|
2772
|
+
} else if (tag === "u") {
|
|
2773
|
+
const f = splitFields(line, 10);
|
|
2774
|
+
if (!f) continue;
|
|
2775
|
+
const xy = f[1];
|
|
2776
|
+
entries.push({ path: stripPrefix(unquoteGitPath(f[10]), prefix), index: xy[0], worktree: xy[1], kind: "conflicted", staged: false, unstaged: true, conflict: xy });
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
return { entries, header };
|
|
2780
|
+
}
|
|
2781
|
+
function splitFields(line, n) {
|
|
2782
|
+
const out = [];
|
|
2783
|
+
let rest = line;
|
|
2784
|
+
for (let i = 0; i < n; i++) {
|
|
2785
|
+
const sp = rest.indexOf(" ");
|
|
2786
|
+
if (sp < 0) return null;
|
|
2787
|
+
out.push(rest.slice(0, sp));
|
|
2788
|
+
rest = rest.slice(sp + 1);
|
|
2789
|
+
}
|
|
2790
|
+
out.push(rest);
|
|
2791
|
+
return out;
|
|
2792
|
+
}
|
|
2793
|
+
function summarise(entries) {
|
|
2794
|
+
const c = { modified: 0, added: 0, deleted: 0, renamed: 0, untracked: 0, staged: 0, conflicted: 0 };
|
|
2795
|
+
for (const e of entries) {
|
|
2796
|
+
if (e.kind === "untracked") c.untracked++;
|
|
2797
|
+
else if (e.kind === "conflicted") c.conflicted++;
|
|
2798
|
+
else {
|
|
2799
|
+
if (e.staged) c.staged++;
|
|
2800
|
+
if (e.unstaged) c.modified++;
|
|
2801
|
+
if (e.kind === "added" && !e.unstaged) c.added++;
|
|
2802
|
+
if (e.kind === "deleted") c.deleted++;
|
|
2803
|
+
if (e.kind === "renamed" || e.kind === "copied") c.renamed++;
|
|
2804
|
+
}
|
|
2805
|
+
}
|
|
2806
|
+
return c;
|
|
2807
|
+
}
|
|
2808
|
+
async function currentOperation(runner) {
|
|
2809
|
+
const probes = [
|
|
2810
|
+
["MERGE_HEAD", "merge"],
|
|
2811
|
+
["REBASE_HEAD", "rebase"],
|
|
2812
|
+
["CHERRY_PICK_HEAD", "cherry-pick"],
|
|
2813
|
+
["REVERT_HEAD", "revert"]
|
|
2814
|
+
];
|
|
2815
|
+
for (const [ref, op] of probes) {
|
|
2816
|
+
const r = await runner.read(["rev-parse", "-q", "--verify", ref], { purpose: `Check whether a ${op} is in progress`, maxBytes: 1e4 });
|
|
2817
|
+
if (r.ok) return op;
|
|
2818
|
+
}
|
|
2819
|
+
return null;
|
|
2820
|
+
}
|
|
2821
|
+
async function readStatus(runner, repo, settings, opts = {}) {
|
|
2822
|
+
const r = await runner.read(["status", "--porcelain=v2", "--branch", "--untracked-files=all", "--", "."], { purpose: "Read the repository status", maxBytes: 2e6 });
|
|
2823
|
+
if (!r.ok) {
|
|
2824
|
+
const e = explainGitFailure(r.stderr, "Git could not read the repository status.");
|
|
2825
|
+
throw new GitError("failed", e.message, e.hint);
|
|
2826
|
+
}
|
|
2827
|
+
const { entries, header } = parseStatus(r.stdout, repo.prefix);
|
|
2828
|
+
const current = { ...repo, branch: header.branch, detached: header.detached, headOid: header.oid, unborn: header.unborn };
|
|
2829
|
+
const operation = await currentOperation(runner);
|
|
2830
|
+
const shown = opts.all ? entries : entries.slice(0, settings.statusMaxFiles);
|
|
2831
|
+
return {
|
|
2832
|
+
repo: current,
|
|
2833
|
+
upstream: header.upstream,
|
|
2834
|
+
ahead: header.ahead,
|
|
2835
|
+
behind: header.behind,
|
|
2836
|
+
entries: shown,
|
|
2837
|
+
staged: shown.filter((e) => e.staged && e.kind !== "conflicted"),
|
|
2838
|
+
unstaged: shown.filter((e) => e.unstaged && e.kind !== "untracked" && e.kind !== "conflicted"),
|
|
2839
|
+
untracked: shown.filter((e) => e.kind === "untracked"),
|
|
2840
|
+
conflicted: shown.filter((e) => e.kind === "conflicted"),
|
|
2841
|
+
operation,
|
|
2842
|
+
truncated: entries.length > shown.length || r.truncated,
|
|
2843
|
+
totalEntries: entries.length,
|
|
2844
|
+
counts: summarise(entries)
|
|
2845
|
+
};
|
|
2846
|
+
}
|
|
2847
|
+
function displayPath(e) {
|
|
2848
|
+
const p = safeText(e.path);
|
|
2849
|
+
return e.origPath ? `${safeText(e.origPath)} -> ${p}` : p;
|
|
2850
|
+
}
|
|
2851
|
+
|
|
2852
|
+
// src/git/git-commit.ts
|
|
2853
|
+
async function planCommit(ctx, rawMessage) {
|
|
2854
|
+
ctx.permissions.require("commit");
|
|
2855
|
+
const msg = validateCommitMessage(rawMessage);
|
|
2856
|
+
const status = await ctx.status();
|
|
2857
|
+
if (status.conflicted.length > 0) throw new GitError("conflicts", `${status.conflicted.length} file(s) have unresolved merge conflicts, so a commit is not possible.`, "Inspect them with /git conflicts.");
|
|
2858
|
+
if (status.operation && status.operation !== "merge") throw new GitError("blocked", `A ${status.operation} is in progress. Finish or abort it in your own terminal first.`);
|
|
2859
|
+
const staged = status.entries.filter((e) => e.staged);
|
|
2860
|
+
if (staged.length === 0) throw new GitError("nothing-to-do", "Nothing is staged, so there is nothing to commit.", "Stage files first with /git stage <file>. zg never stages or commits everything for you.");
|
|
2861
|
+
for (const e of staged) {
|
|
2862
|
+
const secret = secretPathReason(e.path);
|
|
2863
|
+
if (secret) throw new GitError("protected-path", `${safeText(e.path)} is staged but is ${secret}. zg will not commit it.`, "Unstage it with /git unstage, or commit it yourself if you are sure it is not a secret.");
|
|
2864
|
+
}
|
|
2865
|
+
const diff = await ctx.diff({ kind: "staged" });
|
|
2866
|
+
const headBefore = status.repo.headOid;
|
|
2867
|
+
const notIncluded = status.entries.filter((e) => e.unstaged);
|
|
2868
|
+
const warnings = [...msg.warnings];
|
|
2869
|
+
if (status.repo.detached) warnings.push("HEAD is detached: this commit will not belong to any branch.");
|
|
2870
|
+
if (status.operation === "merge") warnings.push("A merge is in progress: this commit will complete it.");
|
|
2871
|
+
if (status.repo.unborn) warnings.push("This will be the first commit of the repository.");
|
|
2872
|
+
if (diff.files.some((f) => f.binary)) warnings.push("The staged files include binary files whose contents are not shown.");
|
|
2873
|
+
const lines = [
|
|
2874
|
+
"Message:",
|
|
2875
|
+
...msg.full.split("\n").map((l) => ` ${safeText(l)}`),
|
|
2876
|
+
"",
|
|
2877
|
+
`Files: ${staged.length} changed${diff.filesChanged ? `, ${diff.insertions} insertion(s), ${diff.deletions} deletion(s)` : ""}`,
|
|
2878
|
+
...staged.slice(0, 40).map((e) => ` ${(e.index === "?" ? "A" : e.index).padEnd(2)} ${displayPath(e)}`),
|
|
2879
|
+
...staged.length > 40 ? [` ... and ${staged.length - 40} more`] : [],
|
|
2880
|
+
...notIncluded.length > 0 ? ["", `Not included: ${notIncluded.length} file(s) with unstaged or untracked changes stay as they are.`] : []
|
|
2881
|
+
];
|
|
2882
|
+
const args = ["commit", "-m", msg.subject, ...msg.body ? ["-m", msg.body] : []];
|
|
2883
|
+
const prepared = await ctx.runner.prepareWrite("commit", args, "Create the commit you approved", "Records exactly the staged changes as one new commit on the current branch; nothing else is included, nothing is amended or pushed");
|
|
2884
|
+
return {
|
|
2885
|
+
id: ctx.newId(),
|
|
2886
|
+
kind: "commit",
|
|
2887
|
+
title: "Create commit",
|
|
2888
|
+
lines,
|
|
2889
|
+
warnings,
|
|
2890
|
+
command: prepared.display,
|
|
2891
|
+
prepared,
|
|
2892
|
+
createdAt: Date.now(),
|
|
2893
|
+
guard: async () => {
|
|
2894
|
+
const now = await ctx.status();
|
|
2895
|
+
const d = await ctx.diff({ kind: "staged" });
|
|
2896
|
+
if (now.repo.headOid !== headBefore || d.digest !== diff.digest) throw new GitError("stale", "The staged changes or the branch changed since you reviewed this commit, so nothing was committed.", "Review the commit again.");
|
|
2897
|
+
},
|
|
2898
|
+
describeResult: async (out) => {
|
|
2899
|
+
if (!out.ok) {
|
|
2900
|
+
const e = explainGitFailure(out.stderr, "Git could not create the commit.");
|
|
2901
|
+
throw new GitError("failed", e.message, e.hint);
|
|
2902
|
+
}
|
|
2903
|
+
const c = await readCommit(ctx.runner, "HEAD");
|
|
2904
|
+
return [`Commit ${c.shortHash} created: ${c.subject}`, `Full hash: ${c.hash}`, `${c.filesChanged ?? 0} file(s) changed, ${c.insertions ?? 0} insertion(s), ${c.deletions ?? 0} deletion(s). Nothing was pushed.`];
|
|
2905
|
+
}
|
|
2906
|
+
};
|
|
2907
|
+
}
|
|
2908
|
+
|
|
2909
|
+
// src/git/git-conflicts.ts
|
|
2910
|
+
function findConflictRegions(content, maxRegions, previewLines) {
|
|
2911
|
+
const lines = content.split(/\r\n|\n|\r/);
|
|
2912
|
+
const regions = [];
|
|
2913
|
+
let total = 0;
|
|
2914
|
+
let problem = null;
|
|
2915
|
+
let state = "none";
|
|
2916
|
+
let start = 0;
|
|
2917
|
+
let ours = [];
|
|
2918
|
+
let base = [];
|
|
2919
|
+
let theirs = [];
|
|
2920
|
+
let oursLabel = "";
|
|
2921
|
+
let theirsLabel = "";
|
|
2922
|
+
const cut = (a) => a.length > previewLines ? [...a.slice(0, previewLines), `... (${a.length - previewLines} more lines)`] : a;
|
|
2923
|
+
lines.forEach((line, i) => {
|
|
2924
|
+
if (/^<{7}( |$)/.test(line)) {
|
|
2925
|
+
if (state !== "none") problem = "Conflict markers are nested or unbalanced";
|
|
2926
|
+
state = "ours";
|
|
2927
|
+
start = i + 1;
|
|
2928
|
+
ours = [];
|
|
2929
|
+
base = [];
|
|
2930
|
+
theirs = [];
|
|
2931
|
+
oursLabel = line.slice(8);
|
|
2932
|
+
theirsLabel = "";
|
|
2933
|
+
} else if (/^\|{7}( |$)/.test(line) && state === "ours") state = "base";
|
|
2934
|
+
else if (/^={7}$/.test(line) && (state === "ours" || state === "base")) state = "theirs";
|
|
2935
|
+
else if (/^>{7}( |$)/.test(line) && state === "theirs") {
|
|
2936
|
+
total++;
|
|
2937
|
+
theirsLabel = line.slice(8);
|
|
2938
|
+
if (regions.length < maxRegions) {
|
|
2939
|
+
regions.push({ startLine: start, endLine: i + 1, ours: cut(ours), theirs: cut(theirs), base: base.length > 0 ? cut(base) : null, oursLabel: clip(safeText(oursLabel), 60), theirsLabel: clip(safeText(theirsLabel), 60) });
|
|
2940
|
+
}
|
|
2941
|
+
state = "none";
|
|
2942
|
+
} else if (state === "ours") ours.push(safeText(line));
|
|
2943
|
+
else if (state === "base") base.push(safeText(line));
|
|
2944
|
+
else if (state === "theirs") theirs.push(safeText(line));
|
|
2945
|
+
});
|
|
2946
|
+
if (state !== "none") problem = "A conflict region was not closed (the file ends inside it)";
|
|
2947
|
+
return { regions, total, problem };
|
|
2948
|
+
}
|
|
2949
|
+
async function inspectConflicts(entries, settings, readFile) {
|
|
2950
|
+
const files = [];
|
|
2951
|
+
const notes = [];
|
|
2952
|
+
for (const e of entries) {
|
|
2953
|
+
const base = { path: safeText(e.path), code: e.conflict ?? "UU", description: describeConflictCode(e.conflict ?? "UU") };
|
|
2954
|
+
const secret = secretPathReason(e.path);
|
|
2955
|
+
if (secret) {
|
|
2956
|
+
files.push({ ...base, regions: [], regionsShown: 0, hidden: `contents hidden: this is ${secret}` });
|
|
2957
|
+
continue;
|
|
2958
|
+
}
|
|
2959
|
+
if (!["UU", "AA"].includes(base.code)) {
|
|
2960
|
+
files.push({ ...base, regions: [], regionsShown: 0, hidden: `${base.description}: there are no conflict markers to show` });
|
|
2961
|
+
continue;
|
|
2962
|
+
}
|
|
2963
|
+
try {
|
|
2964
|
+
const text3 = await readFile(e.path);
|
|
2965
|
+
const f = findConflictRegions(text3, settings.conflictMaxRegions, settings.conflictPreviewLines);
|
|
2966
|
+
if (f.problem) notes.push(`${base.path}: ${f.problem}.`);
|
|
2967
|
+
files.push({ ...base, regions: f.regions, regionsShown: f.regions.length, hidden: null });
|
|
2968
|
+
if (f.total > f.regions.length) notes.push(`${base.path}: showing ${f.regions.length} of ${f.total} conflict regions.`);
|
|
2969
|
+
if (f.total === 0) notes.push(`${base.path}: Git lists it as conflicted but no markers were found (they may already be removed; stage it when you are done).`);
|
|
2970
|
+
} catch {
|
|
2971
|
+
files.push({ ...base, regions: [], regionsShown: 0, hidden: "the file could not be read (it may be too large, binary or protected)" });
|
|
2972
|
+
}
|
|
2973
|
+
}
|
|
2974
|
+
return { files, notes };
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
// src/git/git-diff.ts
|
|
2978
|
+
import { createHash as createHash3 } from "crypto";
|
|
2979
|
+
var BASE = ["--no-ext-diff", "--no-textconv", "--no-color", "--find-renames", "--no-relative", "--unified=3", "--src-prefix=a/", "--dst-prefix=b/"];
|
|
2980
|
+
function diffArgs(target) {
|
|
2981
|
+
const paths = (target.paths ?? []).map(validateRelPath);
|
|
2982
|
+
const tail = ["--", ...paths.length > 0 ? paths : ["."]];
|
|
2983
|
+
switch (target.kind) {
|
|
2984
|
+
case "working":
|
|
2985
|
+
return { args: ["diff", ...BASE, ...tail], title: paths.length ? `Working tree changes (${paths.length} file${paths.length > 1 ? "s" : ""})` : "Working tree changes (not yet staged)" };
|
|
2986
|
+
case "staged":
|
|
2987
|
+
return { args: ["diff", "--cached", ...BASE, ...tail], title: paths.length ? `Staged changes (${paths.length} file${paths.length > 1 ? "s" : ""})` : "Staged changes (will be in the next commit)" };
|
|
2988
|
+
case "compare": {
|
|
2989
|
+
const r = parseRange(target.range);
|
|
2990
|
+
if (r) return { args: ["diff", ...BASE, r.dots === ".." ? r.from : `${r.from}...${r.to}`, ...r.dots === ".." ? [r.to] : [], ...tail], title: `Comparison ${r.from}${r.dots}${r.to}` };
|
|
2991
|
+
const one = validateRevision(target.range);
|
|
2992
|
+
return { args: ["diff", ...BASE, one, ...tail], title: `Changes since ${one}` };
|
|
2993
|
+
}
|
|
2994
|
+
case "commit": {
|
|
2995
|
+
const rev = validateRevision(target.rev);
|
|
2996
|
+
return { args: ["show", ...BASE, "--format=", rev, ...tail], title: `Commit ${rev}` };
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
}
|
|
3000
|
+
function sameHalves(header) {
|
|
3001
|
+
const len = header.length;
|
|
3002
|
+
if (len < 5 || (len - 5) % 2 !== 0) return null;
|
|
3003
|
+
const n = (len - 5) / 2;
|
|
3004
|
+
const left = header.slice(0, 2 + n);
|
|
3005
|
+
const right = header.slice(3 + n);
|
|
3006
|
+
return left.startsWith("a/") && right.startsWith("b/") && left.slice(2) === right.slice(2) ? left.slice(2) : null;
|
|
3007
|
+
}
|
|
3008
|
+
function parseUnifiedDiff(text3, limits) {
|
|
3009
|
+
const files = [];
|
|
3010
|
+
let cur = null;
|
|
3011
|
+
let inHunk = false;
|
|
3012
|
+
let shown = 0;
|
|
3013
|
+
let totalFiles = 0;
|
|
3014
|
+
let omittedFiles = 0;
|
|
3015
|
+
let insertions = 0;
|
|
3016
|
+
let deletions = 0;
|
|
3017
|
+
let collecting = false;
|
|
3018
|
+
const start = (header) => {
|
|
3019
|
+
totalFiles++;
|
|
3020
|
+
inHunk = false;
|
|
3021
|
+
const p = sameHalves(header);
|
|
3022
|
+
const path15 = unquoteGitPath(p ?? header.replace(/^"?a\//, "").replace(/ "?b\/.*$/, ""));
|
|
3023
|
+
const file = { path: path15, status: "modified", binary: false, hidden: null, insertions: 0, deletions: 0, lines: [], truncated: false };
|
|
3024
|
+
const secret = secretPathReason(path15);
|
|
3025
|
+
if (secret) file.hidden = `contents hidden: this is ${secret}`;
|
|
3026
|
+
if (files.length >= limits.maxFiles) {
|
|
3027
|
+
omittedFiles++;
|
|
3028
|
+
collecting = false;
|
|
3029
|
+
cur = file;
|
|
3030
|
+
return;
|
|
3031
|
+
}
|
|
3032
|
+
collecting = true;
|
|
3033
|
+
files.push(file);
|
|
3034
|
+
cur = file;
|
|
3035
|
+
};
|
|
3036
|
+
for (const line of text3.split("\n")) {
|
|
3037
|
+
if (line.startsWith("diff --git ")) {
|
|
3038
|
+
start(line.slice("diff --git ".length));
|
|
3039
|
+
continue;
|
|
3040
|
+
}
|
|
3041
|
+
const f = cur;
|
|
3042
|
+
if (!f) continue;
|
|
3043
|
+
if (!inHunk) {
|
|
3044
|
+
if (line.startsWith("new file mode")) f.status = "added";
|
|
3045
|
+
else if (line.startsWith("deleted file mode")) f.status = "deleted";
|
|
3046
|
+
else if (line.startsWith("rename from ")) {
|
|
3047
|
+
f.status = "renamed";
|
|
3048
|
+
f.oldPath = unquoteGitPath(line.slice("rename from ".length));
|
|
3049
|
+
} else if (line.startsWith("rename to ")) f.path = unquoteGitPath(line.slice("rename to ".length));
|
|
3050
|
+
else if (line.startsWith("copy from ")) {
|
|
3051
|
+
f.status = "copied";
|
|
3052
|
+
f.oldPath = unquoteGitPath(line.slice("copy from ".length));
|
|
3053
|
+
} else if (line.startsWith("copy to ")) f.path = unquoteGitPath(line.slice("copy to ".length));
|
|
3054
|
+
else if (line.startsWith("old mode") || line.startsWith("new mode")) {
|
|
3055
|
+
if (f.status === "modified") f.status = "typechange";
|
|
3056
|
+
} else if (line.startsWith("Binary files ") || line.startsWith("GIT binary patch")) {
|
|
3057
|
+
f.binary = true;
|
|
3058
|
+
f.hidden = f.hidden ?? "binary file: contents not shown";
|
|
3059
|
+
} else if (line.startsWith("+++ ") && f.path !== "") {
|
|
3060
|
+
const to = unquoteGitPath(line.slice(4));
|
|
3061
|
+
if (to.startsWith("b/") && f.status !== "renamed") f.path = to.slice(2);
|
|
3062
|
+
} else if (line.startsWith("--- ")) {
|
|
3063
|
+
const from = unquoteGitPath(line.slice(4));
|
|
3064
|
+
if (from.startsWith("a/") && f.status === "deleted") f.path = from.slice(2);
|
|
3065
|
+
} else if (line.startsWith("@@")) {
|
|
3066
|
+
inHunk = true;
|
|
3067
|
+
const sec = f.oldPath ? secretPathReason(f.oldPath) : null;
|
|
3068
|
+
const sec2 = secretPathReason(f.path) ?? sec;
|
|
3069
|
+
if (sec2 && !f.hidden) f.hidden = `contents hidden: this is ${sec2}`;
|
|
3070
|
+
if (collecting && !f.hidden) f.lines.push({ type: "note", text: safeText(line) });
|
|
3071
|
+
}
|
|
3072
|
+
continue;
|
|
3073
|
+
}
|
|
3074
|
+
if (line.startsWith("@@")) {
|
|
3075
|
+
if (collecting && !f.hidden) f.lines.push({ type: "note", text: safeText(line) });
|
|
3076
|
+
continue;
|
|
3077
|
+
}
|
|
3078
|
+
const c = line[0];
|
|
3079
|
+
let type = null;
|
|
3080
|
+
if (c === "+") {
|
|
3081
|
+
type = "add";
|
|
3082
|
+
f.insertions++;
|
|
3083
|
+
insertions++;
|
|
3084
|
+
} else if (c === "-") {
|
|
3085
|
+
type = "del";
|
|
3086
|
+
f.deletions++;
|
|
3087
|
+
deletions++;
|
|
3088
|
+
} else if (c === " ") type = "context";
|
|
3089
|
+
else if (c === "\\") type = "note";
|
|
3090
|
+
if (type === null || !collecting || f.hidden) continue;
|
|
3091
|
+
if (shown >= limits.maxLines) {
|
|
3092
|
+
f.truncated = true;
|
|
3093
|
+
continue;
|
|
3094
|
+
}
|
|
3095
|
+
shown++;
|
|
3096
|
+
f.lines.push({ type, text: safeText(type === "note" ? line : line.slice(1)) });
|
|
3097
|
+
}
|
|
3098
|
+
return { files, totalFiles, insertions, deletions, shownLines: shown, omittedFiles };
|
|
3099
|
+
}
|
|
3100
|
+
async function readDiff(runner, settings, target) {
|
|
3101
|
+
const { args, title } = diffArgs(target);
|
|
3102
|
+
const r = await runner.read(args, { purpose: "Read the diff", maxBytes: settings.diffMaxBytes });
|
|
3103
|
+
if (!r.ok) {
|
|
3104
|
+
const e = explainGitFailure(r.stderr, "Git could not produce the diff.");
|
|
3105
|
+
throw new GitError("failed", e.message, e.hint);
|
|
3106
|
+
}
|
|
3107
|
+
const parsed = parseUnifiedDiff(r.stdout, { maxLines: settings.diffMaxLines, maxFiles: settings.diffMaxFiles });
|
|
3108
|
+
const notices = [];
|
|
3109
|
+
if (r.truncated) notices.push(`Git's output was larger than ${settings.diffMaxBytes} bytes and was cut; the numbers below cover only the part that was read.`);
|
|
3110
|
+
if (parsed.omittedFiles > 0) notices.push(`Only the first ${settings.diffMaxFiles} files are shown; ${parsed.omittedFiles} more changed (see /git status).`);
|
|
3111
|
+
if (parsed.files.some((f) => f.truncated)) notices.push(`Only the first ${settings.diffMaxLines} changed lines are shown. Use /git diff <file> to see one file at a time.`);
|
|
3112
|
+
for (const f of parsed.files) if (f.hidden) notices.push(`${safeText(f.path)}: ${f.hidden}.`);
|
|
3113
|
+
return {
|
|
3114
|
+
title,
|
|
3115
|
+
files: parsed.files,
|
|
3116
|
+
filesChanged: parsed.totalFiles,
|
|
3117
|
+
insertions: parsed.insertions,
|
|
3118
|
+
deletions: parsed.deletions,
|
|
3119
|
+
notices: [...new Set(notices)],
|
|
3120
|
+
digest: createHash3("sha256").update(r.stdout).digest("hex")
|
|
3121
|
+
};
|
|
3122
|
+
}
|
|
3123
|
+
|
|
3124
|
+
// src/git/git-ledger.ts
|
|
3125
|
+
var ChangeLedger = class {
|
|
3126
|
+
#entries = /* @__PURE__ */ new Map();
|
|
3127
|
+
#dirtyBefore = /* @__PURE__ */ new Set();
|
|
3128
|
+
/** Called just before an approved edit is applied, with the paths that were already modified in Git. */
|
|
3129
|
+
noteBefore(dirtyPaths) {
|
|
3130
|
+
this.#dirtyBefore.clear();
|
|
3131
|
+
for (const p of dirtyPaths) this.#dirtyBefore.add(p);
|
|
3132
|
+
}
|
|
3133
|
+
noteApplied(paths, now = Date.now()) {
|
|
3134
|
+
for (const p of paths) {
|
|
3135
|
+
const prev = this.#entries.get(p);
|
|
3136
|
+
this.#entries.set(p, { path: p, preexisting: prev ? prev.preexisting : this.#dirtyBefore.has(p), appliedAt: now, count: (prev?.count ?? 0) + 1 });
|
|
3137
|
+
}
|
|
3138
|
+
this.#dirtyBefore.clear();
|
|
3139
|
+
}
|
|
3140
|
+
has(path15) {
|
|
3141
|
+
return this.#entries.has(path15);
|
|
3142
|
+
}
|
|
3143
|
+
/** The file had your own uncommitted changes when zg first edited it. */
|
|
3144
|
+
hadOwnChanges(path15) {
|
|
3145
|
+
return this.#entries.get(path15)?.preexisting === true;
|
|
3146
|
+
}
|
|
3147
|
+
get size() {
|
|
3148
|
+
return this.#entries.size;
|
|
3149
|
+
}
|
|
3150
|
+
paths() {
|
|
3151
|
+
return [...this.#entries.keys()];
|
|
3152
|
+
}
|
|
3153
|
+
clear() {
|
|
3154
|
+
this.#entries.clear();
|
|
3155
|
+
this.#dirtyBefore.clear();
|
|
3156
|
+
}
|
|
3157
|
+
};
|
|
3158
|
+
|
|
3159
|
+
// src/git/git-permissions.ts
|
|
3160
|
+
var GitPermissions = class {
|
|
3161
|
+
#settings;
|
|
3162
|
+
#mode;
|
|
3163
|
+
constructor(settings, approvalMode) {
|
|
3164
|
+
this.#settings = settings;
|
|
3165
|
+
this.#mode = approvalMode;
|
|
3166
|
+
}
|
|
3167
|
+
/** Why the action is not allowed right now, or null. */
|
|
3168
|
+
why(action) {
|
|
3169
|
+
const s = this.#settings();
|
|
3170
|
+
if (s.permission === "deny") return "Git integration is turned off (git.permission is deny).";
|
|
3171
|
+
if (action === "read") return null;
|
|
3172
|
+
if (this.#mode() === "read-only") return "Your approval mode is read-only, which does not allow changing the repository.";
|
|
3173
|
+
const key = action === "stage" ? "staging" : action === "commit" ? "commit" : "branches";
|
|
3174
|
+
if (s[key] === "deny") return `${action === "stage" ? "Staging" : action === "commit" ? "Committing" : "Changing branches"} is turned off (git.${key} is deny).`;
|
|
3175
|
+
return null;
|
|
3176
|
+
}
|
|
3177
|
+
require(action) {
|
|
3178
|
+
const why = this.why(action);
|
|
3179
|
+
if (why) throw new GitError("denied", why);
|
|
3180
|
+
}
|
|
3181
|
+
};
|
|
3182
|
+
|
|
3183
|
+
// src/git/git-remote.ts
|
|
3184
|
+
function parseRemotes(stdout) {
|
|
3185
|
+
const map = /* @__PURE__ */ new Map();
|
|
3186
|
+
for (const line of stdout.split("\n")) {
|
|
3187
|
+
const m = /^(\S+)\t(.*) \((fetch|push)\)$/.exec(line);
|
|
3188
|
+
if (!m) continue;
|
|
3189
|
+
const name = safeText(m[1]);
|
|
3190
|
+
const { url, changed } = sanitizeRemoteUrl(m[2]);
|
|
3191
|
+
const shown = safeText(url);
|
|
3192
|
+
const info = map.get(name) ?? { name, fetchUrl: null, pushUrl: null, sanitized: false };
|
|
3193
|
+
if (m[3] === "fetch") info.fetchUrl = shown;
|
|
3194
|
+
else info.pushUrl = shown;
|
|
3195
|
+
info.sanitized = info.sanitized || changed;
|
|
3196
|
+
map.set(name, info);
|
|
3197
|
+
}
|
|
3198
|
+
return [...map.values()];
|
|
3199
|
+
}
|
|
3200
|
+
async function readRemotes(runner) {
|
|
3201
|
+
const r = await runner.read(["remote", "-v"], { purpose: "List configured remotes", maxBytes: 1e5 });
|
|
3202
|
+
if (!r.ok) {
|
|
3203
|
+
const e = explainGitFailure(r.stderr, "Git could not list remotes.");
|
|
3204
|
+
throw new GitError("failed", e.message, e.hint);
|
|
3205
|
+
}
|
|
3206
|
+
return parseRemotes(r.stdout);
|
|
3207
|
+
}
|
|
3208
|
+
|
|
3209
|
+
// src/git/git-restore.ts
|
|
3210
|
+
async function previewRestore(ctx, rawPaths) {
|
|
3211
|
+
ctx.permissions.require("read");
|
|
3212
|
+
const paths = [...new Set(rawPaths.map(validateRelPath))];
|
|
3213
|
+
if (paths.length === 0 || paths.length > MAX_PATHS) throw new GitError("invalid-argument", "Name the file(s) you are thinking of discarding.", "For example: /git restore src/app.ts");
|
|
3214
|
+
const status = await ctx.status();
|
|
3215
|
+
const byPath = new Map(status.entries.map((e) => [e.path, e]));
|
|
3216
|
+
const chosen = [];
|
|
3217
|
+
for (const p of paths) {
|
|
3218
|
+
const e = byPath.get(p);
|
|
3219
|
+
if (!e) throw new GitError("invalid-argument", `${safeText(p)} has no uncommitted changes, so there is nothing to discard.`);
|
|
3220
|
+
chosen.push(e);
|
|
3221
|
+
}
|
|
3222
|
+
const files = chosen.map((e) => ({ path: safeText(e.path), stagedChange: e.staged ? e.kind : null, unstagedChange: e.unstaged && e.kind !== "untracked" ? e.kind : null, untracked: e.kind === "untracked" }));
|
|
3223
|
+
const tracked = chosen.filter((e) => e.kind !== "untracked" && e.kind !== "conflicted").map((e) => e.path);
|
|
3224
|
+
let diff = null;
|
|
3225
|
+
const lines = ["Files that would be affected if their uncommitted changes were discarded:"];
|
|
3226
|
+
for (const e of chosen) {
|
|
3227
|
+
const where = e.kind === "untracked" ? "untracked file (would be deleted by a clean)" : [e.staged ? "staged change" : "", e.unstaged ? "unstaged change" : ""].filter(Boolean).join(" + ");
|
|
3228
|
+
lines.push(` ${displayPath(e)} [${where}]`);
|
|
3229
|
+
}
|
|
3230
|
+
if (tracked.length > 0) diff = await ctx.diff({ kind: "working", paths: tracked });
|
|
3231
|
+
lines.push(
|
|
3232
|
+
"",
|
|
3233
|
+
"Zero Gravity does not discard changes: git restore, checkout --, reset --hard and clean can destroy work for good, so they are blocked.",
|
|
3234
|
+
"Your options:",
|
|
3235
|
+
" - Changes zg made itself: /backups then /restore <id> puts the earlier contents back (with a preview).",
|
|
3236
|
+
" - Staged but not wanted in the commit: /git unstage <file> (keeps your edits).",
|
|
3237
|
+
" - Truly discarding: run the Git command yourself after reviewing the diff above."
|
|
3238
|
+
);
|
|
3239
|
+
return { files, lines, diff };
|
|
3240
|
+
}
|
|
3241
|
+
|
|
3242
|
+
// src/git/git-review.ts
|
|
3243
|
+
var BIG = 400;
|
|
3244
|
+
var NOISE = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|Cargo\.lock|poetry\.lock|go\.sum)$|(^|\/)(dist|build|\.next|coverage)\//;
|
|
3245
|
+
function buildReview(status, working, staged, ledger) {
|
|
3246
|
+
const diffOf = (path15) => [...staged.files, ...working.files].find((f) => f.path === path15);
|
|
3247
|
+
const sizeOf = (path15) => {
|
|
3248
|
+
const a = staged.files.find((f) => f.path === path15);
|
|
3249
|
+
const b = working.files.find((f) => f.path === path15);
|
|
3250
|
+
return { ins: (a?.insertions ?? 0) + (b?.insertions ?? 0), del: (a?.deletions ?? 0) + (b?.deletions ?? 0) };
|
|
3251
|
+
};
|
|
3252
|
+
const zgActive = ledger.size > 0;
|
|
3253
|
+
const items = status.entries.map((e) => {
|
|
3254
|
+
const inLedger = ledger.has(e.path) || (e.origPath ? ledger.has(e.origPath) : false);
|
|
3255
|
+
const origin = inLedger ? ledger.hadOwnChanges(e.path) ? "zero-gravity-on-yours" : "zero-gravity" : "yours";
|
|
3256
|
+
const flags = [];
|
|
3257
|
+
const secret = secretPathReason(e.path);
|
|
3258
|
+
if (secret) flags.push(`this is ${secret}; do not commit it`);
|
|
3259
|
+
const d = diffOf(e.path);
|
|
3260
|
+
if (d?.binary) flags.push("binary file");
|
|
3261
|
+
if (e.kind === "conflicted") flags.push("unresolved merge conflict");
|
|
3262
|
+
if (NOISE.test(e.path)) flags.push("generated or lock file");
|
|
3263
|
+
if (e.kind === "deleted") flags.push("file deleted");
|
|
3264
|
+
if (e.kind === "typechange") flags.push("file type or mode changed");
|
|
3265
|
+
const size = sizeOf(e.path);
|
|
3266
|
+
if (size.ins + size.del > BIG) flags.push(`large change (${size.ins + size.del} lines)`);
|
|
3267
|
+
if (zgActive && origin === "yours") flags.push("not changed by Zero Gravity in this session");
|
|
3268
|
+
if (origin === "zero-gravity-on-yours") flags.push("had your own uncommitted changes before zg edited it; the diff mixes both");
|
|
3269
|
+
return {
|
|
3270
|
+
path: e.path,
|
|
3271
|
+
display: displayPath(e),
|
|
3272
|
+
kind: e.kind,
|
|
3273
|
+
staged: e.staged,
|
|
3274
|
+
unstaged: e.unstaged,
|
|
3275
|
+
origin,
|
|
3276
|
+
originText: origin === "yours" ? "your change (not made by zg in this session)" : origin === "zero-gravity" ? "changed by Zero Gravity" : "changed by Zero Gravity on top of your own changes",
|
|
3277
|
+
flags,
|
|
3278
|
+
insertions: size.ins,
|
|
3279
|
+
deletions: size.del
|
|
3280
|
+
};
|
|
3281
|
+
});
|
|
3282
|
+
const unexpected = items.filter((i) => i.flags.some((f) => !f.startsWith("file deleted") || i.origin === "yours"));
|
|
3283
|
+
const c = status.counts;
|
|
3284
|
+
const summary = [
|
|
3285
|
+
`Branch: ${status.repo.branch ? safeText(status.repo.branch) : "(detached HEAD)"}`,
|
|
3286
|
+
`${items.length} changed file(s): ${c.staged} staged, ${c.modified} with unstaged changes, ${c.untracked} untracked${c.conflicted ? `, ${c.conflicted} conflicted` : ""}.`,
|
|
3287
|
+
`Working tree diff: ${working.filesChanged} file(s), +${working.insertions} -${working.deletions}. Staged diff: ${staged.filesChanged} file(s), +${staged.insertions} -${staged.deletions}.`,
|
|
3288
|
+
zgActive ? `Zero Gravity edited ${ledger.size} file(s) in this session: ${ledger.paths().slice(0, 8).map((p) => safeText(p)).join(", ")}${ledger.size > 8 ? ", ..." : ""}.` : "Zero Gravity has not edited files in this session, so every change below is treated as yours."
|
|
3289
|
+
];
|
|
3290
|
+
const next = [];
|
|
3291
|
+
if (status.conflicted.length > 0) next.push("Resolve the merge conflicts first: /git conflicts");
|
|
3292
|
+
else if (items.length === 0) next.push("There is nothing to commit.");
|
|
3293
|
+
else {
|
|
3294
|
+
next.push("Read the diffs: /git diff, /git diff staged");
|
|
3295
|
+
next.push("Stage the files you want in the commit, one by one: /git stage <file>");
|
|
3296
|
+
next.push("Then prepare the commit: /git commit [message] (zg can suggest a message)");
|
|
3297
|
+
}
|
|
3298
|
+
return { status, workingDiff: working, stagedDiff: staged, items, unexpected, summary, next };
|
|
3299
|
+
}
|
|
3300
|
+
|
|
3301
|
+
// src/git/git-staging.ts
|
|
3302
|
+
var WORD = { modified: "modified", added: "new file", deleted: "deleted", renamed: "renamed", copied: "copied", typechange: "type changed", untracked: "new file (untracked)", conflicted: "conflicted" };
|
|
3303
|
+
function uniquePaths(raw) {
|
|
3304
|
+
const paths = [...new Set(raw.map(validateRelPath))];
|
|
3305
|
+
if (paths.length === 0) throw new GitError("invalid-argument", "Name the file(s) to use.", "For example: /git stage src/app.ts");
|
|
3306
|
+
if (paths.length > MAX_PATHS) throw new GitError("invalid-argument", `At most ${MAX_PATHS} files can be handled at once.`);
|
|
3307
|
+
for (const p of paths) {
|
|
3308
|
+
if (/[*?]$|^\.$/.test(p) || p.endsWith("/")) throw new GitError("invalid-argument", `"${safeText(p)}" is not a single file. zg never stages whole folders or "everything".`, "Name each file.");
|
|
3309
|
+
}
|
|
3310
|
+
return paths;
|
|
3311
|
+
}
|
|
3312
|
+
function describe(e, staged) {
|
|
3313
|
+
const letter = staged ? e.index : e.kind === "untracked" ? "?" : e.worktree;
|
|
3314
|
+
return `${letter.padEnd(2)} ${displayPath(e)} (${WORD[e.kind] ?? e.kind})`;
|
|
3315
|
+
}
|
|
3316
|
+
async function digestFor(ctx, entries) {
|
|
3317
|
+
const out = [];
|
|
3318
|
+
for (const e of entries) {
|
|
3319
|
+
let h = null;
|
|
3320
|
+
if (e.kind === "untracked" && ctx.fileHash) h = await ctx.fileHash(e.path);
|
|
3321
|
+
out.push(`${e.path}|${e.index}${e.worktree}|${h ?? ""}`);
|
|
3322
|
+
}
|
|
3323
|
+
const tracked = entries.filter((e) => e.kind !== "untracked").map((e) => e.path);
|
|
3324
|
+
if (tracked.length > 0) out.push(`diff|${(await ctx.diff({ kind: "working", paths: tracked })).digest}`);
|
|
3325
|
+
return out;
|
|
3326
|
+
}
|
|
3327
|
+
async function planStage(ctx, rawPaths) {
|
|
3328
|
+
ctx.permissions.require("stage");
|
|
3329
|
+
const paths = uniquePaths(rawPaths);
|
|
3330
|
+
const status = await ctx.status();
|
|
3331
|
+
const byPath = new Map(status.entries.map((e) => [e.path, e]));
|
|
3332
|
+
const chosen = [];
|
|
3333
|
+
for (const p of paths) {
|
|
3334
|
+
const secret = secretPathReason(p);
|
|
3335
|
+
if (secret) throw new GitError("protected-path", `${safeText(p)} is ${secret}, so zg will not stage it.`, "Stage it yourself if you really mean to (and make sure it is not a secret).");
|
|
3336
|
+
const e = byPath.get(p);
|
|
3337
|
+
if (!e) {
|
|
3338
|
+
const dir = [...byPath.keys()].filter((k) => k.startsWith(`${p}/`)).length;
|
|
3339
|
+
throw new GitError("invalid-argument", dir > 0 ? `${safeText(p)} is a folder with ${dir} changed file(s); zg stages named files only.` : `${safeText(p)} has no changes to stage (or it is outside the project folder).`, "Check /git status.");
|
|
3340
|
+
}
|
|
3341
|
+
if (e.path.endsWith("/")) throw new GitError("invalid-argument", `${safeText(p)} is an untracked folder; name the files inside it.`, "Use /read or your file browser to list them.");
|
|
3342
|
+
if (e.kind === "conflicted") throw new GitError("conflicts", `${safeText(p)} has an unresolved merge conflict.`, "Resolve it first (/git conflicts).");
|
|
3343
|
+
if (!e.unstaged) throw new GitError("nothing-to-do", `${safeText(p)} is already staged and has no further changes.`);
|
|
3344
|
+
chosen.push(e);
|
|
3345
|
+
}
|
|
3346
|
+
const before = await digestFor(ctx, chosen);
|
|
3347
|
+
const command = ["add", "--", ...paths];
|
|
3348
|
+
const prepared = await ctx.runner.prepareWrite("add", command, "Stage the files you approved", "Adds exactly these files' current contents to the next commit; the files themselves are not changed");
|
|
3349
|
+
const lines = ["Files to stage (exactly these, nothing else):", ...chosen.map((e) => ` ${describe(e, false)}`), "", "Staging does not commit anything and does not change the files; it only selects their current contents for the next commit."];
|
|
3350
|
+
const warnings = [];
|
|
3351
|
+
const stagedAlready = status.staged.filter((s) => !paths.includes(s.path));
|
|
3352
|
+
if (stagedAlready.length > 0) warnings.push(`${stagedAlready.length} other file(s) are already staged and stay staged.`);
|
|
3353
|
+
return {
|
|
3354
|
+
id: ctx.newId(),
|
|
3355
|
+
kind: "stage",
|
|
3356
|
+
title: `Stage ${paths.length} file${paths.length > 1 ? "s" : ""}`,
|
|
3357
|
+
lines,
|
|
3358
|
+
warnings,
|
|
3359
|
+
command: prepared.display,
|
|
3360
|
+
prepared,
|
|
3361
|
+
createdAt: Date.now(),
|
|
3362
|
+
guard: async () => {
|
|
3363
|
+
const now = await ctx.status();
|
|
3364
|
+
const cur = paths.map((p) => now.entries.find((e) => e.path === p));
|
|
3365
|
+
if (cur.some((e) => !e || e.kind === "conflicted" || !e.unstaged)) throw new GitError("stale", "The files changed since you reviewed them, so nothing was staged.", "Run the staging step again.");
|
|
3366
|
+
const after = await digestFor(ctx, cur);
|
|
3367
|
+
if (JSON.stringify(after) !== JSON.stringify(before)) throw new GitError("stale", "A file changed after you reviewed it, so nothing was staged.", "Review the files again before staging.");
|
|
3368
|
+
},
|
|
3369
|
+
describeResult: async (out) => {
|
|
3370
|
+
if (!out.ok) {
|
|
3371
|
+
const e = explainGitFailure(out.stderr, "Git could not stage the files.");
|
|
3372
|
+
throw new GitError("failed", e.message, e.hint);
|
|
3373
|
+
}
|
|
3374
|
+
const now = await ctx.status();
|
|
3375
|
+
const stagedNow = paths.filter((p) => now.entries.find((e) => e.path === p)?.staged);
|
|
3376
|
+
return [`Staged ${stagedNow.length} of ${paths.length} file(s).`, ...stagedNow.map((p) => ` ${safeText(p)}`), `${now.counts.staged} file(s) are now staged in total. Nothing was committed.`];
|
|
3377
|
+
}
|
|
3378
|
+
};
|
|
3379
|
+
}
|
|
3380
|
+
async function planUnstage(ctx, rawPaths) {
|
|
3381
|
+
ctx.permissions.require("stage");
|
|
3382
|
+
const paths = uniquePaths(rawPaths);
|
|
3383
|
+
const status = await ctx.status();
|
|
3384
|
+
if (status.repo.unborn) throw new GitError("unborn", "This repository has no commits yet, so there is nothing to unstage back to.", "Use `git rm --cached <file>` yourself.");
|
|
3385
|
+
const byPath = new Map(status.entries.map((e) => [e.path, e]));
|
|
3386
|
+
const chosen = [];
|
|
3387
|
+
const all = [];
|
|
3388
|
+
const warnings = [];
|
|
3389
|
+
for (const p of paths) {
|
|
3390
|
+
const e = byPath.get(p);
|
|
3391
|
+
if (!e || !e.staged || e.kind === "conflicted") throw new GitError("invalid-argument", `${safeText(p)} is not staged.`, "Check /git status.");
|
|
3392
|
+
chosen.push(e);
|
|
3393
|
+
all.push(p);
|
|
3394
|
+
if (e.origPath) {
|
|
3395
|
+
if (/^\.\.?\//.test(e.origPath) || e.origPath.startsWith("/")) warnings.push(`${safeText(e.path)} was renamed from a path outside the project folder; only the new name is unstaged.`);
|
|
3396
|
+
else all.push(e.origPath);
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
3399
|
+
const finalPaths = [...new Set(all)];
|
|
3400
|
+
const beforeKey = JSON.stringify(chosen.map((e) => `${e.path}|${e.index}${e.worktree}`));
|
|
3401
|
+
const prepared = await ctx.runner.prepareWrite("unstage", ["restore", "--staged", "--", ...finalPaths], "Unstage the files you approved", "Removes these files from the next commit; their contents in the working tree are not changed");
|
|
3402
|
+
return {
|
|
3403
|
+
id: ctx.newId(),
|
|
3404
|
+
kind: "unstage",
|
|
3405
|
+
title: `Unstage ${finalPaths.length} file${finalPaths.length > 1 ? "s" : ""}`,
|
|
3406
|
+
lines: ["Files to unstage:", ...finalPaths.map((p) => ` ${safeText(p)}`), "", "Your edits stay in the files; only the selection for the next commit changes."],
|
|
3407
|
+
warnings,
|
|
3408
|
+
command: prepared.display,
|
|
3409
|
+
prepared,
|
|
3410
|
+
createdAt: Date.now(),
|
|
3411
|
+
guard: async () => {
|
|
3412
|
+
const now = await ctx.status();
|
|
3413
|
+
const key = JSON.stringify(paths.map((p) => now.entries.find((e) => e.path === p)).map((e) => e ? `${e.path}|${e.index}${e.worktree}` : "gone"));
|
|
3414
|
+
if (key !== beforeKey) throw new GitError("stale", "The staged files changed since you reviewed them, so nothing was unstaged.");
|
|
3415
|
+
},
|
|
3416
|
+
describeResult: async (out) => {
|
|
3417
|
+
if (!out.ok) {
|
|
3418
|
+
const e = explainGitFailure(out.stderr, "Git could not unstage the files.");
|
|
3419
|
+
throw new GitError("failed", e.message, e.hint);
|
|
3420
|
+
}
|
|
3421
|
+
const now = await ctx.status();
|
|
3422
|
+
return [`Unstaged ${finalPaths.length} file(s). Your edits are still in the working tree.`, `${now.counts.staged} file(s) remain staged.`];
|
|
3423
|
+
}
|
|
3424
|
+
};
|
|
3425
|
+
}
|
|
3426
|
+
|
|
3427
|
+
// src/git/git-manager.ts
|
|
3428
|
+
var GitManager = class {
|
|
3429
|
+
ledger = new ChangeLedger();
|
|
3430
|
+
permissions;
|
|
3431
|
+
#d;
|
|
3432
|
+
#pending = /* @__PURE__ */ new Map();
|
|
3433
|
+
#busy = false;
|
|
3434
|
+
#security = null;
|
|
3435
|
+
constructor(deps) {
|
|
3436
|
+
this.#d = deps;
|
|
3437
|
+
this.permissions = new GitPermissions(deps.settings, deps.approvalMode);
|
|
3438
|
+
}
|
|
3439
|
+
setSecurity(guard) {
|
|
3440
|
+
this.#security = guard;
|
|
3441
|
+
}
|
|
3442
|
+
get settings() {
|
|
3443
|
+
return this.#d.settings();
|
|
3444
|
+
}
|
|
3445
|
+
// ---- detection ----
|
|
3446
|
+
async detect() {
|
|
3447
|
+
this.permissions.require("read");
|
|
3448
|
+
const d = await detectRepository(this.#d.runner, this.#d.projectRoot);
|
|
3449
|
+
return d;
|
|
3450
|
+
}
|
|
3451
|
+
/** The repository, or a GitError that explains why there is none. */
|
|
3452
|
+
async requireRepo() {
|
|
3453
|
+
const d = await this.detect();
|
|
3454
|
+
switch (d.state) {
|
|
3455
|
+
case "ok":
|
|
3456
|
+
return d.repo;
|
|
3457
|
+
case "git-missing":
|
|
3458
|
+
throw new GitError("not-installed", d.reason, "Install Git (Termux: pkg install git). zg does not install programs.");
|
|
3459
|
+
case "git-too-old":
|
|
3460
|
+
throw new GitError("unsupported-git", d.reason);
|
|
3461
|
+
case "not-a-repo":
|
|
3462
|
+
throw new GitError("not-a-repo", "This project folder is not inside a Git repository.", "Run `git init` yourself if you want one; zg never creates repositories.");
|
|
3463
|
+
case "bare":
|
|
3464
|
+
throw new GitError("bare-repo", "This is a bare repository (it has no working tree), so there are no files to inspect.");
|
|
3465
|
+
case "invalid":
|
|
3466
|
+
throw new GitError("invalid-repo", d.reason);
|
|
3467
|
+
}
|
|
3468
|
+
}
|
|
3469
|
+
// ---- reads ----
|
|
3470
|
+
async status(opts = {}) {
|
|
3471
|
+
const repo = await this.requireRepo();
|
|
3472
|
+
return readStatus(this.#d.runner, repo, this.#d.settings(), opts);
|
|
3473
|
+
}
|
|
3474
|
+
async diff(target) {
|
|
3475
|
+
await this.requireRepo();
|
|
3476
|
+
return readDiff(this.#d.runner, this.#d.settings(), target);
|
|
3477
|
+
}
|
|
3478
|
+
async log(opts = {}) {
|
|
3479
|
+
await this.requireRepo();
|
|
3480
|
+
return readLog(this.#d.runner, this.#d.settings(), opts);
|
|
3481
|
+
}
|
|
3482
|
+
async commit(rev) {
|
|
3483
|
+
await this.requireRepo();
|
|
3484
|
+
return readCommit(this.#d.runner, rev);
|
|
3485
|
+
}
|
|
3486
|
+
async branches(includeRemote = true) {
|
|
3487
|
+
await this.requireRepo();
|
|
3488
|
+
return readBranches(this.#d.runner, includeRemote);
|
|
3489
|
+
}
|
|
3490
|
+
async remotes() {
|
|
3491
|
+
await this.requireRepo();
|
|
3492
|
+
return readRemotes(this.#d.runner);
|
|
3493
|
+
}
|
|
3494
|
+
async conflicts() {
|
|
3495
|
+
const status = await this.status({ all: true });
|
|
3496
|
+
const readFile = this.#d.readFile ?? (() => Promise.reject(new Error("no reader")));
|
|
3497
|
+
return { status, report: await inspectConflicts(status.conflicted, this.#d.settings(), readFile) };
|
|
3498
|
+
}
|
|
3499
|
+
async review() {
|
|
3500
|
+
const status = await this.status({ all: true });
|
|
3501
|
+
const working = await readDiff(this.#d.runner, this.#d.settings(), { kind: "working" });
|
|
3502
|
+
const staged = await readDiff(this.#d.runner, this.#d.settings(), { kind: "staged" });
|
|
3503
|
+
return buildReview(status, working, staged, this.ledger);
|
|
3504
|
+
}
|
|
3505
|
+
async restorePreview(paths) {
|
|
3506
|
+
await this.requireRepo();
|
|
3507
|
+
return previewRestore(this.#ctx(), paths);
|
|
3508
|
+
}
|
|
3509
|
+
// ---- changes: prepare (nothing happens), then apply with a GitApproval ----
|
|
3510
|
+
#ctx() {
|
|
3511
|
+
return {
|
|
3512
|
+
runner: this.#d.runner,
|
|
3513
|
+
settings: this.#d.settings(),
|
|
3514
|
+
permissions: this.permissions,
|
|
3515
|
+
status: () => this.status({ all: true }),
|
|
3516
|
+
diff: (t) => readDiff(this.#d.runner, this.#d.settings(), t),
|
|
3517
|
+
...this.#d.fileHash ? { fileHash: this.#d.fileHash } : {},
|
|
3518
|
+
newId: () => `git-${Date.now().toString(36)}-${randomBytes5(3).toString("hex")}`
|
|
3519
|
+
};
|
|
3520
|
+
}
|
|
3521
|
+
async #keep(make) {
|
|
3522
|
+
await this.requireRepo();
|
|
3523
|
+
const op = await make();
|
|
3524
|
+
this.#pending.set(op.id, op);
|
|
3525
|
+
return op;
|
|
3526
|
+
}
|
|
3527
|
+
prepareStage(paths) {
|
|
3528
|
+
return this.#keep(() => planStage(this.#ctx(), paths));
|
|
3529
|
+
}
|
|
3530
|
+
prepareUnstage(paths) {
|
|
3531
|
+
return this.#keep(() => planUnstage(this.#ctx(), paths));
|
|
3532
|
+
}
|
|
3533
|
+
prepareCommit(message) {
|
|
3534
|
+
return this.#keep(() => planCommit(this.#ctx(), message));
|
|
3535
|
+
}
|
|
3536
|
+
prepareBranchCreate(name) {
|
|
3537
|
+
return this.#keep(() => planBranchCreate(this.#ctx(), name));
|
|
3538
|
+
}
|
|
3539
|
+
prepareSwitch(name) {
|
|
3540
|
+
return this.#keep(() => planSwitch(this.#ctx(), name));
|
|
3541
|
+
}
|
|
3542
|
+
pending(id) {
|
|
3543
|
+
return this.#pending.get(id);
|
|
3544
|
+
}
|
|
3545
|
+
discard(id) {
|
|
3546
|
+
this.#pending.delete(id);
|
|
3547
|
+
}
|
|
3548
|
+
/**
|
|
3549
|
+
* Runs a prepared operation. It needs the user's GitApproval for exactly this operation, re-checks the
|
|
3550
|
+
* permissions, then re-checks that the repository is unchanged since the review, then runs the one
|
|
3551
|
+
* approved command. An operation runs at most once.
|
|
3552
|
+
*/
|
|
3553
|
+
async apply(op, approval, signal) {
|
|
3554
|
+
if (!(approval instanceof GitApproval) || approval.operationId !== op.id) throw new GitError("not-approved", "That approval does not belong to this operation, so nothing was changed.");
|
|
3555
|
+
if (this.#pending.get(op.id) !== op) throw new GitError("stale", "This operation was already used or was discarded, so it will not run again.", "Prepare it again to review it afresh.");
|
|
3556
|
+
this.permissions.require(op.kind === "stage" || op.kind === "unstage" ? "stage" : op.kind === "commit" ? "commit" : "branch");
|
|
3557
|
+
if (this.#busy) throw new GitError("busy", "Another Git change is running.");
|
|
3558
|
+
this.#busy = true;
|
|
3559
|
+
this.#pending.delete(op.id);
|
|
3560
|
+
let decision = null;
|
|
3561
|
+
try {
|
|
3562
|
+
if (this.#security) decision = await this.#security.authorize({ level: "git", operation: `git ${op.kind}`, resource: "git", target: op.title, detail: op.command, component: "git", actor: "user", risk: op.kind === "commit" || op.kind === "stage" || op.kind === "unstage" ? "low" : "medium", reason: op.title }, { approved: true });
|
|
3563
|
+
await this.requireRepo();
|
|
3564
|
+
await op.guard();
|
|
3565
|
+
const out = await this.#d.runner.runWrite(op.prepared, signal);
|
|
3566
|
+
const res = { op, lines: await op.describeResult(out) };
|
|
3567
|
+
if (decision) await this.#security?.complete(decision, "completed");
|
|
3568
|
+
return res;
|
|
3569
|
+
} catch (err) {
|
|
3570
|
+
if (decision) await this.#security?.complete(decision, "failed", err instanceof Error ? err.message.slice(0, 120) : "failed");
|
|
3571
|
+
throw err;
|
|
3572
|
+
} finally {
|
|
3573
|
+
this.#busy = false;
|
|
3574
|
+
}
|
|
3575
|
+
}
|
|
3576
|
+
// ---- commit message suggestion (the AI proposes text only; it never runs anything) ----
|
|
3577
|
+
async suggestMessage(signal) {
|
|
3578
|
+
this.permissions.require("read");
|
|
3579
|
+
if (!this.#d.settings().suggestCommitMessage) throw new GitError("denied", "Commit message suggestions are turned off (git.suggestCommitMessage is false).", "Write the message yourself: /git commit <message>");
|
|
3580
|
+
if (!this.#d.suggester) throw new GitError("failed", "No AI provider is connected, so a message cannot be suggested.", "Write the message yourself: /git commit <message>");
|
|
3581
|
+
const status = await this.status({ all: true });
|
|
3582
|
+
const staged = status.entries.filter((e) => e.staged);
|
|
3583
|
+
if (staged.length === 0) throw new GitError("nothing-to-do", "Nothing is staged, so there is nothing to describe.", "Stage files first with /git stage <file>.");
|
|
3584
|
+
const diff = await readDiff(this.#d.runner, this.#d.settings(), { kind: "staged" });
|
|
3585
|
+
const recent = await readLog(this.#d.runner, this.#d.settings(), { limit: 5 }).catch(() => ({ commits: [] }));
|
|
3586
|
+
const res = await this.#d.suggester({ files: staged.map((e) => safeText(e.path)), diffText: diffToText(diff, 12e3), recentSubjects: recent.commits.map((c) => c.subject) }, signal);
|
|
3587
|
+
if (res.status === "cancelled") throw new GitError("failed", "Cancelled.");
|
|
3588
|
+
if (res.status === "failed") throw new GitError("failed", res.message);
|
|
3589
|
+
return { message: validateCommitMessage(res.message) };
|
|
3590
|
+
}
|
|
3591
|
+
// ---- hooks for the Phase 6 editing engine (label which changes are zg's) ----
|
|
3592
|
+
hooks() {
|
|
3593
|
+
return {
|
|
3594
|
+
before: async () => {
|
|
3595
|
+
try {
|
|
3596
|
+
if (this.#d.settings().permission === "deny") return;
|
|
3597
|
+
const s = await this.status({ all: true });
|
|
3598
|
+
this.ledger.noteBefore(s.entries.map((e) => e.path));
|
|
3599
|
+
} catch {
|
|
3600
|
+
this.ledger.noteBefore([]);
|
|
3601
|
+
}
|
|
3602
|
+
},
|
|
3603
|
+
after: (paths) => this.ledger.noteApplied(paths)
|
|
3604
|
+
};
|
|
3605
|
+
}
|
|
3606
|
+
};
|
|
3607
|
+
|
|
3608
|
+
// src/git/git-runner.ts
|
|
3609
|
+
function hardeningEnv(windows, write) {
|
|
3610
|
+
const pairs = [
|
|
3611
|
+
["core.fsmonitor", "false"],
|
|
3612
|
+
["core.hooksPath", windows ? "NUL" : "/dev/null"],
|
|
3613
|
+
["core.quotepath", "false"],
|
|
3614
|
+
["gc.auto", "0"],
|
|
3615
|
+
["maintenance.auto", "false"],
|
|
3616
|
+
["color.ui", "false"]
|
|
3617
|
+
];
|
|
3618
|
+
const env = { GIT_CONFIG_COUNT: String(pairs.length), GIT_TERMINAL_PROMPT: "0", GIT_LITERAL_PATHSPECS: "1", LC_ALL: "C" };
|
|
3619
|
+
pairs.forEach(([k, v], i) => {
|
|
3620
|
+
env[`GIT_CONFIG_KEY_${i}`] = k;
|
|
3621
|
+
env[`GIT_CONFIG_VALUE_${i}`] = v;
|
|
3622
|
+
});
|
|
3623
|
+
if (!write) env["GIT_OPTIONAL_LOCKS"] = "0";
|
|
3624
|
+
return env;
|
|
3625
|
+
}
|
|
3626
|
+
function translate(err) {
|
|
3627
|
+
if (err instanceof GitError) return err;
|
|
3628
|
+
if (err instanceof ExecutionError) {
|
|
3629
|
+
switch (err.code) {
|
|
3630
|
+
case "not-found":
|
|
3631
|
+
return new GitError("not-installed", "Git is not installed (or is not on your PATH).", "Install Git (Termux: pkg install git) and try again. zg does not install programs.");
|
|
3632
|
+
case "denied":
|
|
3633
|
+
return new GitError("denied", err.message, err.hint);
|
|
3634
|
+
case "blocked":
|
|
3635
|
+
case "not-approved":
|
|
3636
|
+
return new GitError("blocked", err.message, err.hint);
|
|
3637
|
+
case "stale":
|
|
3638
|
+
return new GitError("stale", err.message, err.hint);
|
|
3639
|
+
case "duplicate":
|
|
3640
|
+
return new GitError("busy", err.message, err.hint);
|
|
3641
|
+
case "too-many-processes":
|
|
3642
|
+
return new GitError("busy", err.message, err.hint);
|
|
3643
|
+
case "unsupported-platform":
|
|
3644
|
+
return new GitError("failed", err.message, err.hint);
|
|
3645
|
+
case "outside-workspace":
|
|
3646
|
+
case "no-workspace":
|
|
3647
|
+
return new GitError("no-workspace", err.message, err.hint);
|
|
3648
|
+
default:
|
|
3649
|
+
return new GitError("failed", err.message, err.hint);
|
|
3650
|
+
}
|
|
3651
|
+
}
|
|
3652
|
+
return new GitError("failed", "The Git command could not be run.");
|
|
3653
|
+
}
|
|
3654
|
+
var GitRunner = class {
|
|
3655
|
+
#d;
|
|
3656
|
+
constructor(deps) {
|
|
3657
|
+
this.#d = deps;
|
|
3658
|
+
}
|
|
3659
|
+
async read(args, opts = {}) {
|
|
3660
|
+
assertReadArgs(args);
|
|
3661
|
+
try {
|
|
3662
|
+
const prepared = await this.#d.engine.prepareRead({
|
|
3663
|
+
spec: { kind: "direct", program: "git", args: [...args] },
|
|
3664
|
+
cwd: ".",
|
|
3665
|
+
purpose: opts.purpose ?? "Read repository information",
|
|
3666
|
+
expectedEffect: "Nothing is changed",
|
|
3667
|
+
timeoutSeconds: 30,
|
|
3668
|
+
source: "git"
|
|
3669
|
+
});
|
|
3670
|
+
const res = await this.#d.engine.executeReadOnly(prepared, {
|
|
3671
|
+
extraEnv: hardeningEnv(this.#d.windows, false),
|
|
3672
|
+
rawStdout: true,
|
|
3673
|
+
maxOutputBytes: opts.maxBytes ?? 2e5,
|
|
3674
|
+
...opts.signal ? { signal: opts.signal } : {}
|
|
3675
|
+
});
|
|
3676
|
+
if (res.status === "spawn-error") throw new GitError(res.spawnError?.kind === "not-found" ? "not-installed" : "failed", res.spawnError?.kind === "not-found" ? "Git is not installed (or is not on your PATH)." : "Git could not be started.", res.spawnError?.kind === "not-found" ? "Install Git and try again." : void 0);
|
|
3677
|
+
if (res.status === "timed-out") throw new GitError("failed", "Git took too long and was stopped.", "A very large repository can be slow; try a smaller request.");
|
|
3678
|
+
if (res.status === "cancelled") throw new GitError("failed", "Cancelled.");
|
|
3679
|
+
return { ok: res.status === "completed", exitCode: res.exitCode, stdout: res.stdoutRaw ?? "", stderr: res.output, truncated: res.outputTruncated };
|
|
3680
|
+
} catch (err) {
|
|
3681
|
+
throw translate(err);
|
|
3682
|
+
}
|
|
3683
|
+
}
|
|
3684
|
+
/** Prepare (but do not run) a change. Throws when the command is not allowed. */
|
|
3685
|
+
async prepareWrite(shape, args, purpose, effect) {
|
|
3686
|
+
assertWriteArgs(shape, args);
|
|
3687
|
+
try {
|
|
3688
|
+
const prepared = await this.#d.engine.prepare({ spec: { kind: "direct", program: "git", args: [...args] }, cwd: ".", purpose, expectedEffect: effect, timeoutSeconds: 60, source: "git" });
|
|
3689
|
+
if (prepared.assessment.risk === "blocked") throw new GitError("blocked", `This Git command is blocked: ${prepared.assessment.reasons[0] ?? "it is not allowed"}.`);
|
|
3690
|
+
if (prepared.assessment.risk === "high" || prepared.assessment.needsConfirm) throw new GitError("blocked", `This Git command is rated high risk (${prepared.assessment.reasons[0] ?? "see the risk reasons"}), so zg will not run it.`);
|
|
3691
|
+
return prepared;
|
|
3692
|
+
} catch (err) {
|
|
3693
|
+
throw translate(err);
|
|
3694
|
+
}
|
|
3695
|
+
}
|
|
3696
|
+
async runWrite(prepared, signal) {
|
|
3697
|
+
try {
|
|
3698
|
+
const res = await this.#d.engine.execute(prepared, ApprovedCommand.grant(prepared.id, false), {
|
|
3699
|
+
extraEnv: hardeningEnv(this.#d.windows, true),
|
|
3700
|
+
...signal ? { signal } : {}
|
|
3701
|
+
});
|
|
3702
|
+
if (res.status === "spawn-error") throw new GitError(res.spawnError?.kind === "not-found" ? "not-installed" : "failed", "Git could not be started.");
|
|
3703
|
+
if (res.status === "timed-out") throw new GitError("failed", "Git took too long and was stopped.");
|
|
3704
|
+
if (res.status === "cancelled") throw new GitError("failed", "Cancelled.");
|
|
3705
|
+
return { ok: res.status === "completed", exitCode: res.exitCode, stdout: res.output, stderr: res.output, truncated: res.outputTruncated };
|
|
3706
|
+
} catch (err) {
|
|
3707
|
+
throw translate(err);
|
|
3708
|
+
}
|
|
3709
|
+
}
|
|
3710
|
+
};
|
|
3711
|
+
|
|
3712
|
+
// src/intelligence/code-intel.ts
|
|
3713
|
+
import { promises as fsp11 } from "fs";
|
|
3714
|
+
import path13 from "path";
|
|
3715
|
+
|
|
3716
|
+
// src/indexing/store.ts
|
|
3717
|
+
import { promises as fsp10 } from "fs";
|
|
3718
|
+
import path11 from "path";
|
|
3719
|
+
var IndexStore = class {
|
|
3720
|
+
file;
|
|
3721
|
+
constructor(dataDir, projectId) {
|
|
3722
|
+
this.file = path11.join(dataDir, "index", projectId, "index.json");
|
|
3723
|
+
}
|
|
3724
|
+
async load() {
|
|
3725
|
+
let raw;
|
|
3726
|
+
try {
|
|
3727
|
+
raw = await fsp10.readFile(this.file, "utf8");
|
|
3728
|
+
} catch {
|
|
3729
|
+
return null;
|
|
3730
|
+
}
|
|
3731
|
+
try {
|
|
3732
|
+
const d = JSON.parse(raw);
|
|
3733
|
+
if (d.version !== INDEX_VERSION || typeof d.files !== "object" || d.files === null) return null;
|
|
3734
|
+
return d;
|
|
3735
|
+
} catch {
|
|
3736
|
+
await fsp10.rename(this.file, `${this.file}.damaged`).catch(() => void 0);
|
|
3737
|
+
return null;
|
|
3738
|
+
}
|
|
3739
|
+
}
|
|
3740
|
+
async save(d) {
|
|
3741
|
+
await fsp10.mkdir(path11.dirname(this.file), { recursive: true, mode: 448 });
|
|
3742
|
+
await atomicWriteFile(this.file, JSON.stringify(d));
|
|
3743
|
+
}
|
|
3744
|
+
async clear() {
|
|
3745
|
+
let had = false;
|
|
3746
|
+
for (const f of [this.file, `${this.file}.damaged`]) {
|
|
3747
|
+
try {
|
|
3748
|
+
await fsp10.rm(f);
|
|
3749
|
+
had = true;
|
|
3750
|
+
} catch {
|
|
3751
|
+
}
|
|
3752
|
+
}
|
|
3753
|
+
return had;
|
|
3754
|
+
}
|
|
3755
|
+
};
|
|
3756
|
+
|
|
3757
|
+
// src/search/search.ts
|
|
3758
|
+
var WORD2 = /[A-Za-z_$][A-Za-z0-9_$]*/g;
|
|
3759
|
+
function queryTerms(q) {
|
|
3760
|
+
const out = /* @__PURE__ */ new Set();
|
|
3761
|
+
for (const m of q.matchAll(WORD2)) {
|
|
3762
|
+
const lower = m[0].toLowerCase();
|
|
3763
|
+
if (lower.length > 1) out.add(lower);
|
|
3764
|
+
for (const p of splitIdentifier(m[0])) if (p.length > 1) out.add(p);
|
|
3765
|
+
}
|
|
3766
|
+
return [...out];
|
|
3767
|
+
}
|
|
3768
|
+
function searchFiles2(data, query, o = {}) {
|
|
3769
|
+
const terms = queryTerms(query);
|
|
3770
|
+
if (terms.length === 0) return [];
|
|
3771
|
+
const files = Object.values(data.files).filter((f) => (o.includeTests ?? true) || !f.isTest).filter((f) => !o.language || f.language === o.language).filter((f) => !o.under || f.path.startsWith(o.under.replace(/\/?$/, "/")));
|
|
3772
|
+
const df = /* @__PURE__ */ new Map();
|
|
3773
|
+
for (const t of terms) df.set(t, files.filter((f) => f.terms[t] !== void 0).length);
|
|
3774
|
+
const hits = [];
|
|
3775
|
+
for (const f of files) {
|
|
3776
|
+
let score = 0;
|
|
3777
|
+
const matched = [];
|
|
3778
|
+
const lowerPath = f.path.toLowerCase();
|
|
3779
|
+
for (const t of terms) {
|
|
3780
|
+
const tf = f.terms[t] ?? 0;
|
|
3781
|
+
const idf = Math.log(1 + files.length / (1 + df.get(t)));
|
|
3782
|
+
if (tf > 0) {
|
|
3783
|
+
score += (1 + Math.log(tf)) * idf;
|
|
3784
|
+
matched.push(t);
|
|
3785
|
+
}
|
|
3786
|
+
if (lowerPath.includes(t)) {
|
|
3787
|
+
score += 3 * idf;
|
|
3788
|
+
if (!matched.includes(t)) matched.push(t);
|
|
3789
|
+
}
|
|
3790
|
+
for (const s of f.symbols) {
|
|
3791
|
+
const n = s.name.toLowerCase();
|
|
3792
|
+
if (n === t) score += 6 * idf;
|
|
3793
|
+
else if (n.includes(t)) score += 2 * idf;
|
|
3794
|
+
if (n.includes(t) && !matched.includes(t)) matched.push(t);
|
|
3795
|
+
}
|
|
3796
|
+
}
|
|
3797
|
+
if (score > 0) {
|
|
3798
|
+
const sym = f.symbols.filter((s) => terms.some((t) => s.name.toLowerCase().includes(t))).slice(0, 5).map((s) => ({ name: s.name, kind: s.kind, line: s.line }));
|
|
3799
|
+
score *= 1 + 0.5 * (matched.length / terms.length);
|
|
3800
|
+
hits.push({ path: f.path, score: Math.round(score * 100) / 100, language: f.language, matchedTerms: matched, symbols: sym, isTest: f.isTest });
|
|
3801
|
+
}
|
|
3802
|
+
}
|
|
3803
|
+
return hits.sort((a, b) => b.score - a.score || (a.path < b.path ? -1 : 1)).slice(0, o.limit ?? 20);
|
|
3804
|
+
}
|
|
3805
|
+
function subsequence(needle, hay) {
|
|
3806
|
+
let i = 0;
|
|
3807
|
+
for (const c of hay) if (c === needle[i] && ++i === needle.length) return true;
|
|
3808
|
+
return needle.length === 0;
|
|
3809
|
+
}
|
|
3810
|
+
function searchSymbols(data, name, o = {}) {
|
|
3811
|
+
const q = name.toLowerCase();
|
|
3812
|
+
const hits = [];
|
|
3813
|
+
for (const f of Object.values(data.files)) {
|
|
3814
|
+
for (const s of f.symbols) {
|
|
3815
|
+
if (o.kind && s.kind !== o.kind) continue;
|
|
3816
|
+
if (o.exportedOnly && !s.exported) continue;
|
|
3817
|
+
const n = s.name.toLowerCase();
|
|
3818
|
+
let match = null;
|
|
3819
|
+
let score = 0;
|
|
3820
|
+
if (n === q) {
|
|
3821
|
+
match = "exact";
|
|
3822
|
+
score = 100;
|
|
3823
|
+
} else if (n.startsWith(q)) {
|
|
3824
|
+
match = "prefix";
|
|
3825
|
+
score = 60 - Math.min(20, n.length - q.length);
|
|
3826
|
+
} else if (n.includes(q)) {
|
|
3827
|
+
match = "substring";
|
|
3828
|
+
score = 35;
|
|
3829
|
+
} else if (q.length >= 2 && subsequence(q, splitIdentifier(s.name).map((p) => p[0]).join(""))) {
|
|
3830
|
+
match = "parts";
|
|
3831
|
+
score = 20;
|
|
3832
|
+
}
|
|
3833
|
+
if (!match) continue;
|
|
3834
|
+
if (s.exported) score += 3;
|
|
3835
|
+
if (f.isTest) score -= 5;
|
|
3836
|
+
if (s.kind === "class" || s.kind === "function" || s.kind === "interface") score += 2;
|
|
3837
|
+
hits.push({ path: f.path, symbol: s, score, match });
|
|
3838
|
+
}
|
|
3839
|
+
}
|
|
3840
|
+
return hits.sort((a, b) => b.score - a.score || (a.path < b.path ? -1 : a.symbol.line - b.symbol.line)).slice(0, o.limit ?? 30);
|
|
3841
|
+
}
|
|
3842
|
+
|
|
3843
|
+
// src/search/context.ts
|
|
3844
|
+
var numbered = (lines, first) => lines.map((l, i) => `${String(first + i).padStart(5)} ${l}`).join("\n");
|
|
3845
|
+
async function retrieveContext(data, read, query, o) {
|
|
3846
|
+
const terms = queryTerms(query);
|
|
3847
|
+
const hits = searchFiles2(data, query, { limit: o.maxFiles ?? 8 });
|
|
3848
|
+
const order = [...(o.include ?? []).filter((p) => p in data.files), ...hits.map((h) => h.path).filter((p) => !(o.include ?? []).includes(p))];
|
|
3849
|
+
const sources = [];
|
|
3850
|
+
const parts = [];
|
|
3851
|
+
let used = 0;
|
|
3852
|
+
let truncated = false;
|
|
3853
|
+
for (const path15 of order) {
|
|
3854
|
+
if (o.signal?.aborted) break;
|
|
3855
|
+
const f = data.files[path15];
|
|
3856
|
+
if (!f) continue;
|
|
3857
|
+
const text4 = await read(path15);
|
|
3858
|
+
if (text4 === null) continue;
|
|
3859
|
+
const lines = text4.split("\n");
|
|
3860
|
+
const ranges = [];
|
|
3861
|
+
for (const s of f.symbols) {
|
|
3862
|
+
if (terms.some((t) => s.name.toLowerCase().includes(t)) && (s.kind === "function" || s.kind === "method" || s.kind === "class" || s.kind === "interface" || s.kind === "type")) ranges.push({ s: Math.max(1, s.line - 1), e: Math.min(lines.length, Math.min(s.endLine, s.line + 60)), why: `${s.kind} ${s.name}` });
|
|
3863
|
+
}
|
|
3864
|
+
if (ranges.length === 0) ranges.push({ s: 1, e: Math.min(lines.length, 40), why: "top of the file" });
|
|
3865
|
+
const outline = f.symbols.filter((s) => !s.container).slice(0, 25).map((s) => `${s.kind} ${s.name}:${s.line}`).join(", ");
|
|
3866
|
+
const chunks = [`=== ${path15} (${f.language}, ${f.lines} lines)${outline ? `
|
|
3867
|
+
outline: ${outline}` : ""}`];
|
|
3868
|
+
for (const r of ranges.slice(0, 4)) {
|
|
3869
|
+
const body = redactSecrets(numbered(lines.slice(r.s - 1, r.e), r.s));
|
|
3870
|
+
chunks.push(`--- lines ${r.s}-${r.e} (${r.why})
|
|
3871
|
+
${body}`);
|
|
3872
|
+
sources.push({ path: path15, startLine: r.s, endLine: r.e, why: r.why });
|
|
3873
|
+
}
|
|
3874
|
+
const block = chunks.join("\n");
|
|
3875
|
+
if (used + block.length > o.budgetChars) {
|
|
3876
|
+
truncated = true;
|
|
3877
|
+
if (parts.length > 0) break;
|
|
3878
|
+
parts.push(block.slice(0, o.budgetChars));
|
|
3879
|
+
break;
|
|
3880
|
+
}
|
|
3881
|
+
parts.push(block);
|
|
3882
|
+
used += block.length;
|
|
3883
|
+
}
|
|
3884
|
+
const text3 = parts.length ? fenceUntrusted("project-code", parts.join("\n\n")) : "";
|
|
3885
|
+
return { text: text3, sources, filesConsidered: order.length, truncated };
|
|
3886
|
+
}
|
|
3887
|
+
|
|
3888
|
+
// src/intelligence/project.ts
|
|
3889
|
+
import path12 from "path";
|
|
3890
|
+
var NODE_FRAMEWORKS = { react: "React", next: "Next.js", vue: "Vue", nuxt: "Nuxt", svelte: "Svelte", "@angular/core": "Angular", express: "Express", fastify: "Fastify", "@nestjs/core": "NestJS", koa: "Koa", electron: "Electron", "react-native": "React Native", astro: "Astro", "solid-js": "Solid", commander: "Commander (CLI)", hono: "Hono" };
|
|
3891
|
+
var NODE_BUILD = { vite: "Vite", webpack: "webpack", tsup: "tsup", esbuild: "esbuild", rollup: "Rollup", parcel: "Parcel", turbo: "Turborepo", typescript: "TypeScript compiler (tsc)", "@swc/core": "SWC" };
|
|
3892
|
+
var PY_FRAMEWORKS = { django: "Django", flask: "Flask", fastapi: "FastAPI", pytest: "pytest", numpy: "NumPy", pandas: "pandas", torch: "PyTorch", tensorflow: "TensorFlow", sqlalchemy: "SQLAlchemy" };
|
|
3893
|
+
var has = (files, rel) => files.has(rel);
|
|
3894
|
+
async function detectFacts(data, graph, read, extraFiles = []) {
|
|
3895
|
+
const files = /* @__PURE__ */ new Set([...Object.keys(data.files), ...extraFiles]);
|
|
3896
|
+
const langs = /* @__PURE__ */ new Map();
|
|
3897
|
+
for (const f of Object.values(data.files)) {
|
|
3898
|
+
if (f.language === "json" || f.language === "markdown" || f.language === "yaml" || f.language === "toml") continue;
|
|
3899
|
+
const e = langs.get(f.language) ?? { files: 0, lines: 0 };
|
|
3900
|
+
e.files++;
|
|
3901
|
+
e.lines += f.lines;
|
|
3902
|
+
langs.set(f.language, e);
|
|
3903
|
+
}
|
|
3904
|
+
const frameworks = [];
|
|
3905
|
+
const buildSystems = [];
|
|
3906
|
+
const packageManagers = [];
|
|
3907
|
+
const entryPoints = [];
|
|
3908
|
+
let monorepo = null;
|
|
3909
|
+
const manifests = [...files].filter((f) => /(^|\/)package\.json$/.test(f) && !f.includes("node_modules/")).slice(0, 12);
|
|
3910
|
+
for (const m of manifests) {
|
|
3911
|
+
const text3 = await read(m);
|
|
3912
|
+
if (!text3) continue;
|
|
3913
|
+
let pkg;
|
|
3914
|
+
try {
|
|
3915
|
+
pkg = JSON.parse(text3);
|
|
3916
|
+
} catch {
|
|
3917
|
+
continue;
|
|
3918
|
+
}
|
|
3919
|
+
const deps = { ...pkg["dependencies"], ...pkg["devDependencies"], ...pkg["peerDependencies"] };
|
|
3920
|
+
for (const [d, n] of Object.entries(NODE_FRAMEWORKS)) if (d in deps) frameworks.push({ name: n, evidence: `${m}: ${d}` });
|
|
3921
|
+
for (const [d, n] of Object.entries(NODE_BUILD)) if (d in deps) buildSystems.push({ name: n, evidence: `${m}: ${d}` });
|
|
3922
|
+
if (pkg["workspaces"]) monorepo = `${m} declares workspaces`;
|
|
3923
|
+
const dir = path12.posix.dirname(m) === "." ? "" : `${path12.posix.dirname(m)}/`;
|
|
3924
|
+
const add = (rel, reason) => {
|
|
3925
|
+
if (typeof rel !== "string") return;
|
|
3926
|
+
const p = path12.posix.normalize(`${dir}${rel}`.replace(/^\.\//, ""));
|
|
3927
|
+
entryPoints.push({ path: p, reason: `${m} ${reason}` });
|
|
3928
|
+
};
|
|
3929
|
+
add(pkg["main"], "main");
|
|
3930
|
+
add(pkg["module"], "module");
|
|
3931
|
+
const bin = pkg["bin"];
|
|
3932
|
+
if (typeof bin === "string") add(bin, "bin");
|
|
3933
|
+
else if (bin && typeof bin === "object") for (const v of Object.values(bin)) add(v, "bin");
|
|
3934
|
+
const scripts = pkg["scripts"] ?? {};
|
|
3935
|
+
for (const key of ["start", "dev"]) {
|
|
3936
|
+
const mm = /(?:node|tsx|ts-node|bun|deno run)\s+(?:--[\w-]+(?:=\S+)?\s+)*([\w./-]+\.[cm]?[jt]sx?)/.exec(scripts[key] ?? "");
|
|
3937
|
+
if (mm) add(mm[1], `scripts.${key}`);
|
|
3938
|
+
}
|
|
3939
|
+
}
|
|
3940
|
+
if (has(files, "pnpm-lock.yaml") || has(files, "pnpm-workspace.yaml") || extraFiles.includes("pnpm-lock.yaml")) packageManagers.push({ name: "pnpm", evidence: "pnpm-lock.yaml" });
|
|
3941
|
+
if (extraFiles.includes("yarn.lock")) packageManagers.push({ name: "Yarn", evidence: "yarn.lock" });
|
|
3942
|
+
if (extraFiles.includes("package-lock.json")) packageManagers.push({ name: "npm", evidence: "package-lock.json" });
|
|
3943
|
+
if (extraFiles.includes("bun.lockb") || extraFiles.includes("bun.lock")) packageManagers.push({ name: "Bun", evidence: "bun.lock" });
|
|
3944
|
+
if (manifests.length && packageManagers.length === 0) packageManagers.push({ name: "npm (assumed: no lockfile found)", evidence: "package.json" });
|
|
3945
|
+
if (has(files, "tsconfig.json")) buildSystems.push({ name: "TypeScript project (tsconfig.json)", evidence: "tsconfig.json" });
|
|
3946
|
+
const pyText = `${await read("requirements.txt") ?? ""}
|
|
3947
|
+
${await read("pyproject.toml") ?? ""}`.toLowerCase();
|
|
3948
|
+
for (const [d, n] of Object.entries(PY_FRAMEWORKS)) if (new RegExp(`(^|[\\s"'\\[,])${d}([\\s"'=<>~!\\],;]|$)`, "m").test(pyText)) frameworks.push({ name: n, evidence: pyText.includes(d) ? "requirements.txt / pyproject.toml" : "" });
|
|
3949
|
+
if (has(files, "pyproject.toml") || extraFiles.includes("pyproject.toml")) buildSystems.push({ name: "Python packaging (pyproject.toml)", evidence: "pyproject.toml" });
|
|
3950
|
+
if (extraFiles.includes("poetry.lock")) packageManagers.push({ name: "Poetry", evidence: "poetry.lock" });
|
|
3951
|
+
else if (pyText.trim()) packageManagers.push({ name: "pip", evidence: "requirements.txt / pyproject.toml" });
|
|
3952
|
+
for (const n of ["manage.py", "main.py", "app.py", "__main__.py", "wsgi.py", "asgi.py"]) for (const f of files) if (f === n || f.endsWith(`/${n}`)) entryPoints.push({ path: f, reason: `conventional Python entry file name (${n})` });
|
|
3953
|
+
const gradle = ["build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"].filter((f) => extraFiles.includes(f) || files.has(f));
|
|
3954
|
+
const gtext = (await Promise.all(gradle.map((g) => read(g)))).join("\n");
|
|
3955
|
+
if (gradle.length) buildSystems.push({ name: /com\.android\./.test(gtext) ? "Gradle (Android)" : "Gradle", evidence: gradle.join(", ") });
|
|
3956
|
+
if (/spring-boot/.test(gtext)) frameworks.push({ name: "Spring Boot", evidence: "Gradle files" });
|
|
3957
|
+
if (/com\.android\.(application|library)/.test(gtext)) frameworks.push({ name: "Android", evidence: "Gradle plugin com.android.*" });
|
|
3958
|
+
if (extraFiles.includes("pom.xml")) {
|
|
3959
|
+
buildSystems.push({ name: "Maven", evidence: "pom.xml" });
|
|
3960
|
+
if (/spring-boot/.test(await read("pom.xml") ?? "")) frameworks.push({ name: "Spring Boot", evidence: "pom.xml" });
|
|
3961
|
+
}
|
|
3962
|
+
if (has(files, "go.mod") || extraFiles.includes("go.mod")) buildSystems.push({ name: "Go modules", evidence: "go.mod" });
|
|
3963
|
+
if (extraFiles.includes("Cargo.toml") || has(files, "Cargo.toml")) {
|
|
3964
|
+
buildSystems.push({ name: "Cargo", evidence: "Cargo.toml" });
|
|
3965
|
+
const ct = await read("Cargo.toml") ?? "";
|
|
3966
|
+
for (const [d, n] of [["tokio", "Tokio"], ["actix-web", "Actix Web"], ["axum", "Axum"], ["rocket", "Rocket"]]) if (new RegExp(`^${d}\\b`, "m").test(ct)) frameworks.push({ name: n, evidence: "Cargo.toml" });
|
|
3967
|
+
}
|
|
3968
|
+
if (extraFiles.includes("CMakeLists.txt")) buildSystems.push({ name: "CMake", evidence: "CMakeLists.txt" });
|
|
3969
|
+
if (extraFiles.includes("Makefile")) buildSystems.push({ name: "Make", evidence: "Makefile" });
|
|
3970
|
+
if (extraFiles.includes("Dockerfile")) buildSystems.push({ name: "Docker", evidence: "Dockerfile" });
|
|
3971
|
+
for (const f of Object.values(data.files)) {
|
|
3972
|
+
if (f.language === "go" && f.notes.some((n) => n === "package main") && f.symbols.some((s) => s.name === "main" && s.kind === "function")) entryPoints.push({ path: f.path, reason: "Go package main with func main" });
|
|
3973
|
+
else if (f.language === "rust" && /(^|\/)src\/(main|lib)\.rs$/.test(f.path)) entryPoints.push({ path: f.path, reason: `Rust crate root (${path12.posix.basename(f.path)})` });
|
|
3974
|
+
else if ((f.language === "java" || f.language === "kotlin") && f.symbols.some((s) => s.name === "main" && (s.kind === "method" || s.kind === "function"))) entryPoints.push({ path: f.path, reason: "defines a main function" });
|
|
3975
|
+
else if ((f.language === "c" || f.language === "cpp") && f.symbols.some((s) => s.name === "main" && s.kind === "function")) entryPoints.push({ path: f.path, reason: "defines main()" });
|
|
3976
|
+
else if ((f.language === "typescript" || f.language === "javascript") && /(^|\/)src\/(index|main|cli\/index)\.[cm]?[jt]sx?$/.test(f.path)) entryPoints.push({ path: f.path, reason: "conventional entry file name" });
|
|
3977
|
+
}
|
|
3978
|
+
if (extraFiles.some((f) => f.endsWith("AndroidManifest.xml"))) entryPoints.push({ path: extraFiles.find((f) => f.endsWith("AndroidManifest.xml")), reason: "Android manifest (declares activities)" });
|
|
3979
|
+
void graph;
|
|
3980
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3981
|
+
const uniq = entryPoints.filter((e) => seen.has(e.path) ? false : (seen.add(e.path), true));
|
|
3982
|
+
const dedupe = (l) => l.filter((d, i) => l.findIndex((x) => x.name === d.name) === i);
|
|
3983
|
+
return { languages: [...langs.entries()].map(([id, v]) => ({ id, ...v })).sort((a, b) => b.lines - a.lines), frameworks: dedupe(frameworks), buildSystems: dedupe(buildSystems), packageManagers: dedupe(packageManagers), entryPoints: uniq, monorepo };
|
|
3984
|
+
}
|
|
3985
|
+
|
|
3986
|
+
// src/intelligence/code-intel.ts
|
|
3987
|
+
var MANIFESTS = ["package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "pnpm-workspace.yaml", "bun.lockb", "bun.lock", "tsconfig.json", "requirements.txt", "pyproject.toml", "poetry.lock", "Pipfile", "setup.py", "go.mod", "go.sum", "Cargo.toml", "Cargo.lock", "pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts", "CMakeLists.txt", "Makefile", "Dockerfile", "README.md", "app/build.gradle", "app/build.gradle.kts", "app/src/main/AndroidManifest.xml"];
|
|
3988
|
+
var CodeIntel = class _CodeIntel {
|
|
3989
|
+
root;
|
|
3990
|
+
indexer;
|
|
3991
|
+
languages;
|
|
3992
|
+
validator;
|
|
3993
|
+
#o;
|
|
3994
|
+
#graph = null;
|
|
3995
|
+
constructor(o, v, store) {
|
|
3996
|
+
this.#o = o;
|
|
3997
|
+
this.root = v.root;
|
|
3998
|
+
this.validator = v;
|
|
3999
|
+
this.languages = o.languages ?? defaultLanguages;
|
|
4000
|
+
this.indexer = new Indexer({ validator: v, store, languages: this.languages, maxFiles: o.advanced().indexing.maxFiles, maxFileBytes: Math.min(o.advanced().indexing.maxFileBytes, o.filesystem().maxFileBytes), ignoredDirs: o.filesystem().ignoredDirs, ignoredPatterns: o.filesystem().ignoredPatterns });
|
|
4001
|
+
}
|
|
4002
|
+
static async open(o) {
|
|
4003
|
+
const v = await PathValidator.create(o.root);
|
|
4004
|
+
const pid = await projectIdFor(v.root, o.os);
|
|
4005
|
+
return new _CodeIntel(o, v, new IndexStore(o.dataDir, pid.id));
|
|
4006
|
+
}
|
|
4007
|
+
get settings() {
|
|
4008
|
+
return this.#o.advanced();
|
|
4009
|
+
}
|
|
4010
|
+
/** Text of a project file through the safe reader, or null (sensitive, binary, too large, missing). */
|
|
4011
|
+
read = async (rel) => {
|
|
4012
|
+
try {
|
|
4013
|
+
return (await readTextFile(this.validator, rel, { maxBytes: Math.min(this.#o.advanced().indexing.maxFileBytes, this.#o.filesystem().maxFileBytes) })).content;
|
|
4014
|
+
} catch {
|
|
4015
|
+
return null;
|
|
4016
|
+
}
|
|
4017
|
+
};
|
|
4018
|
+
async index(o) {
|
|
4019
|
+
this.#graph = null;
|
|
4020
|
+
return this.indexer.update(o);
|
|
4021
|
+
}
|
|
4022
|
+
/** The index to answer questions with: the stored one, or one built in memory just now (never written without being asked). */
|
|
4023
|
+
async data(signal) {
|
|
4024
|
+
return this.indexer.ensure(signal);
|
|
4025
|
+
}
|
|
4026
|
+
async graph(signal) {
|
|
4027
|
+
const d = await this.data(signal);
|
|
4028
|
+
if (!this.#graph || this.#graph.key !== d.updatedAt) this.#graph = { key: d.updatedAt, g: buildGraph(d) };
|
|
4029
|
+
return this.#graph.g;
|
|
4030
|
+
}
|
|
4031
|
+
async file(rel) {
|
|
4032
|
+
const d = await this.data();
|
|
4033
|
+
return d.files[rel.replace(/\\/g, "/").replace(/^\.\//, "")] ?? null;
|
|
4034
|
+
}
|
|
4035
|
+
/** Non-source project files that matter for detection (manifests, lockfiles), by name, at the root and one level down. */
|
|
4036
|
+
async manifestFiles() {
|
|
4037
|
+
const out = [];
|
|
4038
|
+
for (const m of MANIFESTS) {
|
|
4039
|
+
try {
|
|
4040
|
+
await fsp11.lstat(path13.join(this.root, ...m.split("/")));
|
|
4041
|
+
out.push(m);
|
|
4042
|
+
} catch {
|
|
4043
|
+
}
|
|
4044
|
+
}
|
|
4045
|
+
return out;
|
|
4046
|
+
}
|
|
4047
|
+
async facts(signal) {
|
|
4048
|
+
return detectFacts(await this.data(signal), await this.graph(signal), this.read, await this.manifestFiles());
|
|
4049
|
+
}
|
|
4050
|
+
async architecture(signal) {
|
|
4051
|
+
return summarize(await this.data(signal), await this.graph(signal), await this.facts(signal));
|
|
4052
|
+
}
|
|
4053
|
+
async search(query, o = {}) {
|
|
4054
|
+
return searchFiles2(await this.data(), query, o);
|
|
4055
|
+
}
|
|
4056
|
+
async symbols(name, o = {}) {
|
|
4057
|
+
return searchSymbols(await this.data(), name, o);
|
|
4058
|
+
}
|
|
4059
|
+
async references(name, o = {}) {
|
|
4060
|
+
return findReferences(await this.data(o.signal), this.languages, this.read, name, o);
|
|
4061
|
+
}
|
|
4062
|
+
async impact(rel) {
|
|
4063
|
+
return dependentsOf(await this.graph(), rel);
|
|
4064
|
+
}
|
|
4065
|
+
async context(query, o = {}) {
|
|
4066
|
+
return retrieveContext(await this.data(o.signal), this.read, query, { budgetChars: o.budgetChars ?? this.#o.advanced().indexing.contextChars, ...o.include ? { include: o.include } : {}, ...o.signal ? { signal: o.signal } : {} });
|
|
4067
|
+
}
|
|
4068
|
+
};
|
|
4069
|
+
|
|
4070
|
+
// src/lsp/manager.ts
|
|
4071
|
+
import path14 from "path";
|
|
4072
|
+
import { fileURLToPath, pathToFileURL } from "url";
|
|
4073
|
+
|
|
4074
|
+
// src/lsp/catalog.ts
|
|
4075
|
+
var KNOWN_SERVERS = [
|
|
4076
|
+
{ languages: ["typescript", "javascript"], name: "TypeScript language server", command: "typescript-language-server", args: ["--stdio"], source: "known", installHint: "npm install -g typescript-language-server typescript" },
|
|
4077
|
+
{ languages: ["python"], name: "Pyright", command: "pyright-langserver", args: ["--stdio"], source: "known", installHint: "npm install -g pyright (or: pip install python-lsp-server, then configure pylsp)" },
|
|
4078
|
+
{ languages: ["python"], name: "python-lsp-server", command: "pylsp", args: [], source: "known", installHint: "pip install python-lsp-server" },
|
|
4079
|
+
{ languages: ["java"], name: "Eclipse JDT language server", command: "jdtls", args: [], source: "known", installHint: "see https://github.com/eclipse-jdtls/eclipse.jdt.ls (needs a JDK)" },
|
|
4080
|
+
{ languages: ["kotlin"], name: "Kotlin language server", command: "kotlin-language-server", args: [], source: "known", installHint: "see https://github.com/fwcd/kotlin-language-server" },
|
|
4081
|
+
{ languages: ["c", "cpp"], name: "clangd", command: "clangd", args: [], source: "known", installHint: "install clangd with your package manager (Termux: pkg install clang)" },
|
|
4082
|
+
{ languages: ["go"], name: "gopls", command: "gopls", args: [], source: "known", installHint: "go install golang.org/x/tools/gopls@latest" },
|
|
4083
|
+
{ languages: ["rust"], name: "rust-analyzer", command: "rust-analyzer", args: [], source: "known", installHint: "rustup component add rust-analyzer" },
|
|
4084
|
+
{ languages: ["html"], name: "HTML language server", command: "vscode-html-language-server", args: ["--stdio"], source: "known", installHint: "npm install -g vscode-langservers-extracted" },
|
|
4085
|
+
{ languages: ["css"], name: "CSS language server", command: "vscode-css-language-server", args: ["--stdio"], source: "known", installHint: "npm install -g vscode-langservers-extracted" },
|
|
4086
|
+
{ languages: ["json"], name: "JSON language server", command: "vscode-json-language-server", args: ["--stdio"], source: "known", installHint: "npm install -g vscode-langservers-extracted" }
|
|
4087
|
+
];
|
|
4088
|
+
|
|
4089
|
+
// src/lsp/lsp-process.ts
|
|
4090
|
+
import { spawn as spawn3 } from "child_process";
|
|
4091
|
+
|
|
4092
|
+
// src/lsp/jsonrpc.ts
|
|
4093
|
+
var MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
4094
|
+
function encodeMessage(msg) {
|
|
4095
|
+
const body = Buffer.from(JSON.stringify(msg), "utf8");
|
|
4096
|
+
return Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r
|
|
4097
|
+
\r
|
|
4098
|
+
`, "ascii"), body]);
|
|
4099
|
+
}
|
|
4100
|
+
var MessageParser = class {
|
|
4101
|
+
#buf = Buffer.alloc(0);
|
|
4102
|
+
push(chunk) {
|
|
4103
|
+
this.#buf = this.#buf.length ? Buffer.concat([this.#buf, chunk]) : chunk;
|
|
4104
|
+
const out = [];
|
|
4105
|
+
for (; ; ) {
|
|
4106
|
+
const headerEnd = this.#buf.indexOf("\r\n\r\n");
|
|
4107
|
+
if (headerEnd === -1) {
|
|
4108
|
+
if (this.#buf.length > 8192) throw new Error("language server sent an oversized header");
|
|
4109
|
+
return out;
|
|
4110
|
+
}
|
|
4111
|
+
const header = this.#buf.subarray(0, headerEnd).toString("ascii");
|
|
4112
|
+
const m = /Content-Length:\s*(\d+)/i.exec(header);
|
|
4113
|
+
if (!m) throw new Error("language server sent a message without Content-Length");
|
|
4114
|
+
const len = Number(m[1]);
|
|
4115
|
+
if (len > MAX_MESSAGE_BYTES) throw new Error("language server sent a message larger than the limit");
|
|
4116
|
+
const start = headerEnd + 4;
|
|
4117
|
+
if (this.#buf.length < start + len) return out;
|
|
4118
|
+
const body = this.#buf.subarray(start, start + len).toString("utf8");
|
|
4119
|
+
this.#buf = this.#buf.subarray(start + len);
|
|
4120
|
+
try {
|
|
4121
|
+
out.push(JSON.parse(body));
|
|
4122
|
+
} catch {
|
|
4123
|
+
throw new Error("language server sent invalid JSON");
|
|
4124
|
+
}
|
|
4125
|
+
}
|
|
4126
|
+
}
|
|
4127
|
+
};
|
|
4128
|
+
|
|
4129
|
+
// src/lsp/types.ts
|
|
4130
|
+
var LspUnavailable = class extends Error {
|
|
4131
|
+
reason;
|
|
4132
|
+
hint;
|
|
4133
|
+
constructor(reason, message, hint) {
|
|
4134
|
+
super(message);
|
|
4135
|
+
this.name = "LspUnavailable";
|
|
4136
|
+
this.reason = reason;
|
|
4137
|
+
this.hint = hint;
|
|
4138
|
+
}
|
|
4139
|
+
};
|
|
4140
|
+
|
|
4141
|
+
// src/lsp/lsp-process.ts
|
|
4142
|
+
var ENV_ALLOW = ["PATH", "Path", "PATHEXT", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "SystemRoot", "ComSpec", "PREFIX", "JAVA_HOME", "GOPATH", "GOROOT", "GOCACHE", "CARGO_HOME", "RUSTUP_HOME", "NODE_PATH"];
|
|
4143
|
+
function serverEnv(env) {
|
|
4144
|
+
const out = {};
|
|
4145
|
+
for (const k of ENV_ALLOW) {
|
|
4146
|
+
const v = env[k];
|
|
4147
|
+
if (v !== void 0) out[k] = v;
|
|
4148
|
+
}
|
|
4149
|
+
return out;
|
|
4150
|
+
}
|
|
4151
|
+
var LspConnection = class _LspConnection {
|
|
4152
|
+
#child;
|
|
4153
|
+
#parser = new MessageParser();
|
|
4154
|
+
#pending = /* @__PURE__ */ new Map();
|
|
4155
|
+
#notify = /* @__PURE__ */ new Map();
|
|
4156
|
+
#next = 1;
|
|
4157
|
+
#closed = null;
|
|
4158
|
+
stderrTail = "";
|
|
4159
|
+
constructor(child) {
|
|
4160
|
+
this.#child = child;
|
|
4161
|
+
child.stdout.on("data", (c) => this.#onData(c));
|
|
4162
|
+
child.stderr.on("data", (c) => {
|
|
4163
|
+
this.stderrTail = (this.stderrTail + c.toString("utf8")).slice(-2e3);
|
|
4164
|
+
});
|
|
4165
|
+
child.on("error", (e) => this.#fail(new LspUnavailable("start-failed", `The language server could not be started: ${e.message}`)));
|
|
4166
|
+
child.on("exit", (code, sig) => this.#fail(new LspUnavailable("protocol", `The language server stopped (${sig ?? `exit ${code ?? "?"}`}).`)));
|
|
4167
|
+
child.stdin.on("error", () => void 0);
|
|
4168
|
+
}
|
|
4169
|
+
static start(file, args, cwd, env) {
|
|
4170
|
+
const child = spawn3(file, [...args], { cwd, env: serverEnv(env), stdio: ["pipe", "pipe", "pipe"], windowsHide: true, shell: false });
|
|
4171
|
+
return new _LspConnection(child);
|
|
4172
|
+
}
|
|
4173
|
+
get alive() {
|
|
4174
|
+
return this.#closed === null;
|
|
4175
|
+
}
|
|
4176
|
+
#fail(err) {
|
|
4177
|
+
if (this.#closed) return;
|
|
4178
|
+
this.#closed = err;
|
|
4179
|
+
for (const p of this.#pending.values()) {
|
|
4180
|
+
clearTimeout(p.timer);
|
|
4181
|
+
p.reject(err);
|
|
4182
|
+
}
|
|
4183
|
+
this.#pending.clear();
|
|
4184
|
+
}
|
|
4185
|
+
#onData(chunk) {
|
|
4186
|
+
let msgs;
|
|
4187
|
+
try {
|
|
4188
|
+
msgs = this.#parser.push(chunk);
|
|
4189
|
+
} catch (e) {
|
|
4190
|
+
this.#fail(new LspUnavailable("protocol", e.message));
|
|
4191
|
+
this.kill();
|
|
4192
|
+
return;
|
|
4193
|
+
}
|
|
4194
|
+
for (const m of msgs) {
|
|
4195
|
+
if (typeof m["id"] === "number" && ("result" in m || "error" in m) && !("method" in m)) {
|
|
4196
|
+
const p = this.#pending.get(m["id"]);
|
|
4197
|
+
if (!p) continue;
|
|
4198
|
+
this.#pending.delete(m["id"]);
|
|
4199
|
+
clearTimeout(p.timer);
|
|
4200
|
+
if (m["error"]) p.reject(new LspUnavailable("protocol", `The language server refused ${p.method}: ${String(m["error"]["message"] ?? "error").slice(0, 200)}`));
|
|
4201
|
+
else p.resolve(m["result"]);
|
|
4202
|
+
} else if (typeof m["method"] === "string") {
|
|
4203
|
+
if (m["id"] !== void 0) this.#send({ jsonrpc: "2.0", id: m["id"], result: null });
|
|
4204
|
+
for (const h of this.#notify.get(m["method"]) ?? []) h(m["params"]);
|
|
4205
|
+
}
|
|
4206
|
+
}
|
|
4207
|
+
}
|
|
4208
|
+
#send(msg) {
|
|
4209
|
+
if (this.#closed || !this.#child.stdin.writable) return;
|
|
4210
|
+
this.#child.stdin.write(encodeMessage(msg));
|
|
4211
|
+
}
|
|
4212
|
+
on(method, handler) {
|
|
4213
|
+
this.#notify.set(method, [...this.#notify.get(method) ?? [], handler]);
|
|
4214
|
+
}
|
|
4215
|
+
notify(method, params) {
|
|
4216
|
+
this.#send({ jsonrpc: "2.0", method, params });
|
|
4217
|
+
}
|
|
4218
|
+
request(method, params, timeoutMs, signal) {
|
|
4219
|
+
if (this.#closed) return Promise.reject(this.#closed);
|
|
4220
|
+
if (signal?.aborted) return Promise.reject(new LspUnavailable("cancelled", "Cancelled."));
|
|
4221
|
+
const id = this.#next++;
|
|
4222
|
+
return new Promise((resolve, reject) => {
|
|
4223
|
+
const onAbort = () => {
|
|
4224
|
+
this.#pending.delete(id);
|
|
4225
|
+
clearTimeout(timer);
|
|
4226
|
+
this.notify("$/cancelRequest", { id });
|
|
4227
|
+
reject(new LspUnavailable("cancelled", "Cancelled."));
|
|
4228
|
+
};
|
|
4229
|
+
const timer = setTimeout(() => {
|
|
4230
|
+
this.#pending.delete(id);
|
|
4231
|
+
signal?.removeEventListener("abort", onAbort);
|
|
4232
|
+
this.notify("$/cancelRequest", { id });
|
|
4233
|
+
reject(new LspUnavailable("timeout", `The language server did not answer ${method} within ${Math.round(timeoutMs / 1e3)}s.`, "Raise advanced.lsp.requestTimeoutSeconds, or use the index-based fallback."));
|
|
4234
|
+
}, timeoutMs);
|
|
4235
|
+
timer.unref?.();
|
|
4236
|
+
this.#pending.set(id, { resolve: (v) => (signal?.removeEventListener("abort", onAbort), resolve(v)), reject: (e) => (signal?.removeEventListener("abort", onAbort), reject(e)), timer, method });
|
|
4237
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
4238
|
+
this.#send({ jsonrpc: "2.0", id, method, params });
|
|
4239
|
+
});
|
|
4240
|
+
}
|
|
4241
|
+
kill() {
|
|
4242
|
+
try {
|
|
4243
|
+
this.#child.kill();
|
|
4244
|
+
} catch {
|
|
4245
|
+
}
|
|
4246
|
+
}
|
|
4247
|
+
/** Ask the server to shut down politely, then make sure it is gone. */
|
|
4248
|
+
async stop() {
|
|
4249
|
+
if (this.alive) {
|
|
4250
|
+
try {
|
|
4251
|
+
await this.request("shutdown", null, 2e3);
|
|
4252
|
+
this.notify("exit", null);
|
|
4253
|
+
} catch {
|
|
4254
|
+
}
|
|
4255
|
+
}
|
|
4256
|
+
await new Promise((resolve) => {
|
|
4257
|
+
if (this.#child.exitCode !== null || this.#child.killed) return resolve();
|
|
4258
|
+
const t = setTimeout(() => (this.kill(), resolve()), 1e3);
|
|
4259
|
+
t.unref?.();
|
|
4260
|
+
this.#child.once("exit", () => (clearTimeout(t), resolve()));
|
|
4261
|
+
this.kill();
|
|
4262
|
+
});
|
|
4263
|
+
this.#fail(new LspUnavailable("cancelled", "stopped"));
|
|
4264
|
+
}
|
|
4265
|
+
};
|
|
4266
|
+
|
|
4267
|
+
// src/lsp/manager.ts
|
|
4268
|
+
var SEVERITY = ["error", "error", "warning", "information", "hint"];
|
|
4269
|
+
var KINDS = ["", "file", "module", "namespace", "package", "class", "method", "property", "field", "constructor", "enum", "interface", "function", "variable", "constant", "string", "number", "boolean", "array", "object", "key", "null", "enum member", "struct", "event", "operator", "type parameter"];
|
|
4270
|
+
var LANG_ID = { typescript: "typescript", javascript: "javascript", python: "python", java: "java", kotlin: "kotlin", c: "c", cpp: "cpp", go: "go", rust: "rust", html: "html", css: "css", json: "json" };
|
|
4271
|
+
var LspManager = class {
|
|
4272
|
+
#o;
|
|
4273
|
+
#conns = /* @__PURE__ */ new Map();
|
|
4274
|
+
#diags = /* @__PURE__ */ new Map();
|
|
4275
|
+
#opened = /* @__PURE__ */ new Set();
|
|
4276
|
+
constructor(o) {
|
|
4277
|
+
this.#o = o;
|
|
4278
|
+
}
|
|
4279
|
+
get enabled() {
|
|
4280
|
+
return this.#o.settings().lsp.enabled;
|
|
4281
|
+
}
|
|
4282
|
+
/** The server entries for a language: your configuration first, then well-known names. */
|
|
4283
|
+
specsFor(lang) {
|
|
4284
|
+
const out = [];
|
|
4285
|
+
const cfg = this.#o.settings().lsp.servers[lang];
|
|
4286
|
+
if (cfg) out.push({ languages: [lang], name: `configured (${cfg.command})`, command: cfg.command, args: cfg.args, source: "configured", installHint: null });
|
|
4287
|
+
for (const k of KNOWN_SERVERS) if (k.languages.includes(lang)) out.push(k);
|
|
4288
|
+
return out;
|
|
4289
|
+
}
|
|
4290
|
+
async #resolve(spec) {
|
|
4291
|
+
try {
|
|
4292
|
+
const r = await resolveExecutable({ program: spec.command, cwdAbs: this.#o.intel.root, root: this.#o.intel.root, env: this.#o.env, windows: this.#o.windows });
|
|
4293
|
+
return r.cmdScript ? null : r.file;
|
|
4294
|
+
} catch {
|
|
4295
|
+
return null;
|
|
4296
|
+
}
|
|
4297
|
+
}
|
|
4298
|
+
async serverFor(lang) {
|
|
4299
|
+
for (const s of this.specsFor(lang)) {
|
|
4300
|
+
const file = await this.#resolve(s);
|
|
4301
|
+
if (file) return { spec: s, file };
|
|
4302
|
+
}
|
|
4303
|
+
return null;
|
|
4304
|
+
}
|
|
4305
|
+
/** What is installed, per language found in this project. Starts nothing. */
|
|
4306
|
+
async status(languages) {
|
|
4307
|
+
const rows = [];
|
|
4308
|
+
for (const language of languages) {
|
|
4309
|
+
const specs = this.specsFor(language);
|
|
4310
|
+
if (specs.length === 0) {
|
|
4311
|
+
rows.push({ language, server: null, command: null, source: null, available: false, resolvedPath: null, installHint: null, running: false });
|
|
4312
|
+
continue;
|
|
4313
|
+
}
|
|
4314
|
+
const found = await this.serverFor(language);
|
|
4315
|
+
const spec = found?.spec ?? specs[0];
|
|
4316
|
+
rows.push({ language, server: spec.name, command: spec.command, source: found ? spec.source === "known" ? "detected" : spec.source : spec.source, available: found !== null, resolvedPath: found?.file ?? null, installHint: found ? null : spec.installHint, running: this.#conns.has(`${found?.spec.command ?? ""}`) });
|
|
4317
|
+
}
|
|
4318
|
+
return rows;
|
|
4319
|
+
}
|
|
4320
|
+
async #connect(lang, signal) {
|
|
4321
|
+
if (!this.enabled) throw new LspUnavailable("disabled", "Language servers are turned off.", "Turn them on with: zg config set advanced.lsp.enabled true");
|
|
4322
|
+
const found = await this.serverFor(lang);
|
|
4323
|
+
if (!found) {
|
|
4324
|
+
const s = this.specsFor(lang)[0];
|
|
4325
|
+
throw new LspUnavailable("no-server", `No language server was found for ${lang}.`, s?.installHint ? `Install one yourself (zg never installs it): ${s.installHint}` : "Set one with: zg lsp configure <language> <command> [args...]");
|
|
4326
|
+
}
|
|
4327
|
+
const key = `${found.spec.command}\0${found.spec.args.join(" ")}`;
|
|
4328
|
+
let p = this.#conns.get(key);
|
|
4329
|
+
if (!p) {
|
|
4330
|
+
p = this.#init(found.file, found.spec, signal);
|
|
4331
|
+
this.#conns.set(key, p);
|
|
4332
|
+
p.catch(() => this.#conns.delete(key));
|
|
4333
|
+
}
|
|
4334
|
+
const conn = await p;
|
|
4335
|
+
if (!conn.alive) {
|
|
4336
|
+
this.#conns.delete(key);
|
|
4337
|
+
throw new LspUnavailable("start-failed", "The language server is no longer running.");
|
|
4338
|
+
}
|
|
4339
|
+
return { conn, name: found.spec.name };
|
|
4340
|
+
}
|
|
4341
|
+
async #init(file, spec, signal) {
|
|
4342
|
+
const s = this.#o.settings().lsp;
|
|
4343
|
+
const conn = LspConnection.start(file, spec.args, this.#o.intel.root, this.#o.env);
|
|
4344
|
+
conn.on("textDocument/publishDiagnostics", (params) => {
|
|
4345
|
+
const p = params;
|
|
4346
|
+
const abs = safeFromUri(String(p["uri"] ?? ""));
|
|
4347
|
+
const rel = abs ? this.#rel(abs) : null;
|
|
4348
|
+
if (!rel) return;
|
|
4349
|
+
this.#diags.set(
|
|
4350
|
+
rel,
|
|
4351
|
+
(p["diagnostics"] ?? []).map((d) => ({ path: rel, line: (d["range"]?.start?.line ?? 0) + 1, column: (d["range"]?.start?.character ?? 0) + 1, severity: SEVERITY[d["severity"] ?? 1] ?? "error", message: String(d["message"] ?? "").slice(0, 500), code: d["code"] === void 0 ? null : String(d["code"]), source: d["source"] ? String(d["source"]) : null }))
|
|
4352
|
+
);
|
|
4353
|
+
});
|
|
4354
|
+
try {
|
|
4355
|
+
await conn.request("initialize", { processId: process.pid, rootUri: pathToFileURL(this.#o.intel.root).href, workspaceFolders: [{ uri: pathToFileURL(this.#o.intel.root).href, name: path14.basename(this.#o.intel.root) }], capabilities: { textDocument: { publishDiagnostics: {}, hover: { contentFormat: ["plaintext", "markdown"] }, definition: {}, references: {}, documentSymbol: { hierarchicalDocumentSymbolSupport: false }, completion: { completionItem: { snippetSupport: false } }, rename: { prepareSupport: true } }, workspace: { symbol: {}, workspaceFolders: true } } }, s.startTimeoutSeconds * 1e3, signal);
|
|
4356
|
+
conn.notify("initialized", {});
|
|
4357
|
+
} catch (e) {
|
|
4358
|
+
await conn.stop();
|
|
4359
|
+
throw e instanceof LspUnavailable ? e : new LspUnavailable("start-failed", String(e.message));
|
|
4360
|
+
}
|
|
4361
|
+
return conn;
|
|
4362
|
+
}
|
|
4363
|
+
#rel(abs) {
|
|
4364
|
+
const r = path14.relative(this.#o.intel.root, abs).split(path14.sep).join("/");
|
|
4365
|
+
return r === "" || r.startsWith("..") || path14.isAbsolute(r) ? null : r;
|
|
4366
|
+
}
|
|
4367
|
+
#abs(rel) {
|
|
4368
|
+
const abs = path14.resolve(this.#o.intel.root, rel);
|
|
4369
|
+
if (this.#rel(abs) === null) throw new LspUnavailable("outside-project", `${rel} is outside the project.`);
|
|
4370
|
+
return abs;
|
|
4371
|
+
}
|
|
4372
|
+
async #open(conn, rel, lang) {
|
|
4373
|
+
const uri = pathToFileURL(this.#abs(rel)).href;
|
|
4374
|
+
if (!this.#opened.has(uri)) {
|
|
4375
|
+
const text3 = await this.#o.intel.read(rel);
|
|
4376
|
+
if (text3 === null) throw new LspUnavailable("unsupported", `${rel} cannot be read (protected, binary, too large or missing).`);
|
|
4377
|
+
conn.notify("textDocument/didOpen", { textDocument: { uri, languageId: LANG_ID[lang] ?? lang, version: 1, text: text3 } });
|
|
4378
|
+
this.#opened.add(uri);
|
|
4379
|
+
}
|
|
4380
|
+
return uri;
|
|
4381
|
+
}
|
|
4382
|
+
async #lang(rel) {
|
|
4383
|
+
const a = this.#o.intel.languages.detect(rel);
|
|
4384
|
+
if (!a) throw new LspUnavailable("unsupported", `zg does not know the language of ${rel}.`);
|
|
4385
|
+
return a.id;
|
|
4386
|
+
}
|
|
4387
|
+
/** Runs `semantic`; when a server is not usable, runs `fallback` and says why. Never reports a fallback as semantic. */
|
|
4388
|
+
async #either(rel, semantic, fallback, signal) {
|
|
4389
|
+
let lang;
|
|
4390
|
+
try {
|
|
4391
|
+
lang = await this.#lang(rel);
|
|
4392
|
+
const { conn, name } = await this.#connect(lang, signal);
|
|
4393
|
+
const uri = await this.#open(conn, rel, lang);
|
|
4394
|
+
return { method: "semantic (language server)", server: name, items: await semantic(conn, uri, name), note: null };
|
|
4395
|
+
} catch (e) {
|
|
4396
|
+
if (!(e instanceof LspUnavailable) || e.reason === "cancelled" || e.reason === "outside-project") throw e;
|
|
4397
|
+
return { method: "textual (index, not a language server)", server: null, items: await fallback(), note: `${e.message}${e.hint ? ` ${e.hint}` : ""} Showing index results instead; they are text patterns, not a compiler's answer.` };
|
|
4398
|
+
}
|
|
4399
|
+
}
|
|
4400
|
+
#t() {
|
|
4401
|
+
return this.#o.settings().lsp.requestTimeoutSeconds * 1e3;
|
|
4402
|
+
}
|
|
4403
|
+
async #wordAt(rel, line, column) {
|
|
4404
|
+
const text3 = await this.#o.intel.read(rel);
|
|
4405
|
+
const l = text3?.split(/\r?\n/)[line - 1];
|
|
4406
|
+
if (l === void 0) return null;
|
|
4407
|
+
const re = /[A-Za-z_$][A-Za-z0-9_$]*/g;
|
|
4408
|
+
for (let m = re.exec(l); m; m = re.exec(l)) if (column - 1 >= m.index && column - 1 <= m.index + m[0].length) return m[0];
|
|
4409
|
+
return null;
|
|
4410
|
+
}
|
|
4411
|
+
#locs(res) {
|
|
4412
|
+
const arr = Array.isArray(res) ? res : res ? [res] : [];
|
|
4413
|
+
const out = [];
|
|
4414
|
+
for (const r of arr) {
|
|
4415
|
+
const uri = String(r["uri"] ?? r["targetUri"] ?? "");
|
|
4416
|
+
const range = r["range"] ?? r["targetSelectionRange"] ?? r["targetRange"];
|
|
4417
|
+
const abs = safeFromUri(uri);
|
|
4418
|
+
const rel = abs ? this.#rel(abs) : null;
|
|
4419
|
+
if (!rel || !range) continue;
|
|
4420
|
+
out.push({ path: rel, line: range.start.line + 1, column: range.start.character + 1, endLine: range.end.line + 1, endColumn: range.end.character + 1 });
|
|
4421
|
+
}
|
|
4422
|
+
return out;
|
|
4423
|
+
}
|
|
4424
|
+
async definition(rel, line, column, signal) {
|
|
4425
|
+
return this.#either(
|
|
4426
|
+
rel,
|
|
4427
|
+
async (c, uri) => this.#locs(await c.request("textDocument/definition", { textDocument: { uri }, position: { line: line - 1, character: column - 1 } }, this.#t(), signal)),
|
|
4428
|
+
async () => {
|
|
4429
|
+
const w = await this.#wordAt(rel, line, column);
|
|
4430
|
+
return w ? (await this.#o.intel.symbols(w, { limit: 20 })).filter((h) => h.symbol.name === w).map((h) => ({ path: h.path, line: h.symbol.line, column: 1, endLine: h.symbol.endLine, endColumn: 1 })) : [];
|
|
4431
|
+
},
|
|
4432
|
+
signal
|
|
4433
|
+
);
|
|
4434
|
+
}
|
|
4435
|
+
async references(rel, line, column, signal) {
|
|
4436
|
+
return this.#either(
|
|
4437
|
+
rel,
|
|
4438
|
+
async (c, uri) => this.#locs(await c.request("textDocument/references", { textDocument: { uri }, position: { line: line - 1, character: column - 1 }, context: { includeDeclaration: true } }, this.#t(), signal)),
|
|
4439
|
+
async () => {
|
|
4440
|
+
const w = await this.#wordAt(rel, line, column);
|
|
4441
|
+
if (!w) return [];
|
|
4442
|
+
const r = await this.#o.intel.references(w, signal ? { signal } : {});
|
|
4443
|
+
return r.references.map((x) => ({ path: x.path, line: x.line, column: x.column, endLine: x.line, endColumn: x.column + w.length }));
|
|
4444
|
+
},
|
|
4445
|
+
signal
|
|
4446
|
+
);
|
|
4447
|
+
}
|
|
4448
|
+
async hover(rel, line, column, signal) {
|
|
4449
|
+
return this.#either(
|
|
4450
|
+
rel,
|
|
4451
|
+
async (c, uri) => {
|
|
4452
|
+
const r = await c.request("textDocument/hover", { textDocument: { uri }, position: { line: line - 1, character: column - 1 } }, this.#t(), signal);
|
|
4453
|
+
const cts = r?.["contents"];
|
|
4454
|
+
const text3 = typeof cts === "string" ? cts : Array.isArray(cts) ? cts.map((x) => typeof x === "string" ? x : x["value"]).join("\n") : cts?.["value"] ?? null;
|
|
4455
|
+
return text3 ? String(text3).slice(0, 2e3) : null;
|
|
4456
|
+
},
|
|
4457
|
+
async () => {
|
|
4458
|
+
const w = await this.#wordAt(rel, line, column);
|
|
4459
|
+
const h = w ? (await this.#o.intel.symbols(w, { limit: 5 })).find((x) => x.symbol.name === w) : void 0;
|
|
4460
|
+
return h ? `${h.symbol.signature} (${h.path}:${h.symbol.line})${h.symbol.doc ? `
|
|
4461
|
+
${h.symbol.doc}` : ""}` : null;
|
|
4462
|
+
},
|
|
4463
|
+
signal
|
|
4464
|
+
);
|
|
4465
|
+
}
|
|
4466
|
+
async documentSymbols(rel, signal) {
|
|
4467
|
+
return this.#either(
|
|
4468
|
+
rel,
|
|
4469
|
+
async (c, uri) => {
|
|
4470
|
+
const res = await c.request("textDocument/documentSymbol", { textDocument: { uri } }, this.#t(), signal) ?? [];
|
|
4471
|
+
const out = [];
|
|
4472
|
+
const walk2 = (s, container) => {
|
|
4473
|
+
const r = s["range"] ?? s["location"]?.range;
|
|
4474
|
+
if (!r) return;
|
|
4475
|
+
out.push({ name: String(s["name"]), kind: KINDS[s["kind"]] ?? "symbol", line: r.start.line + 1, endLine: r.end.line + 1, ...container ? { container } : {} });
|
|
4476
|
+
for (const ch of s["children"] ?? []) walk2(ch, String(s["name"]));
|
|
4477
|
+
};
|
|
4478
|
+
for (const s of res) walk2(s);
|
|
4479
|
+
return out;
|
|
4480
|
+
},
|
|
4481
|
+
async () => ((await this.#o.intel.file(rel))?.symbols ?? []).map((s) => ({ name: s.name, kind: s.kind, line: s.line, endLine: s.endLine, ...s.container ? { container: s.container } : {} })),
|
|
4482
|
+
signal
|
|
4483
|
+
);
|
|
4484
|
+
}
|
|
4485
|
+
async workspaceSymbols(query, language, signal) {
|
|
4486
|
+
const fallback = async () => (await this.#o.intel.symbols(query, { limit: 50 })).map((h) => ({ name: h.symbol.name, kind: h.symbol.kind, line: h.symbol.line, endLine: h.symbol.endLine, path: h.path }));
|
|
4487
|
+
try {
|
|
4488
|
+
const { conn, name } = await this.#connect(language, signal);
|
|
4489
|
+
const res = await conn.request("workspace/symbol", { query }, this.#t(), signal) ?? [];
|
|
4490
|
+
const items = [];
|
|
4491
|
+
for (const s of res.slice(0, 100)) {
|
|
4492
|
+
const abs = safeFromUri(String(s["location"]?.uri ?? ""));
|
|
4493
|
+
const rel = abs ? this.#rel(abs) : null;
|
|
4494
|
+
if (rel) items.push({ name: String(s["name"]), kind: KINDS[s["kind"]] ?? "symbol", line: (s["location"]?.range?.start?.line ?? 0) + 1, endLine: (s["location"]?.range?.end?.line ?? 0) + 1, path: rel });
|
|
4495
|
+
}
|
|
4496
|
+
return { method: "semantic (language server)", server: name, items, note: null };
|
|
4497
|
+
} catch (e) {
|
|
4498
|
+
if (!(e instanceof LspUnavailable) || e.reason === "cancelled") throw e;
|
|
4499
|
+
return { method: "textual (index, not a language server)", server: null, items: await fallback(), note: `${e.message}${e.hint ? ` ${e.hint}` : ""} Showing index results instead.` };
|
|
4500
|
+
}
|
|
4501
|
+
}
|
|
4502
|
+
async completion(rel, line, column, signal) {
|
|
4503
|
+
return this.#either(
|
|
4504
|
+
rel,
|
|
4505
|
+
async (c, uri) => {
|
|
4506
|
+
const r = await c.request("textDocument/completion", { textDocument: { uri }, position: { line: line - 1, character: column - 1 } }, this.#t(), signal);
|
|
4507
|
+
const list = Array.isArray(r) ? r : r?.["items"] ?? [];
|
|
4508
|
+
return list.slice(0, 50).map((i) => String(i["label"]));
|
|
4509
|
+
},
|
|
4510
|
+
async () => {
|
|
4511
|
+
const text3 = await this.#o.intel.read(rel);
|
|
4512
|
+
const l = text3?.split(/\r?\n/)[line - 1] ?? "";
|
|
4513
|
+
const prefix = /[A-Za-z_$][A-Za-z0-9_$]*$/.exec(l.slice(0, column - 1))?.[0] ?? "";
|
|
4514
|
+
return prefix ? [...new Set((await this.#o.intel.symbols(prefix, { limit: 40 })).filter((h) => h.symbol.name.startsWith(prefix)).map((h) => h.symbol.name))] : [];
|
|
4515
|
+
},
|
|
4516
|
+
signal
|
|
4517
|
+
);
|
|
4518
|
+
}
|
|
4519
|
+
/** Diagnostics a server publishes for a file. Index fallback has none: zg does not compile code, and says so. */
|
|
4520
|
+
async diagnostics(rel, signal) {
|
|
4521
|
+
return this.#either(
|
|
4522
|
+
rel,
|
|
4523
|
+
async (c) => {
|
|
4524
|
+
const deadline = Date.now() + Math.min(this.#t(), 5e3);
|
|
4525
|
+
while (!this.#diags.has(rel) && Date.now() < deadline) {
|
|
4526
|
+
if (signal?.aborted) throw new LspUnavailable("cancelled", "Cancelled.");
|
|
4527
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
4528
|
+
}
|
|
4529
|
+
void c;
|
|
4530
|
+
return this.#diags.get(rel) ?? [];
|
|
4531
|
+
},
|
|
4532
|
+
async () => [],
|
|
4533
|
+
signal
|
|
4534
|
+
);
|
|
4535
|
+
}
|
|
4536
|
+
/**
|
|
4537
|
+
* Prepares a rename and returns the edits it would make, WITHOUT applying anything. With a server the edits are the server's;
|
|
4538
|
+
* without one they are every textual mention of the name (flagged as such) so the caller can show a preview and warn.
|
|
4539
|
+
*/
|
|
4540
|
+
async renamePreview(rel, line, column, newName, signal) {
|
|
4541
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(newName)) throw new LspUnavailable("unsupported", "The new name must be a plain identifier (letters, digits, _ and $).");
|
|
4542
|
+
return this.#either(
|
|
4543
|
+
rel,
|
|
4544
|
+
async (c, uri) => {
|
|
4545
|
+
const pos = { line: line - 1, character: column - 1 };
|
|
4546
|
+
const prep = await c.request("textDocument/prepareRename", { textDocument: { uri }, position: pos }, this.#t(), signal).catch(() => void 0);
|
|
4547
|
+
if (prep === null) throw new LspUnavailable("unsupported", "The language server says this position cannot be renamed.");
|
|
4548
|
+
const we = await c.request("textDocument/rename", { textDocument: { uri }, position: pos, newName }, this.#t(), signal);
|
|
4549
|
+
const files = [];
|
|
4550
|
+
const add = (u, edits) => {
|
|
4551
|
+
const abs = safeFromUri(u);
|
|
4552
|
+
const r = abs ? this.#rel(abs) : null;
|
|
4553
|
+
if (r) files.push({ path: r, edits: edits.map((e) => ({ line: e["range"].start.line + 1, column: e["range"].start.character + 1, endLine: e["range"].end.line + 1, endColumn: e["range"].end.character + 1, newText: String(e["newText"]) })) });
|
|
4554
|
+
};
|
|
4555
|
+
for (const [u, edits] of Object.entries(we?.["changes"] ?? {})) add(u, edits);
|
|
4556
|
+
for (const dc of we?.["documentChanges"] ?? []) if (dc["textDocument"]) add(String(dc["textDocument"].uri), dc["edits"] ?? []);
|
|
4557
|
+
return files;
|
|
4558
|
+
},
|
|
4559
|
+
async () => {
|
|
4560
|
+
const w = await this.#wordAt(rel, line, column);
|
|
4561
|
+
if (!w) return [];
|
|
4562
|
+
const r = await this.#o.intel.references(w, signal ? { signal } : {});
|
|
4563
|
+
const by = /* @__PURE__ */ new Map();
|
|
4564
|
+
for (const x of r.references) {
|
|
4565
|
+
const f = by.get(x.path) ?? { path: x.path, edits: [] };
|
|
4566
|
+
f.edits.push({ line: x.line, column: x.column, endLine: x.line, endColumn: x.column + w.length, newText: newName });
|
|
4567
|
+
by.set(x.path, f);
|
|
4568
|
+
}
|
|
4569
|
+
return [...by.values()];
|
|
4570
|
+
},
|
|
4571
|
+
signal
|
|
4572
|
+
);
|
|
4573
|
+
}
|
|
4574
|
+
/** Stops every server this manager started. Call when zg is done with them. */
|
|
4575
|
+
async stopAll() {
|
|
4576
|
+
const all = [...this.#conns.values()];
|
|
4577
|
+
this.#conns.clear();
|
|
4578
|
+
this.#opened.clear();
|
|
4579
|
+
await Promise.all(all.map((p) => p.then((c) => c.stop()).catch(() => void 0)));
|
|
4580
|
+
}
|
|
4581
|
+
};
|
|
4582
|
+
function safeFromUri(uri) {
|
|
4583
|
+
try {
|
|
4584
|
+
return uri.startsWith("file:") ? fileURLToPath(uri) : null;
|
|
4585
|
+
} catch {
|
|
4586
|
+
return null;
|
|
4587
|
+
}
|
|
4588
|
+
}
|
|
4589
|
+
|
|
4590
|
+
// src/workflows/factory.ts
|
|
4591
|
+
async function createAdvancedService(i) {
|
|
4592
|
+
const intel = await CodeIntel.open({ root: i.fs.root, dataDir: i.dataDir, os: i.os, advanced: () => i.config().advanced, filesystem: () => i.config().filesystem });
|
|
4593
|
+
const lsp = new LspManager({ intel, env: i.env, windows: i.os === "windows", settings: () => i.config().advanced });
|
|
4594
|
+
return new AdvancedService({ intel, lsp, fs: i.fs, git: i.git, ai: { backend: i.backend, network: () => i.config().network, policy: () => policyFromSettings(i.config().context) }, ...i.width ? { width: i.width } : {} });
|
|
4595
|
+
}
|
|
4596
|
+
|
|
4597
|
+
export {
|
|
4598
|
+
CommandProposalSchema,
|
|
4599
|
+
CommandEngine,
|
|
4600
|
+
FileOperationsSchema,
|
|
4601
|
+
openWorkspace,
|
|
4602
|
+
GitManager,
|
|
4603
|
+
GitRunner,
|
|
4604
|
+
createAdvancedService
|
|
4605
|
+
};
|