@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
package/src/store.ts ADDED
@@ -0,0 +1,449 @@
1
+ import { createHistoryIndex } from './history.js';
2
+ import { appendFile, mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
3
+ import { replaceFile } from './lock.js';
4
+ import { randomBytes } from 'node:crypto';
5
+ import path from 'node:path';
6
+ import { createLogger } from '@anhlp/alp-core/log';
7
+ import type { Envelope, SessionSnapshot, SessionSpec } from '@anhlp/alp-runtime/index';
8
+ import type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
9
+ import type { TurnAttention } from '@anhlp/alp-protocol/events';
10
+ import type { ConversationBranch, ForkProvenance, NativeBase } from '@anhlp/alp-protocol/session';
11
+
12
+ /** A branch a rewind set aside (§12.7): its public description, the native conversation and where its timeline lies. */
13
+ export type StoredBranch = ConversationBranch & {
14
+ /** The native conversation the root continued before the rewind: never deleted, so the branch stays recoverable. */
15
+ threadId: string;
16
+ base?: NativeBase;
17
+ /** The first discarded cursor, and the rewind's marker cursor (the branch holds what lay between). */
18
+ cut: number;
19
+ marker: number;
20
+ };
21
+
22
+ /**
23
+ * alpd's durable state (plans/reference/ALPD.md §5, §66): one JSON record per session,
24
+ * written atomically, one append-only JSONL timeline per tree, and one receipt per
25
+ * delivered prompt. Writes survive a crash of the alpd process once their promise
26
+ * resolves; nothing is fsynced, so a power loss or a failing disk may lose recent writes.
27
+ */
28
+
29
+ // The session lifecycle and the error shape are neutral (ALPD §18): the protocol owns them so
30
+ // viewers and integrations speak one language. Re-exported here to keep the daemon's API stable.
31
+ export type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
32
+
33
+ export type SessionRecord = {
34
+ version: 1;
35
+ id: string;
36
+ rootId: string;
37
+ /** The client's request, kept for roots so they can be resumed. */
38
+ spec?: SessionSpec;
39
+ delegation?: boolean;
40
+ session?: SessionSnapshot;
41
+ status: SessionStatus;
42
+ lastError?: SessionError;
43
+ title?: string;
44
+ /** Set aside by the user: closed, and listed only when asked (ALPD §61). */
45
+ archived?: boolean;
46
+ /** A root's last turn that ended unseen, until a client acknowledges it or another turn starts (Paseo's requiresAttention). */
47
+ attention?: TurnAttention;
48
+ /** Claude: the conversation `session.threadId` is made from on its first prompt, after a fork or rewind (§12.7). */
49
+ base?: NativeBase;
50
+ /** Where this root was forked from (§12.7). */
51
+ forkedFrom?: ForkProvenance;
52
+ /** Stable creation ownership; current native binding/title may change after a fork. */
53
+ forkAttempt?: { key: string; attemptId?: string; createdAt: string; fingerprint: string };
54
+ /** Branches rewinds set aside, oldest first (§12.7). */
55
+ branches?: StoredBranch[];
56
+ /** Atomic proof of completed conversation commits whose journal marker may be missing. */
57
+ lifecycleCommits?: Record<string, { operation: string; requestId: string; createdAt: string; fingerprint: string; attemptId?: string; result: any }>;
58
+ createdAt: string;
59
+ updatedAt: string;
60
+ };
61
+
62
+ /**
63
+ * Delivery of one clientMessageId; `pending` means alpd may have stopped while sending it.
64
+ * A completed receipt says what the runtime answered: `unknown` when the provider may or
65
+ * may not have the message (its process died or timed out mid-request).
66
+ */
67
+ export type Receipt = {
68
+ version: 1;
69
+ sessionId: string;
70
+ clientMessageId: string;
71
+ fingerprint: string;
72
+ state: 'pending' | 'completed';
73
+ outcome?: 'accepted' | 'failed' | 'unknown';
74
+ error?: { message: string; code?: string };
75
+ /** Completed at the next start from the tree's timeline, not by the delivery itself. */
76
+ reconciled?: boolean;
77
+ updatedAt: string;
78
+ };
79
+
80
+ /** A receipt file that exists but cannot be read as one: its delivery's outcome is unknown. */
81
+ export type UnreadableReceipt = { version: 1; state: 'unreadable' };
82
+
83
+ /** Failed writes since alpd started; `ok` until the first one (ALPD §66). */
84
+ export type StoreHealth = { ok: boolean; failures: number; lastError?: { at: string; operation: string; message: string } };
85
+
86
+ const log = createLogger({ component: 'store' });
87
+
88
+ const SAFE = /[^\w.:-]/g;
89
+ const fileName = (id: string) => id.replace(SAFE, '_');
90
+ const TAIL_CHUNK = 64 * 1024;
91
+
92
+ export type Store = ReturnType<typeof createStore>;
93
+
94
+ export function createStore(root: string, options: { onWriteError?: (error: unknown) => void } = {}) {
95
+ const sessionsDir = path.join(root, 'sessions');
96
+ const timelineDir = path.join(root, 'timeline');
97
+ const historyIndexes = new Map<string, ReturnType<typeof createHistoryIndex>>();
98
+ const receiptsDir = path.join(root, 'receipts');
99
+ const writes = new Map<string, Promise<void>>();
100
+ const appends = new Map<string, Promise<void>>();
101
+ /** Keys whose last write failed (records, receipts) or that lost any append (timelines). */
102
+ const failed = new Map<string, Error>();
103
+ /** Timelines whose tail this process has checked for a line a crash cut short. */
104
+ const repaired = new Set<string>();
105
+ const health: StoreHealth = { ok: true, failures: 0 };
106
+ let ready: Promise<void> | undefined;
107
+ const prepare = () => ready ??= Promise.all([
108
+ mkdir(sessionsDir, { recursive: true, mode: 0o700 }),
109
+ mkdir(timelineDir, { recursive: true, mode: 0o700 }),
110
+ mkdir(receiptsDir, { recursive: true, mode: 0o700 }),
111
+ ]).then(() => {}, error => { ready = undefined; throw error; });
112
+
113
+ async function writeAtomic(file: string, body: string) {
114
+ const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
115
+ try {
116
+ await writeFile(temporary, body, { mode: 0o600 });
117
+ await replaceFile(temporary, file);
118
+ } catch (error) {
119
+ await rm(temporary, { force: true }).catch(() => {});
120
+ throw error;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Serializes work per key so a later write never lands before an earlier one. The
126
+ * returned promise rejects when the write fails; the queue itself goes on.
127
+ */
128
+ function queue(map: Map<string, Promise<void>>, key: string, operation: string, work: () => Promise<void>, sticky = false, ids: { sessionId?: string; rootId?: string; clientMessageId?: string } = {}) {
129
+ const next = (map.get(key) ?? Promise.resolve()).then(prepare).then(work);
130
+ const failure = map === appends ? `timeline:${key}` : key;
131
+ const settled = next.then(
132
+ () => { if (!sticky) failed.delete(failure); },
133
+ error => {
134
+ failed.set(failure, error);
135
+ health.ok = false;
136
+ health.failures++;
137
+ health.lastError = { at: new Date().toISOString(), operation, message: error?.message ?? String(error) };
138
+ log.error(`${operation} failed`, { code: 'ALP_PERSISTENCE_WRITE_FAILED', operation, error, ...ids });
139
+ options.onWriteError?.(error);
140
+ });
141
+ map.set(key, settled);
142
+ void settled.then(() => { if (map.get(key) === settled) map.delete(key); });
143
+ return next;
144
+ }
145
+
146
+ /**
147
+ * A crash during an append can leave a timeline's last line cut short. Before this
148
+ * process appends to it, a cut line is removed, or completed when it parses whole,
149
+ * so the next line does not run into it.
150
+ */
151
+ async function repairTail(file: string) {
152
+ const handle = await open(file, 'r+').catch((error: any) => { if (error?.code === 'ENOENT') return undefined; throw error; });
153
+ if (!handle) return;
154
+ try {
155
+ const { size } = await handle.stat();
156
+ if (!size) return;
157
+ const last = Buffer.alloc(1);
158
+ await handle.read(last, 0, 1, size - 1);
159
+ if (last[0] === 0x0a) return;
160
+ let start = 0;
161
+ for (let end = size; end > 0 && !start; end -= TAIL_CHUNK) {
162
+ const from = Math.max(0, end - TAIL_CHUNK);
163
+ const chunk = Buffer.alloc(end - from);
164
+ await handle.read(chunk, 0, chunk.length, from);
165
+ const newline = chunk.lastIndexOf(0x0a);
166
+ if (newline >= 0) start = from + newline + 1;
167
+ }
168
+ const tail = Buffer.alloc(size - start);
169
+ await handle.read(tail, 0, tail.length, start);
170
+ let whole = false;
171
+ try { JSON.parse(tail.toString('utf8')); whole = true; } catch {}
172
+ if (whole) await handle.write('\n', size);
173
+ else await handle.truncate(start);
174
+ log.warn(`${whole ? 'completed' : 'removed'} a timeline line cut short in ${path.basename(file)} (${tail.length} bytes)`, { code: 'ALP_TIMELINE_REPAIRED', file: path.basename(file), bytes: tail.length });
175
+ } finally {
176
+ await handle.close();
177
+ }
178
+ }
179
+
180
+ /** Envelopes of a timeline text; lines without a cursor (written before cursors) count from the previous one. */
181
+ function parseTimeline(text: string, name: string): Envelope[] {
182
+ const envelopes: Envelope[] = [];
183
+ let cursor = 0;
184
+ let skipped = 0;
185
+ for (const line of text.split('\n')) {
186
+ if (!line) continue;
187
+ let envelope: Envelope;
188
+ try { envelope = JSON.parse(line); } catch { skipped++; continue; }
189
+ cursor = typeof envelope.cursor === 'number' && envelope.cursor > cursor ? envelope.cursor : cursor + 1;
190
+ envelopes.push({ ...envelope, cursor });
191
+ }
192
+ if (skipped) log.warn(`skipped ${skipped} unreadable timeline lines in ${name}`, { code: 'ALP_TIMELINE_UNREADABLE', file: name, skipped });
193
+ return envelopes;
194
+ }
195
+
196
+ const receiptFile = (key: string) => path.join(receiptsDir, `${fileName(key)}.json`);
197
+ const branchFile = (rootId: string, branchId: string) => path.join(timelineDir, `${fileName(rootId)}.branch-${fileName(branchId)}.jsonl`);
198
+
199
+ return {
200
+ /** The state directory this store keeps its files in. */
201
+ root,
202
+
203
+ put(record: SessionRecord) {
204
+ const file = path.join(sessionsDir, `${fileName(record.id)}.json`);
205
+ const body = JSON.stringify(record);
206
+ return queue(writes, record.id, `record ${record.id}`, () => writeAtomic(file, body), false, { sessionId: record.id, rootId: record.rootId });
207
+ },
208
+
209
+ async receipt(key: string): Promise<Receipt | UnreadableReceipt | undefined> {
210
+ await writes.get(`receipt:${key}`);
211
+ let text: string;
212
+ try {
213
+ text = await readFile(receiptFile(key), 'utf8');
214
+ } catch (error: any) {
215
+ if (error?.code === 'ENOENT') return undefined;
216
+ throw error;
217
+ }
218
+ try {
219
+ const receipt = JSON.parse(text);
220
+ if (receipt?.version === 1 && typeof receipt.fingerprint === 'string' && (receipt.state === 'pending' || receipt.state === 'completed')) return receipt;
221
+ } catch {}
222
+ return { version: 1, state: 'unreadable' };
223
+ },
224
+
225
+ putReceipt(key: string, receipt: Receipt) {
226
+ const body = JSON.stringify(receipt);
227
+ return queue(writes, `receipt:${key}`, `receipt ${receipt.clientMessageId}`, () => writeAtomic(receiptFile(key), body), false, { sessionId: receipt.sessionId, clientMessageId: receipt.clientMessageId });
228
+ },
229
+
230
+ removeReceipt(key: string) {
231
+ return queue(writes, `receipt:${key}`, `receipt removal ${key}`, () => rm(receiptFile(key), { force: true }));
232
+ },
233
+
234
+ /** Every readable receipt with its key and when its file was last written. */
235
+ async receipts(): Promise<Array<{ key: string; receipt: Receipt; writtenAt: number }>> {
236
+ await prepare();
237
+ const found: Array<{ key: string; receipt: Receipt; writtenAt: number }> = [];
238
+ for (const name of await readdir(receiptsDir)) {
239
+ if (!name.endsWith('.json')) continue;
240
+ const key = name.slice(0, -'.json'.length);
241
+ try {
242
+ const file = path.join(receiptsDir, name);
243
+ const receipt = JSON.parse(await readFile(file, 'utf8'));
244
+ if (receipt?.version === 1 && typeof receipt.sessionId === 'string') found.push({ key, receipt, writtenAt: (await stat(file)).mtimeMs });
245
+ } catch {}
246
+ }
247
+ return found;
248
+ },
249
+
250
+ /** When the newest of these records' files was written (a restore writes them anew); 0 when none is there. */
251
+ async writtenAt(ids: string[]) {
252
+ let newest = 0;
253
+ for (const id of ids) newest = Math.max(newest, await stat(path.join(sessionsDir, `${fileName(id)}.json`)).then(info => info.mtimeMs, () => 0));
254
+ return newest;
255
+ },
256
+
257
+ /**
258
+ * Deletes receipts not written for `maxAgeMs` and, with `temporaries` (only at start, when no
259
+ * write can be under way), temporary files a crash left behind.
260
+ */
261
+ async pruneReceipts(maxAgeMs: number, { temporaries = true } = {}) {
262
+ await prepare();
263
+ const now = Date.now();
264
+ for (const directory of [sessionsDir, receiptsDir]) {
265
+ for (const name of await readdir(directory)) {
266
+ const file = path.join(directory, name);
267
+ if (name.endsWith('.tmp')) { if (temporaries) await rm(file, { force: true }); continue; }
268
+ if (directory !== receiptsDir) continue;
269
+ const info = await stat(file).catch(() => undefined);
270
+ if (info && now - info.mtimeMs > maxAgeMs) await rm(file, { force: true });
271
+ }
272
+ }
273
+ },
274
+
275
+ /** Authoritative record after queued writes, including failed writes (which do not prove completion). */
276
+ async get(id: string): Promise<SessionRecord | undefined> {
277
+ await writes.get(id)?.catch(() => {});
278
+ try { return JSON.parse(await readFile(path.join(sessionsDir, `${fileName(id)}.json`), 'utf8')); }
279
+ catch (error: any) { if (error?.code === 'ENOENT') return undefined; throw error; }
280
+ },
281
+
282
+ async list(): Promise<SessionRecord[]> {
283
+ await prepare();
284
+ const records: SessionRecord[] = [];
285
+ for (const name of await readdir(sessionsDir)) {
286
+ if (!name.endsWith('.json')) continue;
287
+ try {
288
+ const record = JSON.parse(await readFile(path.join(sessionsDir, name), 'utf8'));
289
+ if (record?.version === 1 && typeof record.id === 'string') records.push(record);
290
+ else log.warn(`skipped invalid record ${name}`, { code: 'ALP_RECORD_UNREADABLE', file: name });
291
+ } catch {
292
+ log.warn(`skipped unreadable record ${name}`, { code: 'ALP_RECORD_UNREADABLE', file: name });
293
+ }
294
+ }
295
+ return records;
296
+ },
297
+
298
+ append(rootId: string, envelope: Envelope) {
299
+ const file = path.join(timelineDir, `${fileName(rootId)}.jsonl`);
300
+ const line = `${JSON.stringify(envelope)}\n`;
301
+ // A lost line leaves a gap in the timeline for good, so a timeline stays failed once it lost one.
302
+ return queue(appends, rootId, `timeline ${rootId}`, async () => {
303
+ if (!repaired.has(rootId)) { await repairTail(file); repaired.add(rootId); }
304
+ await appendFile(file, line, { mode: 0o600 });
305
+ }, true, { rootId });
306
+ },
307
+
308
+ async history(rootId: string, sessionId: string, options: { before?: string; limit?: number; maxBytes?: number } = {}) {
309
+ await prepare();
310
+ await appends.get(rootId);
311
+ let index = historyIndexes.get(rootId);
312
+ if (!index) { index = createHistoryIndex(path.join(timelineDir, `${fileName(rootId)}.jsonl`)); historyIndexes.set(rootId, index); }
313
+ return index.page(sessionId, options);
314
+ },
315
+
316
+ /**
317
+ * Rewinds a tree's timeline (§12.7), idempotently: the whole timeline moves to the branch file
318
+ * `<root>.branch-<id>.jsonl`, and the root's timeline becomes its lines before `cut`, the root's own
319
+ * session lifecycle lines after it (opened, updated, closed: not conversation), `marker`, and any line
320
+ * whose cursor follows the marker's, in cursor order. Runs in
321
+ * the tree's append queue, so no append lands in between. A crash leaves the old timeline, or the
322
+ * branch and the new one beside it (finished by the next call); the history index is rebuilt with a
323
+ * new generation, so every older history cursor is stale.
324
+ */
325
+ rewind(rootId: string, { cut, branchId, marker }: { cut: number; branchId: string; marker: Envelope }) {
326
+ const file = path.join(timelineDir, `${fileName(rootId)}.jsonl`);
327
+ const branch = branchFile(rootId, branchId);
328
+ const temporary = `${file}.rewind-${fileName(branchId)}.tmp`;
329
+ return queue(appends, rootId, `timeline rewind ${rootId}`, async () => {
330
+ const exists = (target: string) => stat(target).then(() => true, (error: any) => { if (error?.code === 'ENOENT') return false; throw error; });
331
+ if (!await exists(branch)) {
332
+ if (!repaired.has(rootId)) { await repairTail(file); repaired.add(rootId); }
333
+ const text = await readFile(file, 'utf8').catch((error: any) => { if (error?.code === 'ENOENT') return ''; throw error; });
334
+ const kept: Array<{ cursor: number; line: string }> = [];
335
+ const markerCursor = marker.cursor ?? Number.MAX_SAFE_INTEGER;
336
+ let cursor = 0;
337
+ for (const line of text.split('\n')) {
338
+ if (!line) continue;
339
+ let envelope: Envelope;
340
+ try { envelope = JSON.parse(line); } catch { continue; }
341
+ cursor = typeof envelope.cursor === 'number' && envelope.cursor > cursor ? envelope.cursor : cursor + 1;
342
+ const lifecycle = envelope.sessionId === rootId && ['session.opened', 'session.ready', 'session.updated', 'session.closed', 'session.failed'].includes(envelope.event?.type);
343
+ // Before the cut: the kept conversation. Between the cut and the marker: only the root's own
344
+ // lifecycle. After the marker (an event kept while the rewind waited for this queue): the new
345
+ // conversation's. A line kept past the cut carries its cursor, so cursors stay what clients saw.
346
+ if (cursor < cut) kept.push({ cursor, line });
347
+ else if (lifecycle || cursor > markerCursor) kept.push({ cursor, line: JSON.stringify({ ...envelope, cursor }) });
348
+ }
349
+ kept.push({ cursor: markerCursor, line: JSON.stringify(marker) });
350
+ kept.sort((a, b) => a.cursor - b.cursor);
351
+ await writeFile(temporary, `${kept.map(entry => entry.line).join('\n')}\n`, { mode: 0o600 });
352
+ if (await exists(file)) await rename(file, branch);
353
+ else await writeFile(branch, '', { mode: 0o600 });
354
+ }
355
+ if (await exists(temporary)) await rename(temporary, file);
356
+ await Promise.all(['.jsonl.idx', '.jsonl.history.json'].map(suffix => rm(path.join(timelineDir, `${fileName(rootId)}${suffix}`), { force: true })));
357
+ historyIndexes.delete(rootId);
358
+ repaired.add(rootId);
359
+ }, false, { rootId });
360
+ },
361
+
362
+ /** Writes a new tree's whole timeline at once (a fork's, §12.7); written again whole by a repeat. */
363
+ createTimeline(rootId: string, envelopes: Envelope[]) {
364
+ const file = path.join(timelineDir, `${fileName(rootId)}.jsonl`);
365
+ return queue(appends, rootId, `timeline ${rootId}`, async () => {
366
+ await writeAtomic(file, envelopes.map(envelope => `${JSON.stringify(envelope)}\n`).join(''));
367
+ await Promise.all(['.jsonl.idx', '.jsonl.history.json'].map(suffix => rm(path.join(timelineDir, `${fileName(rootId)}${suffix}`), { force: true })));
368
+ historyIndexes.delete(rootId);
369
+ repaired.add(rootId);
370
+ }, false, { rootId });
371
+ },
372
+
373
+ /** The timeline of a branch a rewind set aside; empty when it is not there. */
374
+ async branchTimeline(rootId: string, branchId: string): Promise<Envelope[]> {
375
+ await appends.get(rootId);
376
+ try { return parseTimeline(await readFile(branchFile(rootId, branchId), 'utf8'), path.basename(branchFile(rootId, branchId))); }
377
+ catch (error: any) { if (error?.code === 'ENOENT') return []; throw error; }
378
+ },
379
+
380
+ async timeline(rootId: string): Promise<Envelope[]> {
381
+ await appends.get(rootId);
382
+ const name = `${fileName(rootId)}.jsonl`;
383
+ try {
384
+ return parseTimeline(await readFile(path.join(timelineDir, name), 'utf8'), name);
385
+ } catch (error: any) {
386
+ if (error?.code === 'ENOENT') return [];
387
+ throw error;
388
+ }
389
+ },
390
+
391
+ /**
392
+ * Waits for the queued writes of these records and timelines, and names those that
393
+ * failed: a record whose last write failed, or a timeline that lost a line.
394
+ */
395
+ async drain({ records = [] as string[], timelines = [] as string[] }) {
396
+ await Promise.all([...records.map(id => writes.get(id)), ...timelines.map(id => appends.get(id))]);
397
+ return [...records.filter(id => failed.has(id)), ...timelines.filter(id => failed.has(`timeline:${id}`))];
398
+ },
399
+
400
+ /**
401
+ * Whether the state directory can be read and written right now: a small file is written,
402
+ * read back and removed. `StoreHealth` only says what failed since alpd started.
403
+ */
404
+ async probe(): Promise<{ ok: boolean; code?: string; message?: string }> {
405
+ const file = path.join(root, `.probe-${process.pid}-${randomBytes(3).toString('hex')}.tmp`);
406
+ const token = randomBytes(8).toString('hex');
407
+ let step: 'write' | 'read' = 'write';
408
+ try {
409
+ await prepare();
410
+ await writeFile(file, token, { mode: 0o600 });
411
+ step = 'read';
412
+ if (await readFile(file, 'utf8') !== token) throw new Error('what was written is not what was read back');
413
+ return { ok: true };
414
+ } catch (error: any) {
415
+ return { ok: false, code: step === 'write' ? 'ALP_STATE_NOT_WRITABLE' : 'ALP_STATE_NOT_READABLE', message: `${error?.code ? `${error.code}: ` : ''}${error?.message ?? error}` };
416
+ } finally {
417
+ await rm(file, { force: true }).catch(() => {});
418
+ }
419
+ },
420
+
421
+ /** How many records, receipts and timelines are failed now: a later successful write clears a record, a lost timeline line never clears. */
422
+ failing() {
423
+ return failed.size;
424
+ },
425
+
426
+ health(): StoreHealth {
427
+ return { ...health, ...(health.lastError ? { lastError: { ...health.lastError } } : {}) };
428
+ },
429
+
430
+ /** Removes a whole tree: its records, its timeline and the branches rewinds set aside. */
431
+ async remove(rootId: string, ids: string[]) {
432
+ await Promise.all([...ids.map(id => writes.get(id)), appends.get(rootId)]);
433
+ const branches = (await readdir(timelineDir).catch(() => [] as string[])).filter(name => name.startsWith(`${fileName(rootId)}.branch-`));
434
+ await Promise.all([
435
+ ...ids.map(id => rm(path.join(sessionsDir, `${fileName(id)}.json`), { force: true })),
436
+ ...['.jsonl', '.jsonl.idx', '.jsonl.history.json'].map(suffix => rm(path.join(timelineDir, `${fileName(rootId)}${suffix}`), { force: true })),
437
+ ...branches.map(name => rm(path.join(timelineDir, name), { force: true })),
438
+ ]);
439
+ for (const id of ids) failed.delete(id);
440
+ failed.delete(`timeline:${rootId}`);
441
+ historyIndexes.delete(rootId);
442
+ repaired.delete(rootId);
443
+ },
444
+
445
+ async flush() {
446
+ await Promise.all([...writes.values(), ...appends.values()]);
447
+ },
448
+ };
449
+ }
@@ -0,0 +1,74 @@
1
+ import headless from '@xterm/headless';
2
+ import { ERROR } from '@anhlp/alp-protocol';
3
+ import { RpcError } from './rpc-error.js';
4
+
5
+ // Exact xterm 6.0.0, also used by Paseo 0.12. No raw replay reconstruction: one parser from spawn.
6
+ // Bound both queued work and lifetime input (including OSC/combining payloads hidden from rows).
7
+ export const SCREEN_LIMITS = Object.freeze({ scrollback: 1000, pendingBytes: 1024 * 1024, pendingOperations: 256, inputBytes: 8 * 1024 * 1024, resultBytes: 1024 * 1024, retained: 16 });
8
+ export class TerminalScreen {
9
+ #term: InstanceType<typeof headless.Terminal> | undefined;
10
+ #pending = 0;
11
+ #input = 0;
12
+ #operations = 0;
13
+ #waiters = new Set<() => void>();
14
+ constructor(cols: number, rows: number) {
15
+ this.#term = new headless.Terminal({ cols, rows, scrollback: SCREEN_LIMITS.scrollback, allowProposedApi: true, logLevel: 'off' });
16
+ }
17
+ get available() { return this.#term !== undefined; }
18
+ #unavailable() { return new RpcError(ERROR.unavailable, 'Terminal capture is unavailable: its bounded screen was released or exceeded its resource limit', { reason: 'terminal_capture_unavailable' }); }
19
+ #queue(term: InstanceType<typeof headless.Terminal>, data: string, callback: () => void) {
20
+ if (this.#operations >= SCREEN_LIMITS.pendingOperations) { this.dispose(); return; }
21
+ this.#operations++;
22
+ try {
23
+ term.write(data, () => { this.#operations--; callback(); });
24
+ } catch { this.#operations--; this.dispose(); }
25
+ }
26
+ write(data: string) {
27
+ const term = this.#term;
28
+ if (!term) return;
29
+ const bytes = Buffer.byteLength(data);
30
+ this.#input += bytes;
31
+ if (this.#input > SCREEN_LIMITS.inputBytes || this.#pending + bytes > SCREEN_LIMITS.pendingBytes) { this.dispose(); return; }
32
+ this.#pending += bytes;
33
+ this.#queue(term, data, () => { this.#pending -= bytes; });
34
+ }
35
+ resize(cols: number, rows: number) {
36
+ const term = this.#term;
37
+ // Keep resize between the old output and output caused by the new PTY size.
38
+ if (term) this.#queue(term, '', () => { if (this.#term === term) term.resize(cols, rows); });
39
+ }
40
+ capture(options: { start?: number; end?: number; stripAnsi?: boolean } = {}): Promise<{ lines: string[]; totalLines: number }> {
41
+ const term = this.#term;
42
+ if (!term) return Promise.reject(this.#unavailable());
43
+ return new Promise((resolve, reject) => {
44
+ const released = () => reject(this.#unavailable());
45
+ this.#waiters.add(released);
46
+ // The callback is a parser barrier, not a delay or a ring-buffer approximation.
47
+ this.#queue(term, '', () => {
48
+ this.#waiters.delete(released);
49
+ if (this.#term !== term) { reject(this.#unavailable()); return; }
50
+ const buffer = term.buffer.active;
51
+ const totalLines = buffer.length;
52
+ const index = (value: number | undefined, fallback: number) => value === undefined ? fallback : Math.max(0, Math.min(totalLines - 1, value < 0 ? totalLines + value : value));
53
+ const start = index(options.start, 0);
54
+ const end = index(options.end, totalLines - 1);
55
+ const lines: string[] = [];
56
+ let bytes = 0;
57
+ for (let i = start; i <= end; i++) {
58
+ // Cell text, like Paseo: styling escapes are not regenerated when stripAnsi=false.
59
+ const line = buffer.getLine(i)?.translateToString(true).trimEnd() ?? '';
60
+ bytes += Buffer.byteLength(JSON.stringify(line)) + 1;
61
+ if (bytes > SCREEN_LIMITS.resultBytes - 128) { reject(new RpcError(ERROR.unavailable, 'Terminal capture exceeds the response limit; select a smaller line range', { reason: 'terminal_capture_too_large' })); return; }
62
+ lines.push(line);
63
+ }
64
+ resolve({ lines, totalLines });
65
+ });
66
+ });
67
+ }
68
+ dispose() {
69
+ this.#term?.dispose();
70
+ this.#term = undefined;
71
+ for (const waiter of this.#waiters) waiter();
72
+ this.#waiters.clear();
73
+ }
74
+ }