@anhlp/alp-daemon 0.0.0-stage → 0.0.1-beta.4

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.
Files changed (66) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +14 -2
  4. package/dist/THIRD-PARTY-NOTICES.txt +431 -0
  5. package/dist/alp-templates.d.ts +5 -0
  6. package/dist/alpd.js +49562 -0
  7. package/dist/attachments.d.ts +211 -0
  8. package/dist/attachments.js +819 -0
  9. package/dist/build-manifest.json +131 -0
  10. package/dist/conversation.d.ts +119 -0
  11. package/dist/conversation.js +672 -0
  12. package/dist/files.d.ts +123 -0
  13. package/dist/files.js +365 -0
  14. package/dist/git.d.ts +87 -0
  15. package/dist/git.js +1093 -0
  16. package/dist/gitignore.d.ts +62 -0
  17. package/dist/gitignore.js +254 -0
  18. package/dist/history.d.ts +24 -0
  19. package/dist/history.js +149 -0
  20. package/dist/index.d.ts +10 -0
  21. package/dist/index.js +25 -0
  22. package/dist/lifecycle.d.ts +101 -0
  23. package/dist/lifecycle.js +239 -0
  24. package/dist/lock.d.ts +21 -0
  25. package/dist/lock.js +42 -0
  26. package/dist/main.d.ts +1 -0
  27. package/dist/main.js +277 -0
  28. package/dist/operations.d.ts +23 -0
  29. package/dist/operations.js +275 -0
  30. package/dist/registry.d.ts +89 -0
  31. package/dist/registry.js +343 -0
  32. package/dist/rpc-error.d.ts +6 -0
  33. package/dist/rpc-error.js +11 -0
  34. package/dist/scheduler.d.ts +96 -0
  35. package/dist/scheduler.js +290 -0
  36. package/dist/schedules.d.ts +69 -0
  37. package/dist/schedules.js +244 -0
  38. package/dist/server.d.ts +58 -0
  39. package/dist/server.js +1780 -0
  40. package/dist/store.d.ts +176 -0
  41. package/dist/store.js +385 -0
  42. package/dist/terminals.d.ts +157 -0
  43. package/dist/terminals.js +487 -0
  44. package/dist/worktrees.d.ts +41 -0
  45. package/dist/worktrees.js +246 -0
  46. package/package.json +159 -4
  47. package/src/alp-templates.d.ts +5 -0
  48. package/src/attachments.ts +870 -0
  49. package/src/conversation.ts +837 -0
  50. package/src/files.ts +459 -0
  51. package/src/git.ts +1045 -0
  52. package/src/gitignore.ts +277 -0
  53. package/src/history.ts +118 -0
  54. package/src/index.ts +11 -0
  55. package/src/lifecycle.ts +283 -0
  56. package/src/lock.ts +53 -0
  57. package/src/main.ts +292 -0
  58. package/src/operations.ts +300 -0
  59. package/src/registry.ts +238 -0
  60. package/src/rpc-error.ts +4 -0
  61. package/src/scheduler.ts +422 -0
  62. package/src/schedules.ts +294 -0
  63. package/src/server.ts +2056 -0
  64. package/src/store.ts +448 -0
  65. package/src/terminals.ts +591 -0
  66. package/src/worktrees.ts +287 -0
package/dist/git.js ADDED
@@ -0,0 +1,1093 @@
1
+ // packages/daemon/src/git.ts
2
+ import { spawn } from "node:child_process";
3
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
4
+ import { lstat, realpath } from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { user_worktree } from "@anhlp/alp-core";
8
+ import { ERROR, RPC_ERROR, WORKSPACE_GIT, blockedFilePath } from "@anhlp/alp-protocol";
9
+ import { FileAccessError, PRIVATE_KEY, likelyBinary, readConfinedFile, relativeSegments } from "./files.js";
10
+ import { IgnoreUnknown, resolveGit, searchPathOutside } from "./gitignore.js";
11
+ import { RegistryError } from "./registry.js";
12
+ import { RpcError } from "./rpc-error.js";
13
+ var GIT_READ = Object.freeze({
14
+ /** One call (all of its Git processes, waiting for a turn included) gets this long. */
15
+ timeoutMs: 15e3,
16
+ /** Git processes these reads run at once in alpd, and processes that may wait for one. */
17
+ maxConcurrent: 4,
18
+ maxQueued: 32,
19
+ maxErrorBytes: 16 * 1024,
20
+ /** Configuration, change list and untracked list output, at most. */
21
+ maxListBytes: 16 * 1024 * 1024,
22
+ /** One patch stream, at most (its files are at most a window's worth of content). */
23
+ maxPatchStreamBytes: 32 * 1024 * 1024,
24
+ /** One side of a file scanned for a private key; a larger side is `too_large`. */
25
+ maxScanBytes: 8 * 1024 * 1024,
26
+ /** Files whose content one window reads and diffs together, and their content's total. */
27
+ windowFiles: 64,
28
+ windowBytes: 4 * 1024 * 1024,
29
+ /** Pathspec bytes on one command line. */
30
+ maxArgBytes: process.platform === "win32" ? 24 * 1024 : 256 * 1024,
31
+ /** Worktree files whose size and time enter a diff's snapshot. */
32
+ maxSnapshotStats: 5e3
33
+ });
34
+ var FIXED = Object.freeze({
35
+ notRepository: "The workspace is not a Git repository",
36
+ notRoot: "The workspace is not the top level of its Git repository",
37
+ unavailable: "No Git is available to alpd",
38
+ tooOld: "The Git available to alpd is older than 2.31, which these reads need",
39
+ failed: "Git could not read the workspace",
40
+ invalidCompare: "compare.baseRef must name a branch",
41
+ unknownRef: "compare.baseRef names no branch of the repository",
42
+ stale: "The checkout changed since the cursor was given; ask again without a cursor",
43
+ invalidCursor: "cursor is not one alpd gave for this workspace and comparison",
44
+ notFound: "No workspace with this workspaceId"
45
+ });
46
+ var GitReadFailed = class extends Error {
47
+ constructor(cause) {
48
+ super(FIXED.failed);
49
+ this.cause = cause;
50
+ }
51
+ };
52
+ var failed = (why) => {
53
+ throw new GitReadFailed(why);
54
+ };
55
+ var gitFailed = () => new RpcError(ERROR.failed, FIXED.failed, { reason: "git_failed" });
56
+ var running = 0;
57
+ var waiting = [];
58
+ function acquire(deadline) {
59
+ let released = false;
60
+ const release = () => {
61
+ if (released) return;
62
+ released = true;
63
+ running--;
64
+ waiting.shift()?.();
65
+ };
66
+ if (running < GIT_READ.maxConcurrent) {
67
+ running++;
68
+ return Promise.resolve(release);
69
+ }
70
+ if (waiting.length >= GIT_READ.maxQueued) return Promise.reject(new GitReadFailed("too many Git reads waiting"));
71
+ return new Promise((resolve, reject) => {
72
+ const turn = () => {
73
+ clearTimeout(timer);
74
+ running++;
75
+ resolve(release);
76
+ };
77
+ const timer = setTimeout(() => {
78
+ const index = waiting.indexOf(turn);
79
+ if (index >= 0) waiting.splice(index, 1);
80
+ reject(new GitReadFailed("timed out waiting for a turn"));
81
+ }, Math.max(0, deadline - Date.now()));
82
+ waiting.push(turn);
83
+ });
84
+ }
85
+ var gitReadsRunning = () => running;
86
+ var BOXED = [
87
+ "--no-pager",
88
+ "--literal-pathspecs",
89
+ "-c",
90
+ "core.fsmonitor=false",
91
+ "-c",
92
+ `core.hooksPath=${os.devNull}`,
93
+ "-c",
94
+ "core.pager=cat",
95
+ "-c",
96
+ "core.untrackedCache=false",
97
+ "-c",
98
+ "core.quotePath=false",
99
+ "-c",
100
+ "color.ui=never",
101
+ "-c",
102
+ "diff.autoRefreshIndex=false",
103
+ "-c",
104
+ "diff.noprefix=false",
105
+ "-c",
106
+ "diff.mnemonicPrefix=false",
107
+ "-c",
108
+ "diff.relative=false",
109
+ "-c",
110
+ "diff.suppressBlankEmpty=false",
111
+ "-c",
112
+ `diff.orderFile=${os.devNull}`,
113
+ "-c",
114
+ "log.showSignature=false",
115
+ "-c",
116
+ "submodule.recurse=false",
117
+ "-c",
118
+ "protocol.allow=never",
119
+ "-c",
120
+ "maintenance.auto=false",
121
+ "-c",
122
+ "gc.auto=0",
123
+ "-c",
124
+ "status.showStash=false",
125
+ "-c",
126
+ "status.renames=true",
127
+ "-c",
128
+ "diff.renames=true"
129
+ ];
130
+ function runGit(box, args, { stdin, okCodes = [0], maxBytes = GIT_READ.maxListBytes, onData } = {}) {
131
+ return acquire(box.deadline).then((release) => new Promise((resolve, reject) => {
132
+ let settled = false;
133
+ let stopped = false;
134
+ let child;
135
+ const group = process.platform !== "win32";
136
+ const kill = () => {
137
+ try {
138
+ if (group && child.pid) process.kill(-child.pid, "SIGKILL");
139
+ else child.kill("SIGKILL");
140
+ } catch {
141
+ }
142
+ };
143
+ let timer;
144
+ const finish = (outcome) => {
145
+ if (settled) return;
146
+ settled = true;
147
+ if (timer) clearTimeout(timer);
148
+ release();
149
+ outcome();
150
+ };
151
+ try {
152
+ child = spawn(box.git, [...BOXED, ...box.overrides, ...args], {
153
+ cwd: box.root,
154
+ env: box.env,
155
+ shell: false,
156
+ windowsHide: true,
157
+ detached: group,
158
+ stdio: [stdin === void 0 ? "ignore" : "pipe", "pipe", "pipe"]
159
+ });
160
+ } catch (error) {
161
+ finish(() => reject(new GitReadFailed(`spawn: ${error.message}`)));
162
+ return;
163
+ }
164
+ timer = setTimeout(() => finish(() => {
165
+ kill();
166
+ reject(new GitReadFailed("timed out"));
167
+ }), Math.max(1, box.deadline - Date.now()));
168
+ const out = [];
169
+ let outBytes = 0;
170
+ let err = "";
171
+ child.stdout.on("data", (chunk) => {
172
+ if (settled || stopped) return;
173
+ if (onData) {
174
+ if (onData(chunk)) {
175
+ stopped = true;
176
+ kill();
177
+ }
178
+ return;
179
+ }
180
+ outBytes += chunk.length;
181
+ if (outBytes > maxBytes) finish(() => {
182
+ kill();
183
+ reject(new GitReadFailed("output over its bound"));
184
+ });
185
+ else out.push(chunk);
186
+ });
187
+ child.stderr.on("data", (chunk) => {
188
+ if (err.length < GIT_READ.maxErrorBytes) err += chunk.toString("utf8");
189
+ });
190
+ child.on("error", (error) => finish(() => reject(new GitReadFailed(`spawn: ${error.message}`))));
191
+ child.on("close", (code) => finish(() => {
192
+ if (stopped) {
193
+ resolve({ code: code ?? -1, stdout: Buffer.alloc(0), stopped: true });
194
+ return;
195
+ }
196
+ if (code === null || !okCodes.includes(code)) {
197
+ reject(new GitReadFailed(`${args[0]} exit ${code}: ${err.trim().slice(0, 1e3)}`));
198
+ return;
199
+ }
200
+ resolve({ code, stdout: Buffer.concat(out), stopped: false });
201
+ }));
202
+ if (stdin !== void 0) {
203
+ child.stdin.on("error", () => {
204
+ });
205
+ child.stdin.end(stdin);
206
+ }
207
+ }));
208
+ }
209
+ var MINIMUM_GIT = [2, 31];
210
+ var versions = /* @__PURE__ */ new Map();
211
+ function recentEnough(box) {
212
+ const known = versions.get(box.git);
213
+ if (known) return known;
214
+ const checked = runGit(box, ["--version"], { maxBytes: 4096 }).then(({ stdout }) => {
215
+ const found = /^git version (\d+)\.(\d+)/.exec(stdout.toString("utf8"));
216
+ if (!found) failed("unrecognized git --version");
217
+ const [major, minor] = [Number(found[1]), Number(found[2])];
218
+ return major > MINIMUM_GIT[0] || major === MINIMUM_GIT[0] && minor >= MINIMUM_GIT[1];
219
+ });
220
+ versions.set(box.git, checked);
221
+ checked.catch(() => versions.delete(box.git));
222
+ return checked;
223
+ }
224
+ var missing = (error) => ["ENOENT", "ENOTDIR"].includes(error?.code ?? "");
225
+ async function locate(root) {
226
+ let entry = true;
227
+ try {
228
+ await lstat(path.join(root, ".git"));
229
+ } catch (error) {
230
+ if (!missing(error)) failed("cannot examine .git");
231
+ entry = false;
232
+ }
233
+ if (!entry) {
234
+ for (let directory = path.dirname(root); ; directory = path.dirname(directory)) {
235
+ try {
236
+ await lstat(path.join(directory, ".git"));
237
+ return { kind: "unsupported" };
238
+ } catch (error) {
239
+ if (!missing(error)) failed("cannot examine .git above the workspace");
240
+ }
241
+ if (path.dirname(directory) === directory) return { kind: "not_repository" };
242
+ }
243
+ }
244
+ let gitDir;
245
+ try {
246
+ ({ gitDir } = await user_worktree.repositoryIdentity(root));
247
+ } catch (error) {
248
+ failed(`the workspace's .git cannot be used: ${error.message}`);
249
+ }
250
+ return { kind: "repository", root, gitDir };
251
+ }
252
+ function environment(root, gitDir) {
253
+ const env = {};
254
+ for (const [key, value] of Object.entries(process.env)) if (!/^GIT_/i.test(key) && !/^path$/i.test(key)) env[key] = value;
255
+ let searchPath;
256
+ try {
257
+ searchPath = searchPathOutside(root);
258
+ } catch {
259
+ failed("the workspace cannot be examined");
260
+ }
261
+ return {
262
+ ...env,
263
+ PATH: searchPath,
264
+ GIT_DIR: gitDir,
265
+ GIT_WORK_TREE: root,
266
+ GIT_CONFIG_NOSYSTEM: "1",
267
+ GIT_CONFIG_GLOBAL: os.devNull,
268
+ GIT_ATTR_NOSYSTEM: "1",
269
+ GIT_OPTIONAL_LOCKS: "0",
270
+ GIT_TERMINAL_PROMPT: "0",
271
+ GIT_NO_LAZY_FETCH: "1",
272
+ GIT_NO_REPLACE_OBJECTS: "1",
273
+ GIT_PROTOCOL_FROM_USER: "0",
274
+ LC_ALL: "C",
275
+ LANG: "C"
276
+ };
277
+ }
278
+ var EMPTY_TREE = { sha1: "4b825dc642cb6eb9a060e54bf8d69288fbee4904", sha256: "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321" };
279
+ var CONFIG_READ = ["config", "--null", "--get-regexp", "^(remote\\.origin\\.url|core\\.worktree|extensions\\.objectformat|filter\\..+\\.(smudge|clean|process|required))$"];
280
+ async function sameConfig(repo) {
281
+ const { stdout } = await runGit({ ...repo, overrides: [] }, CONFIG_READ, { okCodes: [0, 1] });
282
+ if (hash(stdout) !== repo.config) failed("the repository configuration changed during the read");
283
+ }
284
+ async function boxFor(located, git, deadline) {
285
+ const box = { git, root: located.root, env: environment(located.root, located.gitDir), deadline, overrides: [] };
286
+ if (!await recentEnough(box)) throw new RpcError(ERROR.unavailable, FIXED.tooOld, { reason: "git_unavailable" });
287
+ const { stdout } = await runGit(box, CONFIG_READ, { okCodes: [0, 1] });
288
+ let remoteUrl = null;
289
+ let worktree;
290
+ let format = "sha1";
291
+ const neutral = /* @__PURE__ */ new Set();
292
+ for (const record of stdout.toString("utf8").split("\0")) {
293
+ if (!record) continue;
294
+ const newline = record.indexOf("\n");
295
+ const key = newline < 0 ? record : record.slice(0, newline);
296
+ const value = newline < 0 ? "" : record.slice(newline + 1);
297
+ if (key === "remote.origin.url") remoteUrl = value;
298
+ else if (key === "core.worktree") worktree = value;
299
+ else if (key === "extensions.objectformat") format = value.toLowerCase();
300
+ else if (key.startsWith("filter.")) {
301
+ if (key.includes("=") || /[\0\n]/.test(key)) failed("a filter driver name cannot be neutralized");
302
+ neutral.add(key);
303
+ }
304
+ }
305
+ if (worktree !== void 0) {
306
+ const named = await realpath(path.resolve(located.gitDir, worktree)).catch(() => void 0);
307
+ if (named !== located.root) return "unsupported";
308
+ }
309
+ const emptyTree = format === "sha256" ? EMPTY_TREE.sha256 : format === "sha1" ? EMPTY_TREE.sha1 : failed("unknown object format");
310
+ box.overrides = [...neutral].sort().flatMap((key) => ["-c", `${key}=${key.endsWith(".required") ? "false" : ""}`]);
311
+ return { ...box, remoteUrl, emptyTree, gitDir: located.gitDir, config: hash(stdout) };
312
+ }
313
+ function validBranchName(name) {
314
+ if (typeof name !== "string" || !name || name.length > WORKSPACE_GIT.maxRefLength) return false;
315
+ if (name.startsWith("-") || name === "HEAD" || name === "@") return false;
316
+ if (/[\x00-\x20\x7f~^:?*[\\]/.test(name) || name.includes("..") || name.includes("@{") || name.includes("//")) return false;
317
+ if (name.startsWith("/") || name.endsWith("/") || name.endsWith(".")) return false;
318
+ return name.split("/").every((part) => part && !part.startsWith(".") && !part.endsWith(".lock"));
319
+ }
320
+ function scrubRemoteUrl(url) {
321
+ const value = url?.trim();
322
+ if (!value || /[\x00-\x1f\x7f]/.test(value) || value.includes("::")) return null;
323
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)/.exec(value);
324
+ if (scheme) {
325
+ const protocol = scheme[1].toLowerCase();
326
+ if (protocol === "file") return null;
327
+ const host = scheme[2].slice(scheme[2].lastIndexOf("@") + 1);
328
+ return host ? `${protocol}://${host}${scheme[3]}` : null;
329
+ }
330
+ if (/^file:/i.test(value)) return null;
331
+ const slash = value.indexOf("/");
332
+ const at = (slash < 0 ? value : value.slice(0, slash)).lastIndexOf("@");
333
+ const scp = /^([^@/:]+):(.*)$/.exec(at < 0 ? value : value.slice(at + 1));
334
+ if (scp && scp[1].length > 1 && !scp[2].startsWith("\\")) return `${scp[1]}:${scp[2]}`;
335
+ return null;
336
+ }
337
+ var hash = (...parts) => {
338
+ const digest = createHash("sha256");
339
+ for (const part of parts) {
340
+ digest.update(typeof part === "string" ? part : part);
341
+ digest.update("\0");
342
+ }
343
+ return digest.digest("hex");
344
+ };
345
+ async function statMark(file) {
346
+ try {
347
+ const info = await lstat(file, { bigint: true });
348
+ return `${info.dev}:${info.ino}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
349
+ } catch {
350
+ return "-";
351
+ }
352
+ }
353
+ function cursorScope(workspaceId, compare, relative, body) {
354
+ return JSON.stringify([workspaceId, compare.mode, compare.baseRef ?? null, compare.ignoreWhitespace === true, relative ?? null, body.snapshot, body.offset]);
355
+ }
356
+ var ZERO = /^0+$/;
357
+ var GITLINK = "160000";
358
+ var SYMLINK = "120000";
359
+ var RAW_CHANGE = { A: "added", C: "copied", D: "deleted", M: "modified", R: "renamed", T: "typechange", U: "conflicted" };
360
+ function parseRaw(output) {
361
+ const fields = output.toString("utf8").split("\0");
362
+ const entries = [];
363
+ const conflicted = /* @__PURE__ */ new Set();
364
+ for (let index = 0; index < fields.length; ) {
365
+ const meta = fields[index++];
366
+ if (!meta) continue;
367
+ const match = /^:(\d{6}) (\d{6}) ([0-9a-f]+) ([0-9a-f]+) ([ACDMRTUX])(\d*)$/.exec(meta);
368
+ if (!match) failed("unexpected change list");
369
+ const [, srcMode, dstMode, srcOid, dstOid, letter] = match;
370
+ const first = fields[index++];
371
+ const second = letter === "R" || letter === "C" ? fields[index++] : void 0;
372
+ if (!first || second !== void 0 && !second) failed("unexpected change list");
373
+ if (letter === "X") continue;
374
+ const entry = second !== void 0 ? { path: second, oldPath: first, change: RAW_CHANGE[letter], srcMode, dstMode, srcOid, dstOid } : { path: first, change: RAW_CHANGE[letter], srcMode, dstMode, srcOid, dstOid };
375
+ if (letter === "U") {
376
+ conflicted.add(entry.path);
377
+ entry.conflicted = true;
378
+ }
379
+ entries.push(entry);
380
+ }
381
+ const merged = [];
382
+ for (const entry of entries) {
383
+ if (!conflicted.has(entry.path)) {
384
+ merged.push(entry);
385
+ continue;
386
+ }
387
+ if (entry.conflicted) {
388
+ const ours = entries.find((other) => other.path === entry.path && !other.conflicted);
389
+ merged.push(ours ? { ...ours, change: "conflicted", conflicted: true } : entry);
390
+ }
391
+ }
392
+ return merged;
393
+ }
394
+ function quoted(name) {
395
+ if (!/[\x00-\x1f"\\\x7f]/.test(name)) return name;
396
+ let out = '"';
397
+ for (const byte of Buffer.from(name, "utf8")) {
398
+ const letter = { 7: "a", 8: "b", 9: "t", 10: "n", 11: "v", 12: "f", 13: "r" }[byte];
399
+ if (letter) out += `\\${letter}`;
400
+ else if (byte === 34) out += '\\"';
401
+ else if (byte === 92) out += "\\\\";
402
+ else if (byte < 32 || byte === 127) out += `\\${byte.toString(8).padStart(3, "0")}`;
403
+ else out += String.fromCharCode(byte);
404
+ }
405
+ return Buffer.from(`${out}"`, "latin1").toString("utf8");
406
+ }
407
+ var headerOf = (entry) => `diff --git ${quoted(`a/${entry.oldPath ?? entry.path}`)} ${quoted(`b/${entry.path}`)}`;
408
+ function sectionsOf(keepBytes) {
409
+ const sections = [];
410
+ let buffer = Buffer.alloc(0);
411
+ let atLineStart = true;
412
+ let inHeader = false;
413
+ let total = 0;
414
+ const MARK = Buffer.from("diff --git ");
415
+ const UNMERGED = Buffer.from("* Unmerged path ");
416
+ let skipping = false;
417
+ const append = (bytes) => {
418
+ const current = sections.at(-1);
419
+ if (!current) failed("patch output before a header");
420
+ current.bytes += bytes.length;
421
+ if (current.bytes <= keepBytes + 1) current.chunks.push(Buffer.from(bytes));
422
+ };
423
+ function consume(ended) {
424
+ let at = 0;
425
+ for (; ; ) {
426
+ if (inHeader) {
427
+ const newline2 = buffer.indexOf(10, at);
428
+ if (newline2 < 0) {
429
+ if (buffer.length - at > 64 * 1024) failed("patch header over its bound");
430
+ break;
431
+ }
432
+ const line = buffer.subarray(at, newline2);
433
+ sections.push({ header: line.toString("utf8"), bytes: line.length + 1, chunks: [] });
434
+ at = newline2 + 1;
435
+ inHeader = false;
436
+ atLineStart = true;
437
+ continue;
438
+ }
439
+ if (at >= buffer.length) break;
440
+ if (skipping) {
441
+ const newline2 = buffer.indexOf(10, at);
442
+ if (newline2 < 0) {
443
+ if (buffer.length - at > 64 * 1024) failed("patch marker over its bound");
444
+ break;
445
+ }
446
+ at = newline2 + 1;
447
+ skipping = false;
448
+ atLineStart = true;
449
+ continue;
450
+ }
451
+ if (atLineStart) {
452
+ if (buffer.length - at < UNMERGED.length && !ended) break;
453
+ if (buffer.subarray(at, at + MARK.length).equals(MARK)) {
454
+ inHeader = true;
455
+ continue;
456
+ }
457
+ if (buffer.subarray(at, at + UNMERGED.length).equals(UNMERGED)) {
458
+ skipping = true;
459
+ continue;
460
+ }
461
+ atLineStart = false;
462
+ }
463
+ const newline = buffer.indexOf(10, at);
464
+ if (newline < 0) {
465
+ append(buffer.subarray(at));
466
+ at = buffer.length;
467
+ break;
468
+ }
469
+ append(buffer.subarray(at, newline + 1));
470
+ at = newline + 1;
471
+ atLineStart = true;
472
+ }
473
+ buffer = buffer.subarray(at);
474
+ if (ended && (buffer.length || inHeader || skipping)) failed("unterminated patch");
475
+ }
476
+ return {
477
+ sections,
478
+ write(chunk) {
479
+ total += chunk.length;
480
+ if (total > GIT_READ.maxPatchStreamBytes) failed("patch output over its bound");
481
+ buffer = buffer.length ? Buffer.concat([buffer, chunk]) : chunk;
482
+ consume(false);
483
+ },
484
+ end() {
485
+ consume(true);
486
+ }
487
+ };
488
+ }
489
+ var DECODER = new TextDecoder("utf-8", { fatal: false, ignoreBOM: true });
490
+ function parseSection(section) {
491
+ const lines = DECODER.decode(Buffer.concat(section.chunks)).split("\n");
492
+ const hunks = [];
493
+ let additions = 0;
494
+ let deletions = 0;
495
+ let hunk;
496
+ let oldLeft = 0;
497
+ let newLeft = 0;
498
+ for (const line of lines) {
499
+ if (!hunk && (line === "GIT binary patch" || line.startsWith("Binary files ") && line.endsWith(" differ"))) return { binary: true, hunks: [], additions: 0, deletions: 0 };
500
+ const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
501
+ if (header && oldLeft <= 0 && newLeft <= 0) {
502
+ const context = line.slice(header[0].length).replace(/^ /, "");
503
+ hunk = { oldStart: Number(header[1]), oldCount: Number(header[2] ?? 1), newStart: Number(header[3]), newCount: Number(header[4] ?? 1), ...context ? { context } : {}, lines: [] };
504
+ oldLeft = hunk.oldCount;
505
+ newLeft = hunk.newCount;
506
+ hunks.push(hunk);
507
+ continue;
508
+ }
509
+ if (!hunk) continue;
510
+ if (line.startsWith("\\")) {
511
+ const last = hunk.lines.at(-1);
512
+ if (last) last.noNewline = true;
513
+ continue;
514
+ }
515
+ if (oldLeft <= 0 && newLeft <= 0) continue;
516
+ if (line.startsWith("+")) {
517
+ hunk.lines.push({ type: "add", content: line.slice(1) });
518
+ additions++;
519
+ newLeft--;
520
+ } else if (line.startsWith("-")) {
521
+ hunk.lines.push({ type: "remove", content: line.slice(1) });
522
+ deletions++;
523
+ oldLeft--;
524
+ } else if (line.startsWith(" ") || line === "") {
525
+ hunk.lines.push({ type: "context", content: line.slice(1) });
526
+ oldLeft--;
527
+ newLeft--;
528
+ }
529
+ }
530
+ return { binary: false, hunks, additions, deletions };
531
+ }
532
+ function addedHunks(text) {
533
+ if (!text) return { hunks: [], additions: 0 };
534
+ const endsWithNewline = text.endsWith("\n");
535
+ const parts = (endsWithNewline ? text.slice(0, -1) : text).split("\n");
536
+ const lines = parts.map((content) => ({ type: "add", content }));
537
+ if (!endsWithNewline) lines.at(-1).noNewline = true;
538
+ return { hunks: [{ oldStart: 0, oldCount: 0, newStart: 1, newCount: lines.length, lines }], additions: lines.length };
539
+ }
540
+ var holdsKey = (bytes) => PRIVATE_KEY.test(bytes.toString("latin1"));
541
+ function sized(file) {
542
+ const cost = (value) => Buffer.byteLength(JSON.stringify(value)) + 1;
543
+ if (file.kind !== "text") return { file, cost: cost(file) };
544
+ let content = 0;
545
+ for (const hunk of file.hunks) for (const line of hunk.lines) content += Buffer.byteLength(line.content, "utf8");
546
+ const bytes = cost(file);
547
+ if (content <= WORKSPACE_GIT.maxFileBytes && bytes <= PAGE_BYTES) return { file, cost: bytes };
548
+ const large = { ...file, kind: "too_large", hunks: [] };
549
+ return { file: large, cost: cost(large) };
550
+ }
551
+ var PAGE_BYTES = WORKSPACE_GIT.maxTotalBytes - 16 * 1024;
552
+ function createGitReader({ registry, binary = "git", timeoutMs = GIT_READ.timeoutMs, log = () => {
553
+ }, probe }) {
554
+ const key = randomBytes(32);
555
+ const mac = (scope) => createHmac("sha256", key).update(scope).digest("base64url").slice(0, 32);
556
+ async function workspaceRoot(workspaceId) {
557
+ if (typeof workspaceId !== "string" || !workspaceId) throw new RpcError(RPC_ERROR.invalidParams, "workspaceId is required", { reason: "invalid_params" });
558
+ try {
559
+ return await registry.resolve(workspaceId);
560
+ } catch (error) {
561
+ if (error instanceof RegistryError) throw new RpcError(error.code, error.message, error.data);
562
+ if (missing(error)) throw new RpcError(ERROR.notFound, FIXED.notFound, { reason: "not_found" });
563
+ throw error;
564
+ }
565
+ }
566
+ async function open(workspaceId) {
567
+ const root = await workspaceRoot(workspaceId);
568
+ const deadline = Date.now() + timeoutMs;
569
+ const located = await locate(root);
570
+ if (located.kind !== "repository") return { state: located.kind };
571
+ let git;
572
+ try {
573
+ git = resolveGit(binary, void 0, root);
574
+ } catch (error) {
575
+ if (error instanceof IgnoreUnknown) failed("the workspace cannot be examined");
576
+ throw error;
577
+ }
578
+ if (!git) throw new RpcError(ERROR.unavailable, FIXED.unavailable, { reason: "git_unavailable" });
579
+ const repo = await boxFor(located, git, deadline);
580
+ return repo === "unsupported" ? { state: "unsupported" } : { state: "repository", repo };
581
+ }
582
+ async function commitOf(repo, ref) {
583
+ const { stdout, code } = await runGit(repo, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`], { okCodes: [0, 1, 128] });
584
+ const oid = stdout.toString("utf8").trim();
585
+ return code === 0 && /^[0-9a-f]{40,64}$/.test(oid) ? oid : void 0;
586
+ }
587
+ async function resolveBase(repo, name) {
588
+ for (const ref of [`refs/remotes/origin/${name}`, `refs/heads/${name}`]) {
589
+ const oid = await commitOf(repo, ref);
590
+ if (oid) return { ref, oid };
591
+ }
592
+ return void 0;
593
+ }
594
+ async function defaultBase(repo) {
595
+ const candidates = ["refs/remotes/origin/HEAD", "refs/heads/main", "refs/remotes/origin/main", "refs/heads/master", "refs/remotes/origin/master"];
596
+ const { stdout } = await runGit(repo, ["for-each-ref", "--format=%(refname)%00%(symref)", "--", ...candidates]);
597
+ const found = /* @__PURE__ */ new Map();
598
+ for (const line of stdout.toString("utf8").split("\n")) {
599
+ const [ref, symref = ""] = line.split("\0");
600
+ if (ref && candidates.includes(ref)) found.set(ref, symref);
601
+ }
602
+ const remoteHead = found.get("refs/remotes/origin/HEAD");
603
+ if (remoteHead?.startsWith("refs/remotes/origin/")) {
604
+ const name = remoteHead.slice("refs/remotes/origin/".length);
605
+ if (validBranchName(name)) return name;
606
+ }
607
+ for (const name of ["main", "master"]) if (found.has(`refs/heads/${name}`) || found.has(`refs/remotes/origin/${name}`)) return name;
608
+ return null;
609
+ }
610
+ const emptyStatus = (state) => ({
611
+ state,
612
+ ...state === "unsupported" ? { reason: "not_repository_root" } : {},
613
+ branch: null,
614
+ detached: false,
615
+ head: null,
616
+ upstream: null,
617
+ baseRef: null,
618
+ aheadBehind: null,
619
+ hasRemote: false,
620
+ remoteUrl: null,
621
+ dirty: false,
622
+ files: [],
623
+ hiddenCount: 0,
624
+ truncated: false,
625
+ snapshot: ""
626
+ });
627
+ async function status(workspaceId) {
628
+ const opened = await open(workspaceId);
629
+ if (opened.state !== "repository") return emptyStatus(opened.state);
630
+ const { repo } = opened;
631
+ const files = [];
632
+ let hiddenCount = 0;
633
+ let truncated = false;
634
+ let dirty = false;
635
+ const branch = {};
636
+ const digest = createHash("sha256");
637
+ let pending = "";
638
+ let pendingRename;
639
+ const take = (row) => {
640
+ dirty = true;
641
+ if (blockedFilePath(row.path) || row.oldPath && blockedFilePath(row.oldPath) || [...row.path].length > 4096 || [...row.oldPath ?? ""].length > 4096) {
642
+ hiddenCount++;
643
+ return false;
644
+ }
645
+ if (files.length >= WORKSPACE_GIT.maxStatusFiles) {
646
+ truncated = true;
647
+ return true;
648
+ }
649
+ files.push(row);
650
+ return false;
651
+ };
652
+ const record = (field) => {
653
+ if (pendingRename) {
654
+ const [kind2, xy] = pendingRename;
655
+ pendingRename = void 0;
656
+ return take({ path: kind2, oldPath: field, change: xy.includes("C") ? "copied" : "renamed", staged: xy[0] !== ".", unstaged: xy[1] !== "." });
657
+ }
658
+ if (field.startsWith("# ")) {
659
+ const [name, ...rest] = field.slice(2).split(" ");
660
+ const value = rest.join(" ");
661
+ if (name === "branch.oid") branch.oid = value;
662
+ else if (name === "branch.head") branch.head = value;
663
+ else if (name === "branch.upstream") branch.upstream = value;
664
+ else if (name === "branch.ab") {
665
+ const ab = /^\+(\d+) -(\d+)$/.exec(value);
666
+ if (ab) branch.ab = [Number(ab[1]), Number(ab[2])];
667
+ }
668
+ return false;
669
+ }
670
+ const kind = field[0];
671
+ if (kind === "1" || kind === "2" || kind === "u") {
672
+ const parts = field.split(" ");
673
+ const count = kind === "1" ? 8 : kind === "2" ? 9 : 10;
674
+ const xy = parts[1] ?? "..";
675
+ const rowPath = parts.slice(count).join(" ");
676
+ if (!rowPath) failed("unexpected status");
677
+ if (kind === "2") {
678
+ pendingRename = [rowPath, xy];
679
+ return false;
680
+ }
681
+ if (kind === "u") return take({ path: rowPath, change: "conflicted", staged: true, unstaged: true });
682
+ const [x, y] = [xy[0], xy[1]];
683
+ const change = x === "A" ? "added" : x === "D" || y === "D" ? "deleted" : x === "T" || y === "T" ? "typechange" : "modified";
684
+ return take({ path: rowPath, change, staged: x !== ".", unstaged: y !== "." });
685
+ }
686
+ if (kind === "?") {
687
+ const rowPath = field.slice(2).replace(/\/$/, "");
688
+ return rowPath ? take({ path: rowPath, change: "untracked", staged: false, unstaged: true }) : false;
689
+ }
690
+ if (kind === "!") return false;
691
+ failed("unexpected status");
692
+ return false;
693
+ };
694
+ let seen = 0;
695
+ const { stopped } = await runGit(repo, ["status", "--porcelain=v2", "-z", "--branch", "--ahead-behind", "--untracked-files=all", "--ignored=no", "--ignore-submodules=dirty", "--find-renames"], {
696
+ onData: (chunk) => {
697
+ seen += chunk.length;
698
+ digest.update(chunk);
699
+ const fields = (pending + chunk.toString("utf8")).split("\0");
700
+ pending = fields.pop();
701
+ for (const field of fields) if (field && record(field)) return true;
702
+ if (seen > GIT_READ.maxListBytes) {
703
+ truncated = true;
704
+ return true;
705
+ }
706
+ return false;
707
+ }
708
+ });
709
+ if (!stopped && pending) failed("unterminated status");
710
+ const head = branch.oid && /^[0-9a-f]{40,64}$/.test(branch.oid) ? branch.oid : null;
711
+ const detached = branch.head === "(detached)";
712
+ const current = !detached && branch.head && validBranchName(branch.head) ? branch.head : null;
713
+ const upstream = current && branch.upstream && branch.ab ? { ref: branch.upstream, ahead: branch.ab[0], behind: branch.ab[1] } : null;
714
+ const baseRef = await defaultBase(repo);
715
+ let aheadBehind = null;
716
+ if (baseRef && current && current !== baseRef && head) {
717
+ const base = await resolveBase(repo, baseRef);
718
+ if (base) {
719
+ const { stdout } = await runGit(repo, ["rev-list", "--left-right", "--count", "--end-of-options", `${base.oid}...${head}`], { okCodes: [0, 128] });
720
+ const counts = stdout.toString("utf8").trim().split(/\s+/).map(Number);
721
+ if (counts.length === 2 && counts.every(Number.isSafeInteger)) aheadBehind = { behind: counts[0], ahead: counts[1] };
722
+ }
723
+ }
724
+ digest.update(await statMark(path.join(repo.gitDir, "index")));
725
+ await sameConfig(repo);
726
+ return {
727
+ state: "repository",
728
+ branch: current,
729
+ detached,
730
+ head,
731
+ upstream,
732
+ baseRef,
733
+ aheadBehind,
734
+ hasRemote: repo.remoteUrl !== null,
735
+ remoteUrl: scrubRemoteUrl(repo.remoteUrl),
736
+ dirty,
737
+ files,
738
+ hiddenCount,
739
+ truncated,
740
+ snapshot: `s1.${digest.digest("hex").slice(0, 40)}`
741
+ };
742
+ }
743
+ async function untrackedOf(repo, relative, limit) {
744
+ const found = [];
745
+ let hidden = 0;
746
+ let more = false;
747
+ let pending = "";
748
+ const { stopped } = await runGit(repo, ["ls-files", "-z", "--others", "--exclude-standard", "--", ...relative ? [relative] : []], {
749
+ onData: (chunk) => {
750
+ const fields = (pending + chunk.toString("utf8")).split("\0");
751
+ pending = fields.pop();
752
+ for (const name of fields) {
753
+ if (!name || name.endsWith("/")) continue;
754
+ if (relative && name !== relative) continue;
755
+ if (blockedFilePath(name) || [...name].length > 4096) {
756
+ hidden++;
757
+ continue;
758
+ }
759
+ if (found.length >= limit) {
760
+ more = true;
761
+ return true;
762
+ }
763
+ found.push(name);
764
+ }
765
+ return false;
766
+ }
767
+ });
768
+ if (!stopped && pending) failed("unterminated untracked list");
769
+ return { found, hidden, more };
770
+ }
771
+ async function diff(params) {
772
+ const { workspaceId, compare, path: relative, cursor } = params ?? {};
773
+ const mode = compare?.mode;
774
+ if (!["uncommitted", "staged", "unstaged", "base"].includes(mode)) throw new RpcError(RPC_ERROR.invalidParams, "compare.mode is not one alpd knows", { reason: "invalid_compare" });
775
+ if (compare.baseRef !== void 0 && (mode !== "base" || !validBranchName(compare.baseRef))) throw new RpcError(RPC_ERROR.invalidParams, FIXED.invalidCompare, { reason: "invalid_compare" });
776
+ if (relative !== void 0) {
777
+ try {
778
+ relativeSegments(relative);
779
+ } catch (error) {
780
+ if (error instanceof FileAccessError) throw new RpcError(error.code, error.message, { reason: error.reason });
781
+ throw error;
782
+ }
783
+ }
784
+ let body;
785
+ if (cursor !== void 0) {
786
+ const match = typeof cursor === "string" ? /^c1\.(\d{1,9})\.(s1\.[0-9a-f]{40})\.([A-Za-z0-9_-]{32})$/.exec(cursor) : null;
787
+ if (!match) throw new RpcError(RPC_ERROR.invalidParams, FIXED.invalidCursor, { reason: "invalid_cursor" });
788
+ body = { offset: Number(match[1]), snapshot: match[2] };
789
+ const expected = Buffer.from(mac(cursorScope(workspaceId, compare, relative, body)));
790
+ if (!timingSafeEqual(expected, Buffer.from(match[3]))) throw new RpcError(RPC_ERROR.invalidParams, FIXED.invalidCursor, { reason: "invalid_cursor" });
791
+ }
792
+ const ignoreWhitespace = compare.ignoreWhitespace === true;
793
+ const opened = await open(workspaceId);
794
+ if (opened.state !== "repository") throw new RpcError(ERROR.notFound, opened.state === "unsupported" ? FIXED.notRoot : FIXED.notRepository, { reason: "not_repository" });
795
+ const { repo } = opened;
796
+ const head = await commitOf(repo, "HEAD");
797
+ const done = (files2, hiddenCount2, snapshot2, extra = {}) => ({
798
+ compare: { mode, ...extra.baseRef ? { baseRef: extra.baseRef } : {}, ignoreWhitespace },
799
+ snapshot: snapshot2,
800
+ files: files2,
801
+ hiddenCount: hiddenCount2,
802
+ truncated: extra.truncated ?? false,
803
+ ...extra.nextCursor ? { nextCursor: extra.nextCursor } : {}
804
+ });
805
+ let range;
806
+ let baseRef;
807
+ const marks = [mode, head ?? "-"];
808
+ if (mode === "base") {
809
+ baseRef = compare.baseRef ?? await defaultBase(repo) ?? void 0;
810
+ const base = baseRef ? await resolveBase(repo, baseRef) : void 0;
811
+ if (compare.baseRef && !base) throw new RpcError(ERROR.notFound, FIXED.unknownRef, { reason: "unknown_ref" });
812
+ const mergeBase = base && head ? (await runGit(repo, ["merge-base", "--end-of-options", base.oid, head], { okCodes: [0, 1] })).stdout.toString("utf8").trim() : "";
813
+ marks.push(baseRef ?? "-", base?.oid ?? "-", mergeBase || "-");
814
+ if (!/^[0-9a-f]{40,64}$/.test(mergeBase)) {
815
+ const snapshot2 = `s1.${hash(...marks).slice(0, 40)}`;
816
+ if (body && body.snapshot !== snapshot2) throw new RpcError(ERROR.conflict, FIXED.stale, { reason: "stale_snapshot" });
817
+ return done([], 0, snapshot2, { baseRef });
818
+ }
819
+ range = [mergeBase, head];
820
+ } else if (mode === "staged") {
821
+ range = ["--cached", head ?? repo.emptyTree];
822
+ } else if (mode === "uncommitted") {
823
+ range = [head ?? repo.emptyTree];
824
+ } else {
825
+ range = [];
826
+ }
827
+ const diffFlags = ["--no-color", "--no-ext-diff", "--no-textconv", "--ignore-submodules=dirty", "--submodule=short"];
828
+ const listed = await runGit(repo, ["diff", "--raw", "-z", "--no-abbrev", "-M", ...diffFlags, ...range, "--"]);
829
+ const all = parseRaw(listed.stdout);
830
+ const worktree = mode === "uncommitted" || mode === "unstaged";
831
+ const untracked = worktree ? await untrackedOf(repo, relative, WORKSPACE_GIT.maxUntracked) : { found: [], hidden: 0, more: false };
832
+ marks.push(hash(listed.stdout), untracked.found.join("\0"), String(untracked.more));
833
+ if (mode !== "base") marks.push(await statMark(path.join(repo.gitDir, "index")));
834
+ if (worktree) {
835
+ const files2 = [...all.filter((entry) => entry.dstMode !== "000000" && ZERO.test(entry.dstOid)).map((entry) => entry.path), ...untracked.found].slice(0, GIT_READ.maxSnapshotStats);
836
+ for (const file of files2) marks.push(file, await statMark(path.join(repo.root, ...file.split("/"))));
837
+ }
838
+ const snapshot = `s1.${hash(...marks).slice(0, 40)}`;
839
+ if (body && body.snapshot !== snapshot) throw new RpcError(ERROR.conflict, FIXED.stale, { reason: "stale_snapshot" });
840
+ let hiddenCount = untracked.hidden;
841
+ const entries = [];
842
+ for (const entry of all) {
843
+ if (relative !== void 0 && entry.path !== relative && entry.oldPath !== relative) continue;
844
+ if (blockedFilePath(entry.path) || entry.oldPath && blockedFilePath(entry.oldPath) || [...entry.path].length > 4096 || [...entry.oldPath ?? ""].length > 4096) {
845
+ hiddenCount++;
846
+ continue;
847
+ }
848
+ entries.push(entry);
849
+ }
850
+ for (const name of untracked.found) entries.push({ path: name, change: "untracked", srcMode: "000000", dstMode: "100644", srcOid: "", dstOid: "", untracked: true });
851
+ const offset = body?.offset ?? 0;
852
+ if (offset > entries.length) throw new RpcError(RPC_ERROR.invalidParams, FIXED.invalidCursor, { reason: "invalid_cursor" });
853
+ const files = [];
854
+ let used = 0;
855
+ let next;
856
+ for (let start = offset; start < entries.length && next === void 0; ) {
857
+ const window = await windowOf(repo, entries, start, mode);
858
+ const results = await diffWindow(repo, window.entries, mode, range, diffFlags, ignoreWhitespace);
859
+ for (let index = 0; index < results.length; index++) {
860
+ const result = results[index];
861
+ if (result === void 0) continue;
862
+ const cost = result.cost;
863
+ if (files.length && used + cost > PAGE_BYTES) {
864
+ next = start + index;
865
+ break;
866
+ }
867
+ used += cost;
868
+ files.push(result.file);
869
+ }
870
+ start += window.entries.length;
871
+ }
872
+ await sameConfig(repo);
873
+ const nextCursor = next === void 0 ? void 0 : (() => {
874
+ const nextBody = { offset: next, snapshot };
875
+ return `c1.${next}.${snapshot}.${mac(cursorScope(workspaceId, compare, relative, nextBody))}`;
876
+ })();
877
+ return done(files, hiddenCount, snapshot, { baseRef, truncated: next !== void 0 || untracked.more, nextCursor });
878
+ }
879
+ async function windowOf(repo, entries, start, mode) {
880
+ const candidates = entries.slice(start, start + GIT_READ.windowFiles).map((entry) => {
881
+ const special = entry.srcMode === GITLINK || entry.dstMode === GITLINK || entry.srcMode === SYMLINK || entry.dstMode === SYMLINK || entry.untracked || entry.conflicted && mode === "staged";
882
+ const old = special || ZERO.test(entry.srcMode) ? void 0 : { oid: entry.srcOid };
883
+ const now = special || ZERO.test(entry.dstMode) ? void 0 : ZERO.test(entry.dstOid) ? { file: entry.path } : { oid: entry.dstOid };
884
+ return { ...entry, old, new: now, sizes: [0, 0] };
885
+ });
886
+ const oids = [...new Set(candidates.flatMap((entry) => [entry.old, entry.new]).flatMap((side) => side && "oid" in side ? [side.oid] : []))];
887
+ const sizes = /* @__PURE__ */ new Map();
888
+ if (oids.length) {
889
+ const { stdout } = await runGit(repo, ["cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)"], { stdin: `${oids.join("\n")}
890
+ ` });
891
+ for (const line of stdout.toString("utf8").split("\n")) {
892
+ const [oid, type, size] = line.split(" ");
893
+ if (oid && type === "blob" && size !== void 0) sizes.set(oid, Number(size));
894
+ }
895
+ }
896
+ const sizeOf = async (side) => {
897
+ if (!side) return 0;
898
+ if ("oid" in side) return sizes.get(side.oid) ?? Number.MAX_SAFE_INTEGER;
899
+ try {
900
+ return Number((await lstat(path.join(repo.root, ...side.file.split("/")))).size);
901
+ } catch {
902
+ return 0;
903
+ }
904
+ };
905
+ const chosen = [];
906
+ let total = 0;
907
+ for (const entry of candidates) {
908
+ entry.sizes = [await sizeOf(entry.old), await sizeOf(entry.new)];
909
+ if (entry.untracked) entry.sizes = [0, await sizeOf({ file: entry.path })];
910
+ const reads = entry.sizes.reduce((sum, size) => sum + (size > GIT_READ.maxScanBytes ? 0 : size), 0);
911
+ if (chosen.length && total + reads > GIT_READ.windowBytes) break;
912
+ total += reads;
913
+ chosen.push(entry);
914
+ }
915
+ return { entries: chosen };
916
+ }
917
+ async function blobs(repo, oids, bytes) {
918
+ const contents = /* @__PURE__ */ new Map();
919
+ if (!oids.length) return contents;
920
+ const { stdout } = await runGit(repo, ["cat-file", "--batch"], { stdin: `${oids.join("\n")}
921
+ `, maxBytes: bytes + oids.length * 200 + 1024 });
922
+ let at = 0;
923
+ while (at < stdout.length) {
924
+ const newline = stdout.indexOf(10, at);
925
+ if (newline < 0) failed("unterminated object");
926
+ const [oid, type, size] = stdout.subarray(at, newline).toString("utf8").split(" ");
927
+ at = newline + 1;
928
+ if (type === "missing" || size === void 0) continue;
929
+ const length = Number(size);
930
+ if (!Number.isSafeInteger(length) || at + length > stdout.length) failed("unexpected object");
931
+ contents.set(oid, stdout.subarray(at, at + length));
932
+ at += length + 1;
933
+ }
934
+ return contents;
935
+ }
936
+ async function diffWindow(repo, planned, mode, range, diffFlags, ignoreWhitespace) {
937
+ const shown = (entry, kind, extra = {}, _cost = 0) => sized({ path: entry.path, ...entry.oldPath ? { oldPath: entry.oldPath } : {}, change: entry.change, kind, additions: 0, deletions: 0, hunks: [], ...extra });
938
+ const readable = (size) => size <= GIT_READ.maxScanBytes;
939
+ const wanted = /* @__PURE__ */ new Map();
940
+ for (const entry of planned) {
941
+ for (const [side, size] of [[entry.old, entry.sizes[0]], [entry.new, entry.sizes[1]]]) if (side && "oid" in side && readable(size)) wanted.set(side.oid, size);
942
+ }
943
+ const contents = await blobs(repo, [...wanted.keys()], [...wanted.values()].reduce((sum, size) => sum + size, 0));
944
+ const results = new Array(planned.length).fill(void 0);
945
+ const patched = [];
946
+ const scanned = /* @__PURE__ */ new Map();
947
+ for (const [index, entry] of planned.entries()) {
948
+ if (entry.srcMode === GITLINK || entry.dstMode === GITLINK) {
949
+ results[index] = shown(entry, "submodule");
950
+ continue;
951
+ }
952
+ if (entry.srcMode === SYMLINK || entry.dstMode === SYMLINK) {
953
+ results[index] = shown(entry, "symlink");
954
+ continue;
955
+ }
956
+ if (entry.untracked) {
957
+ results[index] = await untrackedFile(repo, entry, shown);
958
+ continue;
959
+ }
960
+ if (entry.conflicted && mode === "staged") {
961
+ results[index] = shown(entry, "text");
962
+ continue;
963
+ }
964
+ if (entry.sizes.some((size) => !readable(size))) {
965
+ results[index] = shown(entry, "too_large");
966
+ continue;
967
+ }
968
+ const sides = [];
969
+ let refused = false;
970
+ for (const side of [entry.old, entry.new]) {
971
+ if (!side) continue;
972
+ if ("oid" in side) {
973
+ const bytes = contents.get(side.oid);
974
+ if (bytes) sides.push(bytes);
975
+ else refused = true;
976
+ continue;
977
+ }
978
+ try {
979
+ const bytes = await readConfinedFile(repo.root, side.file.split("/"), side.file, GIT_READ.maxScanBytes);
980
+ if (bytes === "too_large") {
981
+ results[index] = shown(entry, "too_large");
982
+ refused = true;
983
+ break;
984
+ }
985
+ scanned.set(side.file, hash(bytes));
986
+ sides.push(bytes);
987
+ } catch {
988
+ refused = true;
989
+ }
990
+ }
991
+ if (results[index]) continue;
992
+ if (refused || sides.some(holdsKey)) {
993
+ results[index] = shown(entry, "withheld");
994
+ continue;
995
+ }
996
+ if (sides.some(likelyBinary)) {
997
+ results[index] = shown(entry, "binary");
998
+ continue;
999
+ }
1000
+ patched.push({ index, entry, group: entry.conflicted ? "ours" : entry.oldPath ? "renamed" : "plain" });
1001
+ }
1002
+ if (patched.length) await probe?.("scanned");
1003
+ for (const group of ["plain", "renamed", "ours"]) {
1004
+ const members = patched.filter((item) => item.group === group);
1005
+ for (let from = 0; from < members.length; ) {
1006
+ const chunk = [];
1007
+ let bytes = 0;
1008
+ while (from < members.length && (chunk.length === 0 || bytes < GIT_READ.maxArgBytes)) {
1009
+ const item = members[from++];
1010
+ bytes += Buffer.byteLength(item.entry.path) + Buffer.byteLength(item.entry.oldPath ?? "") + 2;
1011
+ chunk.push(item);
1012
+ }
1013
+ const flags = [...diffFlags, "-p", "-U3", "--inter-hunk-context=0", "--src-prefix=a/", "--dst-prefix=b/", group === "renamed" ? "-M" : "--no-renames", ...ignoreWhitespace ? ["-w"] : []];
1014
+ const args = group === "ours" ? ["diff", "-2", ...flags, "--"] : ["diff", ...flags, ...range, "--"];
1015
+ const stream = sectionsOf(WORKSPACE_GIT.maxFileBytes);
1016
+ await runGit(repo, [...args, ...chunk.flatMap((item) => item.entry.oldPath ? [item.entry.oldPath, item.entry.path] : [item.entry.path])], { onData: (data) => {
1017
+ stream.write(data);
1018
+ } });
1019
+ stream.end();
1020
+ const byHeader = new Map(chunk.map((item) => [headerOf(item.entry), item]));
1021
+ const seen = /* @__PURE__ */ new Set();
1022
+ for (const section of stream.sections) {
1023
+ const item = byHeader.get(section.header);
1024
+ if (!item || seen.has(section.header)) failed("a patch section for no listed file");
1025
+ seen.add(section.header);
1026
+ if (section.bytes > WORKSPACE_GIT.maxFileBytes) {
1027
+ results[item.index] = shown(item.entry, "too_large");
1028
+ continue;
1029
+ }
1030
+ if (holdsKey(Buffer.concat(section.chunks)) || !await unchanged(repo, item.entry, scanned)) {
1031
+ results[item.index] = shown(item.entry, "withheld");
1032
+ continue;
1033
+ }
1034
+ const parsed = parseSection(section);
1035
+ results[item.index] = parsed.binary ? shown(item.entry, "binary") : shown(item.entry, "text", { additions: parsed.additions, deletions: parsed.deletions, hunks: parsed.hunks }, section.bytes);
1036
+ }
1037
+ }
1038
+ }
1039
+ return results;
1040
+ }
1041
+ async function unchanged(repo, entry, scanned) {
1042
+ const side = entry.new;
1043
+ if (!side || !("file" in side)) return true;
1044
+ const before = scanned.get(side.file);
1045
+ if (before === void 0) return false;
1046
+ try {
1047
+ const bytes = await readConfinedFile(repo.root, side.file.split("/"), side.file, GIT_READ.maxScanBytes);
1048
+ return bytes !== "too_large" && hash(bytes) === before;
1049
+ } catch {
1050
+ return false;
1051
+ }
1052
+ }
1053
+ async function untrackedFile(repo, entry, shown) {
1054
+ const file = path.join(repo.root, ...entry.path.split("/"));
1055
+ let info;
1056
+ try {
1057
+ info = await lstat(file);
1058
+ } catch {
1059
+ return void 0;
1060
+ }
1061
+ if (info.isSymbolicLink()) return shown(entry, "symlink");
1062
+ if (!info.isFile()) return void 0;
1063
+ let bytes;
1064
+ try {
1065
+ bytes = await readConfinedFile(repo.root, entry.path.split("/"), entry.path, WORKSPACE_GIT.maxFileBytes);
1066
+ } catch (error) {
1067
+ if (error instanceof FileAccessError && error.reason === "not_found") return void 0;
1068
+ return shown(entry, "withheld");
1069
+ }
1070
+ if (bytes === "too_large") return shown(entry, "too_large");
1071
+ if (holdsKey(bytes)) return shown(entry, "withheld");
1072
+ if (likelyBinary(bytes)) return shown(entry, "binary");
1073
+ const { hunks, additions } = addedHunks(DECODER.decode(bytes));
1074
+ return shown(entry, "text", { additions, hunks }, bytes.length + additions);
1075
+ }
1076
+ const guarded = (method, run) => run().catch((error) => {
1077
+ if (error instanceof RpcError) throw error;
1078
+ log(`${method} failed`, { cause: error instanceof GitReadFailed ? error.cause : String(error?.message ?? error) });
1079
+ throw gitFailed();
1080
+ });
1081
+ return {
1082
+ status: (workspaceId) => guarded("workspace.git.status", () => status(workspaceId)),
1083
+ diff: (params) => guarded("workspace.git.diff", () => diff(params))
1084
+ };
1085
+ }
1086
+ export {
1087
+ GIT_READ,
1088
+ GitReadFailed,
1089
+ createGitReader,
1090
+ gitReadsRunning,
1091
+ scrubRemoteUrl,
1092
+ validBranchName
1093
+ };