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

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 (115) 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 +456 -0
  5. package/dist/alp-templates.d.ts +5 -0
  6. package/dist/alpd.js +64050 -0
  7. package/dist/attachments.d.ts +187 -0
  8. package/dist/attachments.js +856 -0
  9. package/dist/build-manifest.json +150 -0
  10. package/dist/conversation.d.ts +119 -0
  11. package/dist/conversation.js +688 -0
  12. package/dist/disk.d.ts +67 -0
  13. package/dist/disk.js +152 -0
  14. package/dist/files.d.ts +262 -0
  15. package/dist/files.js +674 -0
  16. package/dist/git.d.ts +98 -0
  17. package/dist/git.js +1246 -0
  18. package/dist/gitignore.d.ts +62 -0
  19. package/dist/gitignore.js +254 -0
  20. package/dist/history.d.ts +24 -0
  21. package/dist/history.js +149 -0
  22. package/dist/index.d.ts +11 -0
  23. package/dist/index.js +28 -0
  24. package/dist/lifecycle.d.ts +101 -0
  25. package/dist/lifecycle.js +239 -0
  26. package/dist/lock.d.ts +21 -0
  27. package/dist/lock.js +42 -0
  28. package/dist/main.d.ts +1 -0
  29. package/dist/main.js +363 -0
  30. package/dist/model-catalog.d.ts +2 -0
  31. package/dist/model-catalog.js +44 -0
  32. package/dist/native-entry.d.ts +2 -0
  33. package/dist/native-entry.js +3 -0
  34. package/dist/native-register.d.ts +1 -0
  35. package/dist/native-register.js +13 -0
  36. package/dist/native-terminal.d.ts +45 -0
  37. package/dist/native-terminal.js +201 -0
  38. package/dist/operations.d.ts +40 -0
  39. package/dist/operations.js +313 -0
  40. package/dist/registry.d.ts +89 -0
  41. package/dist/registry.js +343 -0
  42. package/dist/rpc-error.d.ts +6 -0
  43. package/dist/rpc-error.js +11 -0
  44. package/dist/scheduler.d.ts +96 -0
  45. package/dist/scheduler.js +298 -0
  46. package/dist/schedules.d.ts +70 -0
  47. package/dist/schedules.js +246 -0
  48. package/dist/server.d.ts +60 -0
  49. package/dist/server.js +1958 -0
  50. package/dist/store.d.ts +178 -0
  51. package/dist/store.js +386 -0
  52. package/dist/terminal-native/README.md +201 -0
  53. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  54. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  55. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  56. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  57. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  58. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  59. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  60. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  61. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  62. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  63. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  64. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  65. package/dist/terminal-native/terminal-owner.c +389 -0
  66. package/dist/terminal-screen.d.ts +24 -0
  67. package/dist/terminal-screen.js +99 -0
  68. package/dist/terminals.d.ts +203 -0
  69. package/dist/terminals.js +570 -0
  70. package/dist/windows-terminal.d.ts +32 -0
  71. package/dist/windows-terminal.js +79 -0
  72. package/dist/worktrees.d.ts +65 -0
  73. package/dist/worktrees.js +318 -0
  74. package/native/README.md +201 -0
  75. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  76. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  77. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  78. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  79. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  80. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  81. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  82. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  83. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  84. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  85. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  86. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  87. package/native/terminal-owner.c +389 -0
  88. package/package.json +163 -4
  89. package/src/alp-templates.d.ts +5 -0
  90. package/src/attachments.ts +908 -0
  91. package/src/conversation.ts +857 -0
  92. package/src/disk.ts +175 -0
  93. package/src/files.ts +884 -0
  94. package/src/git.ts +1220 -0
  95. package/src/gitignore.ts +277 -0
  96. package/src/history.ts +118 -0
  97. package/src/index.ts +12 -0
  98. package/src/lifecycle.ts +283 -0
  99. package/src/lock.ts +53 -0
  100. package/src/main.ts +381 -0
  101. package/src/model-catalog.ts +36 -0
  102. package/src/native-entry.ts +5 -0
  103. package/src/native-register.ts +21 -0
  104. package/src/native-terminal.ts +127 -0
  105. package/src/operations.ts +329 -0
  106. package/src/registry.ts +238 -0
  107. package/src/rpc-error.ts +4 -0
  108. package/src/scheduler.ts +438 -0
  109. package/src/schedules.ts +297 -0
  110. package/src/server.ts +2238 -0
  111. package/src/store.ts +449 -0
  112. package/src/terminal-screen.ts +74 -0
  113. package/src/terminals.ts +653 -0
  114. package/src/windows-terminal.ts +74 -0
  115. package/src/worktrees.ts +382 -0
@@ -0,0 +1,277 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { accessSync, constants, lstatSync, realpathSync, statSync, type BigIntStats } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ /**
6
+ * Which paths of a workspace `.gitignore` hides, for workspace.files.list and workspace.files.read
7
+ * (docs/protocol/alp-json-rpc-v1.md §12.4), as Git itself says: `git check-ignore`, so its rules
8
+ * are Git's exactly (every `.gitignore` on the way, `.git/info/exclude`, `core.excludesFile`).
9
+ *
10
+ * The workspace is not trusted, so Git runs boxed in:
11
+ * - the Git found on the absolute entries of PATH, by its real path: never a `git` the workspace
12
+ * holds (a relative or empty PATH entry, or Windows searching the working directory first, would
13
+ * run one), whatever the spelling of the entry or a link on the way (see resolveGit);
14
+ * - spawned with an argument list, never a shell, in the workspace's real path;
15
+ * - `--no-index`: the index is not read (no fsmonitor or index extension runs; a tracked file a
16
+ * rule matches is hidden too), and `core.fsmonitor` is turned off besides;
17
+ * - an environment without any GIT_* variable of alpd's own, no prompts, no optional locks;
18
+ * - paths on stdin separated by NUL (`-z`), each as `./<path>` so that Git reads none as pathspec
19
+ * magic (`:(glob)…`, `:!…`) and none is ever an argument;
20
+ * - at most MAX_CONCURRENT at once in alpd, a bounded queue, a hard timeout that kills its whole
21
+ * process group, and a cap on what it may print.
22
+ * A timeout, a crash, a refusal, a full queue or an answer that is not plainly a list of the paths
23
+ * asked fails closed: the caller treats the paths as ignored. Git missing, or a workspace in no
24
+ * repository (no `.git` in it or above it): no rules apply, and only the block list hides anything.
25
+ */
26
+
27
+ export const GIT_CHECK = Object.freeze({
28
+ /** Git gets this long per request, waiting for a turn included, then is killed. */
29
+ timeoutMs: 2_000,
30
+ /** Git processes alpd runs at once, and requests that may wait for one. */
31
+ maxConcurrent: 4,
32
+ maxQueued: 64,
33
+ maxErrorBytes: 64 * 1024,
34
+ });
35
+
36
+ /** Git's answer could not be had: whether the paths are ignored is not known, so they count as ignored. */
37
+ export class IgnoreUnknown extends Error {
38
+ constructor(why: string) { super(`git check-ignore failed: ${why}`); }
39
+ }
40
+
41
+ export type GitCheckOptions = { binary?: string; timeoutMs?: number };
42
+
43
+ /** alpd's environment without Git's variables (GIT_DIR, GIT_WORK_TREE, GIT_CONFIG_*…), which would point Git elsewhere. */
44
+ function gitEnvironment(): NodeJS.ProcessEnv {
45
+ const env: NodeJS.ProcessEnv = {};
46
+ for (const [key, value] of Object.entries(process.env)) if (!/^GIT_/i.test(key)) env[key] = value;
47
+ return { ...env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' };
48
+ }
49
+
50
+ const executable = (file: string) => {
51
+ try {
52
+ if (!statSync(file).isFile()) return false;
53
+ if (process.platform !== 'win32') accessSync(file, constants.X_OK);
54
+ return true;
55
+ } catch {
56
+ return false;
57
+ }
58
+ };
59
+
60
+ /** The file system's identity of a directory: one per directory, whatever path names it. */
61
+ type Identity = Pick<BigIntStats, 'dev' | 'ino'>;
62
+ const identity = (file: string): Identity => { const { dev, ino } = statSync(file, { bigint: true }); return { dev, ino }; };
63
+ // macOS and Windows file systems compare names without case, mostly: a name compare there folds it.
64
+ const foldCase = process.platform === 'darwin' || process.platform === 'win32';
65
+ const comparable = (file: string) => (foldCase ? file.toLowerCase() : file);
66
+
67
+ /**
68
+ * Whether `file` is `root` or inside it, however either is spelled: a case-insensitive file
69
+ * system's other case, a Windows drive letter's case or 8.3 short name, a link, a bind mount. Both
70
+ * are made real paths by the system (realpath(3), which spells names as they are stored), and then
71
+ * each directory from `file` up to the file system's root is compared with `root` by device and
72
+ * inode, and by its name (case-folded where names are, for a file system without inode numbers).
73
+ * Anything that cannot be resolved or examined counts as inside: the caller skips it.
74
+ */
75
+ function insideRoot(file: string, root: { path: string; id: Identity }): boolean {
76
+ let directory;
77
+ try { directory = realpathSync.native(file); } catch { return true; }
78
+ const rootName = comparable(root.path.endsWith(path.sep) && root.path.length > 1 ? root.path.slice(0, -1) : root.path);
79
+ for (;;) {
80
+ const name = comparable(directory);
81
+ if (name === rootName || name.startsWith(rootName.endsWith(path.sep) ? rootName : `${rootName}${path.sep}`)) return true;
82
+ let id;
83
+ try { id = identity(directory); } catch { return true; }
84
+ if (root.id.ino !== 0n && id.dev === root.id.dev && id.ino === root.id.ino) return true;
85
+ const parent = path.dirname(directory);
86
+ if (parent === directory) return false;
87
+ directory = parent;
88
+ }
89
+ }
90
+
91
+ /** The workspace as insideRoot compares it, or undefined if it cannot be examined. */
92
+ function rootOf(root: string): { path: string; id: Identity } | undefined {
93
+ try {
94
+ const real = realpathSync.native(root);
95
+ return { path: real, id: identity(real) };
96
+ } catch {
97
+ return undefined;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * The absolute path of `name` on the absolute entries of PATH (Windows: with .exe or .com), or
103
+ * undefined. An absolute `name` (tests) is taken when it is an executable file. Relative and empty
104
+ * PATH entries are skipped: they name the working directory, which is the workspace.
105
+ *
106
+ * With `root`, nothing in the workspace is ever the answer (alpd started by npm or npx has
107
+ * `<project>/node_modules/.bin` on PATH): a PATH entry inside `root` is skipped, and so is a
108
+ * binary that is, or links to, a file inside it; both by insideRoot, which no other spelling of
109
+ * the path fools. The answer is then the binary's real path, so a link swapped later changes
110
+ * nothing. A workspace that cannot be examined finds no Git at all (IgnoreUnknown).
111
+ */
112
+ export function resolveGit(name = 'git', searchPath = process.env.PATH ?? process.env.Path ?? '', root?: string): string | undefined {
113
+ const box = root === undefined ? undefined : rootOf(root);
114
+ if (root !== undefined && !box) throw new IgnoreUnknown('the workspace cannot be examined');
115
+ /** `file` as the answer, or undefined: not executable, or in the workspace. */
116
+ const accept = (file: string) => {
117
+ if (!executable(file)) return undefined;
118
+ if (!box) return file;
119
+ let real;
120
+ try { real = realpathSync.native(file); } catch { return undefined; }
121
+ return insideRoot(path.dirname(real), box) || !executable(real) ? undefined : real;
122
+ };
123
+ if (path.isAbsolute(name)) return accept(name);
124
+ if (name.includes('/') || name.includes('\\')) return undefined;
125
+ const names = process.platform === 'win32' ? [`${name}.exe`, `${name}.com`] : [name];
126
+ for (const directory of searchPath.split(path.delimiter)) {
127
+ if (!directory || !path.isAbsolute(directory)) continue;
128
+ if (box && insideRoot(directory, box)) continue;
129
+ for (const candidate of names) {
130
+ const file = accept(path.join(directory, candidate));
131
+ if (file) return file;
132
+ }
133
+ }
134
+ return undefined;
135
+ }
136
+
137
+ /**
138
+ * The absolute entries of PATH outside `root` (insideRoot), for the environment of a Git alpd runs
139
+ * in a workspace: whatever Git itself starts is then never found in the workspace either.
140
+ */
141
+ export function searchPathOutside(root: string, searchPath = process.env.PATH ?? process.env.Path ?? ''): string {
142
+ const box = rootOf(root);
143
+ if (!box) throw new IgnoreUnknown('the workspace cannot be examined');
144
+ return searchPath.split(path.delimiter).filter(directory => directory && path.isAbsolute(directory) && !insideRoot(directory, box)).join(path.delimiter);
145
+ }
146
+
147
+ /** Whether `root` or a directory above it holds a `.git` entry: Git saying "not a git repository" there is a broken repository, not none. */
148
+ function hasGitEntry(root: string): boolean {
149
+ for (let directory = root; ; directory = path.dirname(directory)) {
150
+ try {
151
+ lstatSync(path.join(directory, '.git'));
152
+ return true;
153
+ } catch (error) {
154
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw new IgnoreUnknown('cannot examine .git');
155
+ }
156
+ if (path.dirname(directory) === directory) return false;
157
+ }
158
+ }
159
+
160
+ // The slots: at most maxConcurrent Git processes; others wait in a bounded queue.
161
+ let running = 0;
162
+ const waiting: Array<() => void> = [];
163
+ function acquire(deadline: number): Promise<() => void> {
164
+ const release = () => { running--; waiting.shift()?.(); };
165
+ if (running < GIT_CHECK.maxConcurrent) { running++; return Promise.resolve(release); }
166
+ if (waiting.length >= GIT_CHECK.maxQueued) return Promise.reject(new IgnoreUnknown('too many waiting'));
167
+ return new Promise((resolve, reject) => {
168
+ const turn = () => { clearTimeout(timer); running++; resolve(release); };
169
+ const timer = setTimeout(() => {
170
+ const index = waiting.indexOf(turn);
171
+ if (index >= 0) waiting.splice(index, 1);
172
+ reject(new IgnoreUnknown('timed out waiting for a turn'));
173
+ }, Math.max(0, deadline - Date.now()));
174
+ waiting.push(turn);
175
+ });
176
+ }
177
+
178
+ /** Git processes running now, for tests. */
179
+ export const gitChecksRunning = () => running;
180
+
181
+ /**
182
+ * The paths among `paths` (relative to `root`, '/'-separated, already checked) that Git ignores;
183
+ * null when no rules apply (Git is not installed, or `root` is in no repository). Throws
184
+ * IgnoreUnknown on anything else.
185
+ */
186
+ export async function gitIgnored(root: string, paths: readonly string[], { binary = 'git', timeoutMs = GIT_CHECK.timeoutMs }: GitCheckOptions = {}): Promise<Set<string> | null> {
187
+ if (!paths.length) return new Set();
188
+ const git = resolveGit(binary, undefined, root);
189
+ if (!git) return null;
190
+ const deadline = Date.now() + timeoutMs;
191
+ const release = await acquire(deadline);
192
+ try {
193
+ return await check(git, root, paths, deadline, timeoutMs);
194
+ } finally {
195
+ release();
196
+ }
197
+ }
198
+
199
+ function check(git: string, root: string, paths: readonly string[], deadline: number, timeoutMs: number): Promise<Set<string> | null> {
200
+ const input = `${paths.map(entry => `./${entry}`).join('\0')}\0`;
201
+ // Git echoes only what it was asked, so what it prints never exceeds what it was sent.
202
+ const maxOutputBytes = Buffer.byteLength(input) + 1024;
203
+ return new Promise((resolve, reject) => {
204
+ let settled = false;
205
+ let timer: ReturnType<typeof setTimeout> | undefined;
206
+ let child: ReturnType<typeof spawn>;
207
+ // POSIX: its own process group, so a timeout kills whatever it started too.
208
+ const group = process.platform !== 'win32';
209
+ const kill = () => {
210
+ try {
211
+ if (group && child.pid) process.kill(-child.pid, 'SIGKILL');
212
+ else child.kill('SIGKILL');
213
+ } catch {
214
+ // already gone
215
+ }
216
+ };
217
+ const finish = (outcome: () => void) => {
218
+ if (settled) return;
219
+ settled = true;
220
+ if (timer) clearTimeout(timer);
221
+ outcome();
222
+ };
223
+ try {
224
+ child = spawn(git, ['-c', 'core.fsmonitor=false', 'check-ignore', '--no-index', '--stdin', '-z'], {
225
+ cwd: root, env: gitEnvironment(), shell: false, windowsHide: true, detached: group, stdio: ['pipe', 'pipe', 'pipe'],
226
+ });
227
+ } catch (error) {
228
+ reject(new IgnoreUnknown(String((error as Error).message)));
229
+ return;
230
+ }
231
+ timer = setTimeout(() => finish(() => { kill(); reject(new IgnoreUnknown('timed out')); }), Math.max(1, Math.min(timeoutMs, deadline - Date.now())));
232
+ const out: Buffer[] = [];
233
+ let outBytes = 0;
234
+ let err = '';
235
+ child.stdout!.on('data', (chunk: Buffer) => {
236
+ outBytes += chunk.length;
237
+ if (outBytes > maxOutputBytes) finish(() => { kill(); reject(new IgnoreUnknown('more output than input')); });
238
+ else out.push(chunk);
239
+ });
240
+ child.stderr!.on('data', (chunk: Buffer) => { if (err.length < GIT_CHECK.maxErrorBytes) err += chunk.toString('utf8'); });
241
+ child.on('error', error => finish(() => {
242
+ // Git was resolved already. ENOENT can also mean a missing cwd or interpreter;
243
+ // it does not establish that no ignore rules apply.
244
+ reject(new IgnoreUnknown(error.message));
245
+ }));
246
+ child.on('close', code => finish(() => {
247
+ // No repository: no rules. A `.git` that Git cannot use (a worktree whose repository moved)
248
+ // is not "no repository": fail closed.
249
+ if (code === 128 && /not a git repository/i.test(err)) {
250
+ try {
251
+ if (hasGitEntry(root)) reject(new IgnoreUnknown('a .git Git cannot use'));
252
+ else resolve(null);
253
+ } catch (error) { reject(error); }
254
+ return;
255
+ }
256
+ // 0: some paths are ignored; 1: none is.
257
+ if (code !== 0 && code !== 1) { reject(new IgnoreUnknown(`exit ${code}`)); return; }
258
+ if (err.length || (code === 1 && outBytes) || (code === 0 && !outBytes)) {
259
+ reject(new IgnoreUnknown('inconsistent exit status or diagnostics')); return;
260
+ }
261
+ const output = Buffer.concat(out).toString('utf8');
262
+ if (outBytes && !output.endsWith('\0')) { reject(new IgnoreUnknown('unterminated answer')); return; }
263
+ const asked = new Set(paths);
264
+ const ignored = new Set<string>();
265
+ for (const entry of output.split('\0')) {
266
+ if (!entry) continue;
267
+ const relative = entry.startsWith('./') ? entry.slice(2) : undefined;
268
+ if (relative === undefined || !asked.has(relative)) { reject(new IgnoreUnknown('an answer for a path not asked')); return; }
269
+ ignored.add(relative);
270
+ }
271
+ resolve(ignored);
272
+ }));
273
+ // A Git that exits before reading everything closes the pipe: its exit decides.
274
+ child.stdin!.on('error', () => {});
275
+ child.stdin!.end(input);
276
+ });
277
+ }
package/src/history.ts ADDED
@@ -0,0 +1,118 @@
1
+ import { open, readFile, writeFile, rename, stat } from 'node:fs/promises';
2
+ import { createReadStream } from 'node:fs';
3
+ import { randomBytes, createHmac, timingSafeEqual } from 'node:crypto';
4
+ import type { Envelope } from '@anhlp/alp-protocol/events';
5
+
6
+ /** Derived fixed-width index: offset, byte length, stable event cursor (three u64s).
7
+ * A first-use migration scans once; subsequent pages seek at most limit index records
8
+ * and at most maxBytes timeline bytes. Metadata commits the recoverable index prefix.
9
+ */
10
+ const WIDTH = 24;
11
+ type Meta = { generation: string; secret: string; ino: number; bytes: number; count: number; tip: number };
12
+ export type HistoryItem = Envelope | { cursor: number; oversized: { bytes: number } };
13
+ export class HistoryError extends Error {
14
+ constructor(public reason: 'invalid_cursor' | 'stale_cursor', message: string) { super(message); }
15
+ }
16
+ export function createHistoryIndex(file: string) {
17
+ let pending: Promise<unknown> = Promise.resolve();
18
+ const index = `${file}.idx`;
19
+ const metadata = `${file}.history.json`;
20
+ async function sync(): Promise<Meta> {
21
+ const info = await stat(file).catch((error: any) => { if (error.code === 'ENOENT') return undefined; throw error; });
22
+ let meta: Meta | undefined;
23
+ try { meta = JSON.parse(await readFile(metadata, 'utf8')); } catch (error: any) { if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; }
24
+ if (meta && (!/^[0-9a-f]{32}$/.test(meta.generation) || !/^[0-9a-f]{64}$/.test(meta.secret) || ![meta.bytes, meta.count, meta.tip, meta.ino].every(value => Number.isSafeInteger(value) && value >= 0))) meta = undefined;
25
+ const indexInfo = await stat(index).catch((error: any) => { if (error.code === 'ENOENT') return undefined; throw error; });
26
+ if (!meta || !indexInfo || indexInfo.size < meta.count * WIDTH || (meta.ino !== 0 && meta.ino !== (info?.ino ?? 0)) || meta.bytes > (info?.size ?? 0)) {
27
+ meta = { generation: randomBytes(16).toString('hex'), secret: randomBytes(32).toString('hex'), ino: info?.ino ?? 0, bytes: 0, count: 0, tip: 0 };
28
+ await writeFile(index, '', { mode: 0o600 });
29
+ }
30
+ if (meta.ino === 0 && info) meta.ino = info.ino;
31
+ const handle = await open(index, 'a+', 0o600);
32
+ try {
33
+ await handle.truncate(meta.count * WIDTH);
34
+ if (info && info.size > meta.bytes) {
35
+ let offset = meta.bytes;
36
+ let start = offset;
37
+ let fragments: Buffer[] = [];
38
+ for await (const raw of createReadStream(file, { start: offset, end: info.size - 1, highWaterMark: 65536 })) {
39
+ const chunk = raw as Buffer;
40
+ let from = 0;
41
+ for (let at = 0; at < chunk.length; at++) if (chunk[at] === 10) {
42
+ const part = chunk.subarray(from, at);
43
+ fragments.push(part);
44
+ const length = offset + at + 1 - start;
45
+ let cursor = meta.tip + 1;
46
+ const body = Buffer.concat(fragments).toString('utf8');
47
+ try { const value = JSON.parse(body); if (Number.isSafeInteger(value.cursor) && value.cursor > meta.tip) cursor = value.cursor; }
48
+ catch { throw new Error('Unreadable history line'); }
49
+ const entry = Buffer.alloc(WIDTH);
50
+ [start, length, cursor].forEach((value, i) => entry.writeBigUInt64LE(BigInt(value), i * 8));
51
+ await handle.write(entry);
52
+ meta.count++; meta.tip = cursor; meta.bytes = offset + at + 1;
53
+ start = meta.bytes; fragments = []; from = at + 1;
54
+ }
55
+ const rest = chunk.subarray(from);
56
+ fragments.push(rest);
57
+ offset += chunk.length;
58
+ }
59
+ }
60
+ const temporary = `${metadata}.tmp`;
61
+ await writeFile(temporary, JSON.stringify(meta), { mode: 0o600 });
62
+ await rename(temporary, metadata);
63
+ return meta;
64
+ } finally { await handle.close(); }
65
+ }
66
+ return {
67
+ page(sessionId: string, options: { before?: string; limit?: number; maxBytes?: number } = {}) {
68
+ const run = pending.then(async () => {
69
+ const { before, limit = 200 } = options;
70
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500) throw new Error('limit must be between 1 and 500');
71
+ const maxBytes = Math.min(512 * 1024, options.maxBytes ?? 512 * 1024);
72
+ if (maxBytes < 2048) throw new Error('history frame budget too small');
73
+ const meta = await sync();
74
+ const sign = (body: string) => createHmac('sha256', meta.secret).update(body).digest('base64url');
75
+ let position = meta.count, tip = meta.tip;
76
+ if (before !== undefined) {
77
+ if (typeof before !== 'string' || before.length > 4096) throw new HistoryError('invalid_cursor', 'Invalid history cursor');
78
+ try {
79
+ const [body, signature, extra] = before.split('.');
80
+ const value = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
81
+ if (value.sessionId !== sessionId) throw new Error();
82
+ if (value.generation !== meta.generation) throw new HistoryError('stale_cursor', 'History generation changed');
83
+ const expected = Buffer.from(sign(body)); const received = Buffer.from(signature ?? '');
84
+ if (extra || expected.length !== received.length || !timingSafeEqual(expected, received)) throw new Error();
85
+ if (!Number.isSafeInteger(value.position) || value.position < 0 || value.position > meta.count || !Number.isSafeInteger(value.tip) || value.tip < 0 || value.tip > meta.tip) throw new Error();
86
+ position = value.position; tip = value.tip;
87
+ } catch (error) { if (error instanceof HistoryError) throw error; throw new HistoryError('invalid_cursor', 'Invalid history cursor'); }
88
+ }
89
+ const items: HistoryItem[] = [];
90
+ let bytes = 1024;
91
+ const idx = await open(index, 'r');
92
+ const timeline = meta.count ? await open(file, 'r') : undefined;
93
+ try {
94
+ while (position > 0 && items.length < limit) {
95
+ const entry = Buffer.alloc(WIDTH);
96
+ if ((await idx.read(entry, 0, WIDTH, (position - 1) * WIDTH)).bytesRead !== WIDTH) throw new Error('Incomplete history index');
97
+ const [offset, length, cursor] = [0, 8, 16].map(at => Number(entry.readBigUInt64LE(at)));
98
+ let item: HistoryItem;
99
+ if (length > maxBytes - 1024) item = { cursor, oversized: { bytes: length } };
100
+ else {
101
+ if (bytes + length > maxBytes) break;
102
+ const data = Buffer.alloc(length);
103
+ if ((await timeline!.read(data, 0, length, offset)).bytesRead !== length) throw new Error('History changed during read');
104
+ item = { ...JSON.parse(data.toString('utf8')), cursor };
105
+ }
106
+ const size = Buffer.byteLength(JSON.stringify(item)) + 1;
107
+ if (bytes + size > maxBytes) break;
108
+ items.unshift(item); bytes += size; position--;
109
+ }
110
+ } finally { await idx.close(); await timeline?.close(); }
111
+ const body = Buffer.from(JSON.stringify({ sessionId, generation: meta.generation, position, tip })).toString('base64url');
112
+ return { generation: meta.generation, items, hasOlder: position > 0, ...(position > 0 ? { olderCursor: `${body}.${sign(body)}` } : {}), tipCursor: tip };
113
+ });
114
+ pending = run.catch(() => {});
115
+ return run;
116
+ },
117
+ };
118
+ }
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ // alpd's building blocks, for embedding and tests; src/daemon/main.ts is the daemon itself.
2
+ export { createDaemonServer, ERROR } from './server.js';
3
+ export type { DaemonConnection, DaemonServer, SessionSummary } from './server.js';
4
+ export { createStore } from './store.js';
5
+ export type { SessionRecord, SessionStatus, Store } from './store.js';
6
+ export { createScheduleStore, PROMPT_CHARS, SCHEDULE_ID, SCHEDULE_VERSION } from './schedules.js';
7
+ export type { ScheduleRecord, ScheduleStore } from './schedules.js';
8
+ export { createScheduler, duration, renderPrompt, SCHEDULE_GRACE_MS, SCHEDULE_TICK_MS } from './scheduler.js';
9
+ export type { ScheduleDelivery, Scheduler } from './scheduler.js';
10
+ export { attachmentLimits, attachmentName, createAttachmentStore, readAttachmentConfig, sniffMimeType } from './attachments.js';
11
+ export type { AttachmentReader, AttachmentRuntime, AttachmentStore, Principal } from './attachments.js';
12
+ export { createDiskGuard, isDiskError } from './disk.js';