@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
@@ -0,0 +1,123 @@
1
+ import { type GitCheckOptions } from './gitignore.js';
2
+ export { gitChecksRunning, resolveGit, GIT_CHECK } from './gitignore.js';
3
+ /**
4
+ * `workspace.files.search` (docs/protocol/alp-json-rpc-v1.md §12.3): the files of a workspace whose
5
+ * path matches a query, as Paseo's command center finds them (server/utils/directory-suggestions.ts
6
+ * at b63a325, with its workspace settings: relative paths, hidden and heavy directories skipped).
7
+ *
8
+ * Read-only and confined to the workspace: the walk starts at the root's real path and never
9
+ * follows a symbolic link (a link is neither listed nor entered). Each directory is checked before
10
+ * and after it is read: a real directory (not a link), at the real path it was reached by, the same
11
+ * one (device and inode) both times; otherwise what was read is dropped. Only names are read, never
12
+ * contents. A link swapped in and back out between those checks, by a writer racing inside the
13
+ * workspace, can still expose names of the directory it pointed to (Node has no openat/O_NOFOLLOW
14
+ * walk); docs/protocol/alp-json-rpc-v1.md §12.3. The walk stops at {@link LIMITS}, checked per
15
+ * entry; the answer then says `truncated`.
16
+ */
17
+ export declare const LIMITS: Readonly<{
18
+ /** Directory levels below the root that are entered (Paseo's DEFAULT_MAX_DEPTH). */
19
+ depth: 12;
20
+ /** Directory entries looked at (Paseo's DEFAULT_MAX_ENTRIES_SCANNED). */
21
+ scanned: 20000;
22
+ /** Wall time of one search. */
23
+ ms: 3000;
24
+ /** Results by default and at most (Paseo's DEFAULT_LIMIT, MAX_LIMIT). */
25
+ defaultLimit: 30;
26
+ maxLimit: 100;
27
+ }>;
28
+ export declare class FilesError extends Error {
29
+ }
30
+ /**
31
+ * The files under `projectRoot` matching `query`, best first. `projectRoot` must be an absolute path
32
+ * of a directory; anything else throws FilesError.
33
+ */
34
+ export declare function searchWorkspaceFiles(projectRoot: string, { query, limit, now, git }?: {
35
+ query?: string;
36
+ limit?: number;
37
+ now?: () => number;
38
+ git?: GitCheckOptions;
39
+ }): Promise<{
40
+ files: Array<{
41
+ path: string;
42
+ }>;
43
+ truncated?: true;
44
+ }>;
45
+ /**
46
+ * A refusal of workspace.files.list or workspace.files.read: the JSON-RPC code and `data.reason`
47
+ * alpd answers with. Messages are fixed or name only the client's own relative path, never a host
48
+ * path or anything read from a file.
49
+ */
50
+ export declare class FileAccessError extends Error {
51
+ readonly code: number;
52
+ readonly reason: string;
53
+ constructor(message: string, code: number, reason: string);
54
+ }
55
+ /**
56
+ * A path relative to the workspace as a client may send it, its segments, or a refusal: '/'
57
+ * separated, no leading slash, drive or backslash, no `.`, `..` or empty segment, no NUL, at most
58
+ * WORKSPACE_FILES.maxPathLength characters. A blocked path (blockedFilePath) is refused as such.
59
+ */
60
+ export declare function relativeSegments(relative: unknown): string[];
61
+ /**
62
+ * The bytes of a regular file reached by name, or undefined when it is larger than `maxBytes`;
63
+ * throws when it is missing, not a regular file, a link, has more than one name, or is not the
64
+ * file it was a moment before. The file is opened without following a final link and checked by
65
+ * its handle (same device and inode as by name, before and after).
66
+ */
67
+ /** Test probes: called between the checks of a read, where a racing writer could change the file. */
68
+ export type FileProbe = (step: 'checked' | 'read' | 'listed') => Promise<void> | void;
69
+ /**
70
+ * The bytes of the file at `segments` under the real root `root`, confined as readWorkspaceFile
71
+ * confines a read (every directory on the way a real directory reached by name and the same after
72
+ * the read; the file a regular file with one name, opened without following a link, the same by
73
+ * handle and by name), or `too_large` past `maxBytes`. Throws FileAccessError `linked` or
74
+ * `not_found` (its message names only `relative`). No block list or .gitignore check: the caller
75
+ * decides what may be read (workspace.git.diff, docs/protocol/alp-json-rpc-v1.md §12.5).
76
+ */
77
+ export declare function readConfinedFile(root: string, segments: readonly string[], relative: string, maxBytes: number): Promise<Buffer | 'too_large'>;
78
+ /** Paseo's isLikelyBinary (file-explorer/service.ts at b63a325): a NUL byte, or over 30% control characters. */
79
+ export declare function likelyBinary(buffer: Buffer): boolean;
80
+ /** PEM, OpenSSH and PuTTY private-key headers: a file holding one is refused whatever its name. */
81
+ export declare const PRIVATE_KEY: RegExp;
82
+ export type ListedEntry = {
83
+ name: string;
84
+ path: string;
85
+ kind: 'file' | 'directory';
86
+ size?: number;
87
+ modifiedAt?: string;
88
+ };
89
+ /**
90
+ * The entries of a directory under `projectRoot` (its root without `relative`): regular files and
91
+ * directories only (links, sockets, devices are left out), never a blocked one (blockedFilePath)
92
+ * and, unless `includeIgnored`, none .gitignore'd. Directories first, then by name. Each directory
93
+ * on the way is checked (real directory, real path, same device and inode) before and after the
94
+ * read. At most WORKSPACE_FILES.maxListEntries entries; then `truncated`.
95
+ */
96
+ export declare function listWorkspaceDirectory(projectRoot: string, { path: relative, includeIgnored, now, probe, git }?: {
97
+ path?: string;
98
+ includeIgnored?: boolean;
99
+ now?: () => number;
100
+ probe?: FileProbe;
101
+ git?: GitCheckOptions;
102
+ }): Promise<{
103
+ entries: ListedEntry[];
104
+ truncated?: true;
105
+ }>;
106
+ /**
107
+ * The content of a UTF-8 text file under `projectRoot`, read-only: refused when it is blocked
108
+ * (blockedFilePath), .gitignore'd (unless `includeIgnored`), missing or not a regular file,
109
+ * reached through a link (any directory on the way or the file), has more than one name (a hard
110
+ * link may share a file from anywhere), changes while it is read, is over
111
+ * WORKSPACE_FILES.maxReadBytes, or is not UTF-8 text.
112
+ */
113
+ export declare function readWorkspaceFile(projectRoot: string, { path: relative, includeIgnored, probe, git }: {
114
+ path: string;
115
+ includeIgnored?: boolean;
116
+ probe?: FileProbe;
117
+ git?: GitCheckOptions;
118
+ }): Promise<{
119
+ path: string;
120
+ content: string;
121
+ size: number;
122
+ modifiedAt: string;
123
+ }>;
package/dist/files.js ADDED
@@ -0,0 +1,365 @@
1
+ // packages/daemon/src/files.ts
2
+ import { constants } from "node:fs";
3
+ import { lstat, open, opendir, realpath, stat } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { ERROR, RPC_ERROR, WORKSPACE_FILES, blockedFilePath } from "@anhlp/alp-protocol";
6
+ import { gitIgnored, IgnoreUnknown, GIT_CHECK } from "./gitignore.js";
7
+ import { gitChecksRunning, resolveGit, GIT_CHECK as GIT_CHECK2 } from "./gitignore.js";
8
+ var LIMITS = Object.freeze({
9
+ /** Directory levels below the root that are entered (Paseo's DEFAULT_MAX_DEPTH). */
10
+ depth: 12,
11
+ /** Directory entries looked at (Paseo's DEFAULT_MAX_ENTRIES_SCANNED). */
12
+ scanned: 2e4,
13
+ /** Wall time of one search. */
14
+ ms: 3e3,
15
+ /** Results by default and at most (Paseo's DEFAULT_LIMIT, MAX_LIMIT). */
16
+ defaultLimit: 30,
17
+ maxLimit: 100
18
+ });
19
+ var HIDDEN_DIRECTORIES = /* @__PURE__ */ new Set([".agents", ".alp", ".claude", ".codex", ".github", ".opencode", ".paseo", ".vscode"]);
20
+ var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set(["node_modules", "venv", "env", "virtualenv", "dist", "build", "target", "out", "coverage", "vendor", "__pycache__", ".git"]);
21
+ var NONE = Number.MAX_SAFE_INTEGER;
22
+ async function identity(directory) {
23
+ const info = await lstat(directory, { bigint: true });
24
+ if (!info.isDirectory() || await realpath(directory) !== directory) return null;
25
+ return `${info.dev}:${info.ino}`;
26
+ }
27
+ function fuzzy(query, candidate) {
28
+ let at = 0;
29
+ let first = -1;
30
+ let previous = -1;
31
+ let gaps = 0;
32
+ for (let index = 0; index < candidate.length && at < query.length; index++) {
33
+ if (candidate[index] !== query[at]) continue;
34
+ if (first < 0) first = index;
35
+ if (previous >= 0) gaps += index - previous - 1;
36
+ previous = index;
37
+ at++;
38
+ }
39
+ return at === query.length && first >= 0 ? first + gaps : null;
40
+ }
41
+ function rank(relative, query) {
42
+ const lower = relative.toLowerCase();
43
+ const segments = lower.split("/");
44
+ const depth = segments.length;
45
+ if (!query) return { path: relative, tier: 3, segment: NONE, offset: NONE, fuzzy: NONE, depth };
46
+ const offset = lower.indexOf(query);
47
+ if (query.includes("/")) {
48
+ if (offset >= 0) return { path: relative, tier: lower.startsWith(query) ? 1 : 3, segment: NONE, offset, fuzzy: NONE, depth };
49
+ const spread = fuzzy(query, lower);
50
+ return spread === null ? null : { path: relative, tier: 4, segment: NONE, offset: NONE, fuzzy: spread, depth };
51
+ }
52
+ const last = fuzzy(query, segments.at(-1) ?? "");
53
+ const tiers = [(segment) => segment === query, (segment) => segment.startsWith(query), (segment) => segment.includes(query)];
54
+ for (const [tier, test] of tiers.entries()) {
55
+ const segment = segments.findIndex(test);
56
+ if (segment >= 0) return { path: relative, tier, segment, offset: offset >= 0 ? offset : NONE, fuzzy: last ?? NONE, depth };
57
+ }
58
+ if (last !== null) return { path: relative, tier: 4, segment: NONE, offset: NONE, fuzzy: last, depth };
59
+ return null;
60
+ }
61
+ var compare = (a, b) => a.tier - b.tier || a.segment - b.segment || a.offset - b.offset || a.fuzzy - b.fuzzy || a.depth - b.depth || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
62
+ var FilesError = class extends Error {
63
+ };
64
+ async function searchWorkspaceFiles(projectRoot, { query = "", limit = LIMITS.defaultLimit, now = Date.now, git } = {}) {
65
+ if (!path.isAbsolute(projectRoot)) throw new FilesError("projectRoot must be an absolute path");
66
+ let root;
67
+ try {
68
+ root = await realpath(projectRoot);
69
+ if (!(await stat(root)).isDirectory()) throw new Error("not a directory");
70
+ } catch {
71
+ throw new FilesError("projectRoot is not a directory alpd can read");
72
+ }
73
+ const wanted = query.trim().replace(/\\/g, "/").replace(/^\.?\/+/, "").toLowerCase();
74
+ const count = Math.max(1, Math.min(LIMITS.maxLimit, Math.trunc(limit)));
75
+ const deadline = now() + LIMITS.ms;
76
+ const realDeadline = Date.now() + LIMITS.ms;
77
+ const found = [];
78
+ let scanned = 0;
79
+ let truncated = false;
80
+ let level = [""];
81
+ for (let depth = 0; level.length && !truncated; depth++) {
82
+ const next = [];
83
+ const levelFiles = [];
84
+ for (const relative of level) {
85
+ if (scanned >= LIMITS.scanned || now() > deadline) {
86
+ truncated = true;
87
+ break;
88
+ }
89
+ const directory = relative ? path.join(root, ...relative.split("/")) : root;
90
+ const files = [];
91
+ const directories = [];
92
+ try {
93
+ const before = await identity(directory);
94
+ if (!before) continue;
95
+ for await (const entry of await opendir(directory)) {
96
+ if (++scanned > LIMITS.scanned || now() > deadline) {
97
+ truncated = true;
98
+ break;
99
+ }
100
+ const name = entry.name;
101
+ const child = relative ? `${relative}/${name}` : name;
102
+ if (name.includes("\\") || blockedFilePath(child)) continue;
103
+ if (entry.isFile()) {
104
+ if (name.startsWith(".")) continue;
105
+ const ranked = rank(child, wanted);
106
+ if (ranked) files.push(ranked);
107
+ } else if (entry.isDirectory()) {
108
+ if (IGNORED_DIRECTORIES.has(name) || name.startsWith(".") && !HIDDEN_DIRECTORIES.has(name)) continue;
109
+ if (depth < LIMITS.depth) directories.push(child);
110
+ }
111
+ }
112
+ if (await identity(directory) !== before) continue;
113
+ } catch {
114
+ continue;
115
+ }
116
+ levelFiles.push(...files);
117
+ next.push(...directories);
118
+ if (truncated) break;
119
+ }
120
+ const remaining = Math.min(deadline - now(), realDeadline - Date.now());
121
+ if (remaining <= 0) {
122
+ truncated = true;
123
+ break;
124
+ }
125
+ let ignored;
126
+ try {
127
+ ignored = await gitIgnored(root, [...levelFiles.map((file) => file.path), ...next], {
128
+ ...git,
129
+ timeoutMs: Math.min(git?.timeoutMs ?? GIT_CHECK.timeoutMs, remaining)
130
+ });
131
+ } catch (error) {
132
+ if (!(error instanceof IgnoreUnknown)) throw error;
133
+ return { files: [], truncated: true };
134
+ }
135
+ found.push(...levelFiles.filter((file) => !ignored?.has(file.path)));
136
+ level = next.filter((directory) => !ignored?.has(directory));
137
+ }
138
+ found.sort(compare);
139
+ return { files: found.slice(0, count).map((entry) => ({ path: entry.path })), ...truncated ? { truncated: true } : {} };
140
+ }
141
+ var FileAccessError = class extends Error {
142
+ constructor(message, code, reason) {
143
+ super(message);
144
+ this.code = code;
145
+ this.reason = reason;
146
+ }
147
+ };
148
+ var LIST_LIMITS = Object.freeze({ scanned: 2e4, ms: 3e3 });
149
+ var OPEN_FLAGS = process.platform === "win32" ? constants.O_RDONLY : constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
150
+ var notFound = (relative) => new FileAccessError(`No readable file or directory at ${relative}`, ERROR.notFound, "not_found");
151
+ var linked = (relative) => new FileAccessError(`${relative} is reached through a link, has more than one name, or changed while it was read; alpd does not follow links`, ERROR.forbidden, "linked");
152
+ async function realRoot(projectRoot) {
153
+ if (!path.isAbsolute(projectRoot)) throw new FilesError("projectRoot must be an absolute path");
154
+ try {
155
+ const root = await realpath(projectRoot);
156
+ if (!(await stat(root)).isDirectory()) throw new Error("not a directory");
157
+ return root;
158
+ } catch {
159
+ throw new FilesError("projectRoot is not a directory alpd can read");
160
+ }
161
+ }
162
+ function relativeSegments(relative) {
163
+ if (typeof relative !== "string" || !relative || [...relative].length > WORKSPACE_FILES.maxPathLength || relative.includes("\0") || relative.includes("\\") || relative.startsWith("/") || /^[A-Za-z]:/.test(relative)) {
164
+ throw new FileAccessError("path must be a relative path inside the workspace, with / between names and no . or .. segment", RPC_ERROR.invalidParams, "invalid_path");
165
+ }
166
+ const segments = relative.split("/");
167
+ if (segments.some((segment) => segment === "" || segment === "." || segment === "..")) {
168
+ throw new FileAccessError("path must be a relative path inside the workspace, with / between names and no . or .. segment", RPC_ERROR.invalidParams, "invalid_path");
169
+ }
170
+ if (blockedFilePath(relative)) throw new FileAccessError(`${relative} is not readable remotely: .git, .env files, ALP configuration and key or credential files are always refused`, ERROR.forbidden, "blocked_path");
171
+ return segments;
172
+ }
173
+ async function directoryChain(root, segments, relative) {
174
+ const paths = [root];
175
+ for (let index = 0; index < segments.length; index++) paths.push(path.join(root, ...segments.slice(0, index + 1)));
176
+ const identities = [];
177
+ for (const directory of paths) identities.push(await directoryIdentity(directory, relative));
178
+ return { paths, identities };
179
+ }
180
+ async function directoryIdentity(directory, relative) {
181
+ let info;
182
+ try {
183
+ info = await lstat(directory, { bigint: true });
184
+ } catch {
185
+ throw notFound(relative);
186
+ }
187
+ if (info.isSymbolicLink()) throw linked(relative);
188
+ if (!info.isDirectory()) throw notFound(relative);
189
+ let real;
190
+ try {
191
+ real = await realpath(directory);
192
+ } catch {
193
+ throw notFound(relative);
194
+ }
195
+ if (real !== directory) throw linked(relative);
196
+ return `${info.dev}:${info.ino}`;
197
+ }
198
+ async function sameChain(chain, relative) {
199
+ for (const [index, directory] of chain.paths.entries()) {
200
+ let now;
201
+ try {
202
+ now = await directoryIdentity(directory, relative);
203
+ } catch {
204
+ throw linked(relative);
205
+ }
206
+ if (now !== chain.identities[index]) throw linked(relative);
207
+ }
208
+ }
209
+ async function ignoredOf(root, paths, git) {
210
+ try {
211
+ const ignored = await gitIgnored(root, paths, git);
212
+ return ignored ? (entry) => ignored.has(entry) : () => false;
213
+ } catch (error) {
214
+ if (!(error instanceof IgnoreUnknown)) throw error;
215
+ return () => true;
216
+ }
217
+ }
218
+ async function readConfined(file, maxBytes, probe) {
219
+ const before = await lstat(file, { bigint: true });
220
+ if (before.isSymbolicLink()) throw Object.assign(new Error("link"), { linked: true });
221
+ if (!before.isFile()) throw new Error("not a file");
222
+ if (before.nlink > 1n) throw Object.assign(new Error("hard link"), { linked: true });
223
+ if (await realpath(file) !== file) throw Object.assign(new Error("real path differs"), { linked: true });
224
+ if (before.size > BigInt(maxBytes)) return void 0;
225
+ await probe?.("checked");
226
+ let handle;
227
+ try {
228
+ handle = await open(file, OPEN_FLAGS);
229
+ } catch (error) {
230
+ if (error.code === "ELOOP") throw Object.assign(new Error("link"), { linked: true });
231
+ throw error;
232
+ }
233
+ try {
234
+ const opened = await handle.stat({ bigint: true });
235
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino || opened.nlink > 1n) throw Object.assign(new Error("changed"), { linked: true });
236
+ const buffer = Buffer.alloc(maxBytes + 1);
237
+ let length = 0;
238
+ while (length < buffer.length) {
239
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
240
+ if (!bytesRead) break;
241
+ length += bytesRead;
242
+ }
243
+ if (length > maxBytes) return void 0;
244
+ await probe?.("read");
245
+ const after = await lstat(file, { bigint: true });
246
+ if (after.dev !== before.dev || after.ino !== before.ino) throw Object.assign(new Error("changed"), { linked: true });
247
+ return { bytes: buffer.subarray(0, length), modifiedAt: opened.mtime };
248
+ } finally {
249
+ await handle.close();
250
+ }
251
+ }
252
+ async function readConfinedFile(root, segments, relative, maxBytes) {
253
+ const chain = await directoryChain(root, segments.slice(0, -1), relative);
254
+ let read;
255
+ try {
256
+ read = await readConfined(path.join(root, ...segments), maxBytes);
257
+ } catch (error) {
258
+ if (error.linked) throw linked(relative);
259
+ throw notFound(relative);
260
+ }
261
+ await sameChain(chain, relative);
262
+ return read === void 0 ? "too_large" : read.bytes;
263
+ }
264
+ function likelyBinary(buffer) {
265
+ if (!buffer.length) return false;
266
+ let suspicious = 0;
267
+ for (const byte of buffer) {
268
+ if (byte === 0) return true;
269
+ if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13 || byte === 127) suspicious++;
270
+ }
271
+ return suspicious / buffer.length > 0.3;
272
+ }
273
+ var PRIVATE_KEY = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----|PuTTY-User-Key-File-\d+:/;
274
+ var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
275
+ async function listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored = false, now = Date.now, probe, git } = {}) {
276
+ const root = await realRoot(projectRoot);
277
+ const segments = relative === void 0 ? [] : relativeSegments(relative);
278
+ const shown = relative ?? ".";
279
+ const chain = await directoryChain(root, segments, shown);
280
+ const directory = chain.paths.at(-1);
281
+ const prefix = segments.length ? `${relative}/` : "";
282
+ const deadline = now() + LIST_LIMITS.ms;
283
+ const candidates = [];
284
+ let scanned = 0;
285
+ let truncated = false;
286
+ try {
287
+ for await (const entry of await opendir(directory)) {
288
+ if (++scanned > LIST_LIMITS.scanned || now() > deadline) {
289
+ truncated = true;
290
+ break;
291
+ }
292
+ const kind = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : void 0;
293
+ if (!kind) continue;
294
+ const child = `${prefix}${entry.name}`;
295
+ if (entry.name.includes("\\") || blockedFilePath(child)) continue;
296
+ candidates.push({ name: entry.name, child, kind });
297
+ }
298
+ } catch {
299
+ throw notFound(shown);
300
+ }
301
+ if (!includeIgnored) {
302
+ const ignored = await ignoredOf(root, [...segments.length ? [relative] : [], ...candidates.map((entry) => entry.child)], git);
303
+ if (segments.length && ignored(relative)) throw new FileAccessError(`${relative} is ignored by .gitignore; ask with includeIgnored to see it`, ERROR.forbidden, "ignored");
304
+ for (let index = candidates.length - 1; index >= 0; index--) if (ignored(candidates[index].child)) candidates.splice(index, 1);
305
+ }
306
+ const entries = [];
307
+ for (const { name, child, kind } of candidates) {
308
+ if (entries.length >= WORKSPACE_FILES.maxListEntries) {
309
+ truncated = true;
310
+ break;
311
+ }
312
+ let info;
313
+ try {
314
+ info = await lstat(path.join(directory, name));
315
+ } catch {
316
+ continue;
317
+ }
318
+ if (kind === "file" ? !info.isFile() : !info.isDirectory()) continue;
319
+ entries.push({ name, path: child, kind, ...kind === "file" ? { size: info.size } : {}, modifiedAt: info.mtime.toISOString() });
320
+ }
321
+ await probe?.("listed");
322
+ await sameChain(chain, shown);
323
+ entries.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === "directory" ? -1 : 1) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
324
+ return { entries, ...truncated ? { truncated: true } : {} };
325
+ }
326
+ async function readWorkspaceFile(projectRoot, { path: relative, includeIgnored = false, probe, git }) {
327
+ const root = await realRoot(projectRoot);
328
+ const segments = relativeSegments(relative);
329
+ const chain = await directoryChain(root, segments.slice(0, -1), relative);
330
+ if (!includeIgnored && (await ignoredOf(root, [relative], git))(relative)) throw new FileAccessError(`${relative} is ignored by .gitignore; ask with includeIgnored to read it`, ERROR.forbidden, "ignored");
331
+ const file = path.join(root, ...segments);
332
+ let read;
333
+ try {
334
+ read = await readConfined(file, WORKSPACE_FILES.maxReadBytes, probe);
335
+ } catch (error) {
336
+ if (error.linked) throw linked(relative);
337
+ throw notFound(relative);
338
+ }
339
+ if (read === void 0) throw new FileAccessError(`${relative} is larger than ${WORKSPACE_FILES.maxReadBytes} bytes`, ERROR.failed, "too_large");
340
+ await sameChain(chain, relative);
341
+ let content;
342
+ try {
343
+ if (likelyBinary(read.bytes)) throw new Error("binary");
344
+ content = UTF8.decode(read.bytes);
345
+ } catch {
346
+ throw new FileAccessError(`${relative} is not a UTF-8 text file`, ERROR.failed, "binary");
347
+ }
348
+ if (PRIVATE_KEY.test(content)) throw new FileAccessError(`${relative} holds a private key; such files are never readable remotely`, ERROR.forbidden, "blocked_path");
349
+ return { path: relative, content, size: read.bytes.length, modifiedAt: read.modifiedAt.toISOString() };
350
+ }
351
+ export {
352
+ FileAccessError,
353
+ FilesError,
354
+ GIT_CHECK2 as GIT_CHECK,
355
+ LIMITS,
356
+ PRIVATE_KEY,
357
+ gitChecksRunning,
358
+ likelyBinary,
359
+ listWorkspaceDirectory,
360
+ readConfinedFile,
361
+ readWorkspaceFile,
362
+ relativeSegments,
363
+ resolveGit,
364
+ searchWorkspaceFiles
365
+ };
package/dist/git.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ import type { GitCompare, GitDiffPage, GitStatus } from '@anhlp/alp-protocol';
2
+ /**
3
+ * `workspace.git.status` and `workspace.git.diff` (docs/protocol/alp-json-rpc-v1.md §12.5): the
4
+ * read-only Git state of a registry workspace, for Paseo's branch header and Changes panel.
5
+ *
6
+ * The workspace and its repository configuration are not trusted, so Git runs boxed in:
7
+ * - the Git found on the absolute PATH entries outside the workspace, by its real path
8
+ * (gitignore.ts resolveGit), spawned with an argument list, no shell, in the workspace's real
9
+ * path, its own process group killed at the call's deadline;
10
+ * - GIT_DIR and GIT_WORK_TREE set by alpd to the repository it checked (the workspace's `.git`,
11
+ * validated as the registry validates worktrees: core repositoryIdentity), every other GIT_*
12
+ * variable of alpd's dropped, no system or global configuration, no optional locks, no prompts,
13
+ * no lazy fetch, no replace objects, PATH without the workspace's entries;
14
+ * - configuration overrides so nothing the repository names runs: no fsmonitor, hooks to the null
15
+ * device, no pager, no colour, no external diff or textconv (flags too), every
16
+ * filter.<driver>.{clean,smudge,process} the repository's configuration names emptied and
17
+ * `required` false, no submodule recursion (`--ignore-submodules=dirty`: a gitlink's recorded
18
+ * commit only, never a Git run inside it), no network protocol, `diff.autoRefreshIndex` off (a
19
+ * porcelain `git diff` would otherwise rewrite the index even with GIT_OPTIONAL_LOCKS=0);
20
+ * - `--literal-pathspecs`: a path is never pathspec magic, and always after `--`; a base branch is
21
+ * a validated name resolved only as `refs/remotes/origin/<name>` then `refs/heads/<name>` with
22
+ * `rev-parse --verify --end-of-options`, never a revision expression;
23
+ * - every output read as a stream with a bound; at most GIT_READ.maxConcurrent Git processes at
24
+ * once in alpd.
25
+ * Content alpd shows is checked first: both sides of every file are scanned for a private key
26
+ * (files.ts PRIVATE_KEY), historical and deleted ones included; untracked files are read by alpd
27
+ * itself, confined as workspace.files.read confines a read. Errors carry fixed messages; the
28
+ * cause is logged, never answered.
29
+ */
30
+ export declare const GIT_READ: Readonly<{
31
+ /** One call (all of its Git processes, waiting for a turn included) gets this long. */
32
+ timeoutMs: 15000;
33
+ /** Git processes these reads run at once in alpd, and processes that may wait for one. */
34
+ maxConcurrent: 4;
35
+ maxQueued: 32;
36
+ maxErrorBytes: number;
37
+ /** Configuration, change list and untracked list output, at most. */
38
+ maxListBytes: number;
39
+ /** One patch stream, at most (its files are at most a window's worth of content). */
40
+ maxPatchStreamBytes: number;
41
+ /** One side of a file scanned for a private key; a larger side is `too_large`. */
42
+ maxScanBytes: number;
43
+ /** Files whose content one window reads and diffs together, and their content's total. */
44
+ windowFiles: 64;
45
+ windowBytes: number;
46
+ /** Pathspec bytes on one command line. */
47
+ maxArgBytes: number;
48
+ /** Worktree files whose size and time enter a diff's snapshot. */
49
+ maxSnapshotStats: 5000;
50
+ }>;
51
+ /** A Git read that failed: answered as `1000 git_failed` with a fixed message; `cause` is logged only. */
52
+ export declare class GitReadFailed extends Error {
53
+ readonly cause: string;
54
+ constructor(cause: string);
55
+ }
56
+ /** Git processes these reads run now, for tests. */
57
+ export declare const gitReadsRunning: () => number;
58
+ /** A branch name as `git check-ref-format --branch` accepts one, never starting with '-' (no option, no revision syntax). */
59
+ export declare function validBranchName(name: unknown): name is string;
60
+ /**
61
+ * origin's URL as a client may see it: no user, password or token, no query or fragment; a local
62
+ * path, a `file:` URL or anything unrecognized is null.
63
+ */
64
+ export declare function scrubRemoteUrl(url: string | null): string | null;
65
+ export type GitReaderOptions = {
66
+ registry: {
67
+ resolve(workspaceId: string): Promise<string>;
68
+ };
69
+ /** Which git: a name looked up on PATH (outside the workspace), or an absolute path (tests). */
70
+ binary?: string;
71
+ timeoutMs?: number;
72
+ log?: (message: string, fields: Record<string, unknown>) => void;
73
+ /** Tests only: called after a window's contents were scanned and before Git writes their patch, where a racing writer could change a file. */
74
+ probe?: (step: 'scanned') => Promise<void> | void;
75
+ };
76
+ type DiffParams = {
77
+ workspaceId: string;
78
+ compare: GitCompare;
79
+ path?: string;
80
+ cursor?: string;
81
+ };
82
+ export declare function createGitReader({ registry, binary, timeoutMs, log, probe }: GitReaderOptions): {
83
+ status: (workspaceId: unknown) => Promise<GitStatus>;
84
+ diff: (params: DiffParams) => Promise<GitDiffPage>;
85
+ };
86
+ export type GitReader = ReturnType<typeof createGitReader>;
87
+ export {};