@anhlp/alp-daemon 0.0.1-beta.3 → 0.0.1-beta.5

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 (95) hide show
  1. package/README.md +4 -0
  2. package/dist/THIRD-PARTY-NOTICES.txt +26 -1
  3. package/dist/alpd.js +29928 -14898
  4. package/dist/attachments.d.ts +187 -0
  5. package/dist/attachments.js +856 -0
  6. package/dist/build-manifest.json +34 -1
  7. package/dist/conversation.d.ts +119 -0
  8. package/dist/conversation.js +688 -0
  9. package/dist/disk.d.ts +67 -0
  10. package/dist/disk.js +152 -0
  11. package/dist/files.d.ts +154 -2
  12. package/dist/files.js +392 -68
  13. package/dist/git.d.ts +93 -0
  14. package/dist/git.js +1192 -0
  15. package/dist/gitignore.d.ts +5 -0
  16. package/dist/gitignore.js +7 -1
  17. package/dist/history.d.ts +24 -0
  18. package/dist/history.js +149 -0
  19. package/dist/index.d.ts +7 -0
  20. package/dist/index.js +21 -1
  21. package/dist/lifecycle.d.ts +101 -0
  22. package/dist/lifecycle.js +239 -0
  23. package/dist/main.js +43 -11
  24. package/dist/native-terminal.d.ts +45 -0
  25. package/dist/native-terminal.js +198 -0
  26. package/dist/operations.d.ts +8 -2
  27. package/dist/operations.js +20 -10
  28. package/dist/registry.d.ts +89 -0
  29. package/dist/registry.js +343 -0
  30. package/dist/scheduler.d.ts +96 -0
  31. package/dist/scheduler.js +296 -0
  32. package/dist/schedules.d.ts +70 -0
  33. package/dist/schedules.js +246 -0
  34. package/dist/server.d.ts +14 -2
  35. package/dist/server.js +836 -90
  36. package/dist/store.d.ts +72 -2
  37. package/dist/store.js +111 -4
  38. package/dist/terminal-native/README.md +201 -0
  39. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  40. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  41. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  42. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  43. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  44. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  45. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  46. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  48. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  49. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  50. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  51. package/dist/terminal-native/terminal-owner.c +389 -0
  52. package/dist/terminal-screen.d.ts +24 -0
  53. package/dist/terminal-screen.js +99 -0
  54. package/dist/terminals.d.ts +193 -0
  55. package/dist/terminals.js +570 -0
  56. package/dist/windows-terminal.d.ts +29 -0
  57. package/dist/windows-terminal.js +122 -0
  58. package/dist/worktrees.d.ts +65 -0
  59. package/dist/worktrees.js +318 -0
  60. package/native/README.md +201 -0
  61. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  62. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  63. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  64. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  65. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  66. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  67. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  68. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  69. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  70. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  71. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  72. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  73. package/native/terminal-owner.c +389 -0
  74. package/package.json +70 -7
  75. package/src/attachments.ts +908 -0
  76. package/src/conversation.ts +857 -0
  77. package/src/disk.ts +175 -0
  78. package/src/files.ts +528 -82
  79. package/src/git.ts +1140 -0
  80. package/src/gitignore.ts +10 -0
  81. package/src/history.ts +118 -0
  82. package/src/index.ts +7 -0
  83. package/src/lifecycle.ts +283 -0
  84. package/src/main.ts +37 -12
  85. package/src/native-terminal.ts +122 -0
  86. package/src/operations.ts +27 -11
  87. package/src/registry.ts +238 -0
  88. package/src/scheduler.ts +432 -0
  89. package/src/schedules.ts +297 -0
  90. package/src/server.ts +948 -102
  91. package/src/store.ts +117 -4
  92. package/src/terminal-screen.ts +74 -0
  93. package/src/terminals.ts +641 -0
  94. package/src/windows-terminal.ts +123 -0
  95. package/src/worktrees.ts +382 -0
package/src/disk.ts ADDED
@@ -0,0 +1,175 @@
1
+ import { statfs, unlink, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ /** Errors that mean alpd cannot write its home now: the disk is full, a quota is used up, or it became read-only. */
5
+ const DISK_CODES = new Set(['ENOSPC', 'EDQUOT', 'EROFS']);
6
+
7
+ /** Whether `error` (or the error it wraps) says the disk cannot take writes. */
8
+ export function isDiskError(error: unknown): boolean {
9
+ for (let current: any = error, depth = 0; current && depth < 4; current = current.cause, depth++) {
10
+ if (typeof current.code === 'string' && DISK_CODES.has(current.code)) return true;
11
+ }
12
+ return false;
13
+ }
14
+
15
+ export const GiB = 1024 ** 3;
16
+ const MiB = 1024 ** 2;
17
+
18
+ export type DiskRuntime = {
19
+ holdForDisk(reason: string): unknown;
20
+ releaseDisk(by: string): unknown;
21
+ diskHeld(): boolean;
22
+ diskLow(free: string): void;
23
+ };
24
+
25
+ export type DiskGuardOptions = {
26
+ /** The directory whose disk alpd writes: ALP_HOME. */
27
+ home: string;
28
+ runtime: DiskRuntime;
29
+ log: { warn(message: string, fields?: Record<string, unknown>): void; info(message: string, fields?: Record<string, unknown>): void };
30
+ /** How often space is checked; ALP checks every minute. */
31
+ intervalMs?: number;
32
+ /** Below this, alpd warns once that space runs low (2 GiB). */
33
+ lowBytes?: number;
34
+ /** Below this, alpd holds work before writes fail (100 MiB). */
35
+ criticalBytes?: number;
36
+ /** Free space alpd needs to resume work it held (256 MiB); above criticalBytes, so it does not flap. */
37
+ resumeBytes?: number;
38
+ /** How long one statfs or probe may take (10 s). */
39
+ checkTimeoutMs?: number;
40
+ /** Free bytes on the disk of a directory; undefined when unknown. */
41
+ free?: (directory: string) => Promise<number | undefined>;
42
+ /** Writes and removes a small file; rejects when the disk takes no writes. */
43
+ probe?: (directory: string) => Promise<void>;
44
+ };
45
+
46
+ async function freeBytes(directory: string) {
47
+ try {
48
+ const info = await statfs(directory);
49
+ return Number(info.bavail) * Number(info.bsize);
50
+ } catch {
51
+ return undefined;
52
+ }
53
+ }
54
+
55
+ async function probeWrite(directory: string) {
56
+ const file = path.join(directory, `.alpd-disk-probe-${process.pid}`);
57
+ try { await writeFile(file, 'x'.repeat(4096), { mode: 0o600 }); }
58
+ finally { await unlink(file).catch(() => {}); }
59
+ }
60
+
61
+ export function formatBytes(bytes: number) {
62
+ return bytes >= GiB ? `${(bytes / GiB).toFixed(1)} GB` : `${Math.max(0, Math.round(bytes / MiB))} MB`;
63
+ }
64
+
65
+ /**
66
+ * Keeps alpd running when its disk fills (t-2831): a write failing with ENOSPC, EDQUOT or
67
+ * EROFS pauses all of ALP and parks running assignments (as a usage limit does), instead of
68
+ * stopping alpd. Reads go on. Every minute alpd checks free space and probes a write; when
69
+ * the disk takes writes again it lifts the pause it made and parked work continues. A pause
70
+ * the user made, and their alp resume, stay theirs. alpd deletes nothing to make room.
71
+ */
72
+ export function createDiskGuard(options: DiskGuardOptions) {
73
+ const { home, runtime, log } = options;
74
+ const lowBytes = options.lowBytes ?? 2 * GiB;
75
+ const criticalBytes = options.criticalBytes ?? 100 * MiB;
76
+ const resumeBytes = Math.max(options.resumeBytes ?? 256 * MiB, criticalBytes);
77
+ const free = options.free ?? freeBytes;
78
+ const probe = options.probe ?? probeWrite;
79
+ let warnedLow = false;
80
+ let timer: ReturnType<typeof setInterval> | undefined;
81
+ let checking: Promise<void> | undefined;
82
+ let last: { at: string; free?: number; writable: boolean } | undefined;
83
+ /** Set from the first disk error until space returns: a log line about it, itself failing, must not hold again (and recurse). */
84
+ let full = false;
85
+ /** Checks in a row that found the disk writable; two are needed to resume, so a borderline disk does not flap. */
86
+ let good = 0;
87
+
88
+ function hold(reason: string) {
89
+ good = 0;
90
+ if (full && runtime.diskHeld()) return;
91
+ const first = !full;
92
+ full = true;
93
+ // Hold first: the log line below may fail on this disk and report again, which now returns at once.
94
+ runtime.holdForDisk(reason);
95
+ if (first) log.warn(`${reason}; ALP pauses its work until the disk takes writes again`, { code: 'ALP_DISK_FULL' });
96
+ }
97
+
98
+ /** A write failed; returns whether it was a disk error that alpd now handles. */
99
+ function report(error: unknown) {
100
+ if (!isDiskError(error)) return false;
101
+ const code = (error as any)?.code ?? (error as any)?.cause?.code;
102
+ hold(code === 'EROFS' ? 'the disk is read-only' : 'the disk is full');
103
+ return true;
104
+ }
105
+
106
+ async function checkOnce() {
107
+ const bytes = await bounded(free(home), undefined);
108
+ const writable = await bounded(probe(home).then(() => true, error => isDiskError(error) ? false : true), !full);
109
+ last = { at: new Date().toISOString(), ...(bytes === undefined ? {} : { free: bytes }), writable };
110
+ const shown = bytes === undefined ? 'unknown' : formatBytes(bytes);
111
+ if (full) {
112
+ if (!writable || (bytes !== undefined && bytes < resumeBytes)) { good = 0; if (!runtime.diskHeld()) runtime.holdForDisk(writable ? `the disk is almost full (${shown} free)` : 'the disk is full'); return; }
113
+ if (++good < 2) return;
114
+ full = false;
115
+ good = 0;
116
+ warnedLow = false;
117
+ // Release first: a log line failing on a disk that filled again holds again, rightly.
118
+ runtime.releaseDisk('alpd, after disk space returned');
119
+ log.info(`the disk takes writes again (${shown} free); ALP resumes its work`, { code: 'ALP_DISK_BACK', free: bytes });
120
+ return;
121
+ }
122
+ if (!writable) { hold('the disk is full'); return; }
123
+ if (bytes !== undefined && bytes < criticalBytes) { hold(`the disk is almost full (${shown} free)`); return; }
124
+ if (bytes !== undefined && bytes < lowBytes) {
125
+ if (!warnedLow) { warnedLow = true; log.warn(`disk space is low: ${shown} free`, { code: 'ALP_DISK_LOW', free: bytes }); runtime.diskLow(shown); }
126
+ } else if (bytes !== undefined && bytes >= lowBytes * 1.25) warnedLow = false;
127
+ }
128
+
129
+ /** A statfs or probe that hangs (a stuck network disk) gives `fallback` after 10 s, so checks go on. */
130
+ function bounded<T>(work: Promise<T>, fallback: T): Promise<T> {
131
+ let timer: ReturnType<typeof setTimeout> | undefined;
132
+ const late = new Promise<T>(resolve => { timer = setTimeout(() => resolve(fallback), options.checkTimeoutMs ?? 10_000); });
133
+ return Promise.race([work, late]).finally(() => clearTimeout(timer));
134
+ }
135
+
136
+ /** Checks space now; concurrent calls share one check. */
137
+ function check() {
138
+ checking ??= checkOnce().catch(() => {}).finally(() => { checking = undefined; });
139
+ return checking;
140
+ }
141
+
142
+ return {
143
+ report,
144
+ check,
145
+ status: () => ({ held: runtime.diskHeld(), full, ...(last ? { last } : {}) }),
146
+ start() {
147
+ if (timer) return;
148
+ timer = setInterval(() => void check(), options.intervalMs ?? 60_000);
149
+ timer.unref?.();
150
+ void check();
151
+ },
152
+ stop() { if (timer) clearInterval(timer); timer = undefined; },
153
+ };
154
+ }
155
+
156
+ /**
157
+ * Makes process.stdout and stderr survive a full disk when they are files (alpd's log, as the
158
+ * detached launcher opens it): a failed write is dropped, not thrown later as an 'error' event
159
+ * that would end alpd, and logging continues once space returns. Other streams (a terminal,
160
+ * a pipe) keep Node's own writes but no longer turn a write error into a crash.
161
+ */
162
+ export function guardOutput(onError: (error: unknown) => void, fs: { fstatSync(fd: number): { isFile(): boolean }; writeSync(fd: number, data: string | Uint8Array): number }) {
163
+ for (const [stream, fd] of [[process.stdout, 1], [process.stderr, 2]] as const) {
164
+ stream.on('error', onError);
165
+ let file = false;
166
+ try { file = fs.fstatSync(fd).isFile(); } catch {}
167
+ if (!file) continue;
168
+ stream.write = ((chunk: string | Uint8Array, encoding?: unknown, callback?: unknown) => {
169
+ try { fs.writeSync(fd, chunk); } catch (error) { onError(error); }
170
+ const done = typeof encoding === 'function' ? encoding : callback;
171
+ if (typeof done === 'function') done();
172
+ return true;
173
+ }) as typeof stream.write;
174
+ }
175
+ }