@anhlp/alp-daemon 0.0.0-beta.1

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.
package/src/server.ts ADDED
@@ -0,0 +1,1159 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { appendFile, chmod, mkdir, readFile, unlink, lstat, rename } from 'node:fs/promises';
3
+ import net from 'node:net';
4
+ import { assertPrivateDirectory, assertPrivateSocket } from '@anhlp/alp-client/index';
5
+ import path from 'node:path';
6
+ import { createLogger } from '@anhlp/alp-core/log';
7
+ import { AlpRpcError, CAPABILITY, MAX_FRAME, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, encodeFrame } from '@anhlp/alp-protocol';
8
+ import { validateParams } from '@anhlp/alp-protocol/contract';
9
+ export { ERROR } from '@anhlp/alp-protocol';
10
+ import { DEFAULT_MODEL, models, modes, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
11
+ import type { Receipt, SessionRecord, SessionStatus, Store, UnreadableReceipt } from './store.js';
12
+ import type { SessionSummary } from '@anhlp/alp-protocol/session';
13
+ import { RpcError } from './rpc-error.js';
14
+ import { createOperations, type OperationsOptions } from './operations.js';
15
+
16
+ /**
17
+ * alpd's JSON-RPC surface over one shared runtime (plans/reference/ALPD.md §3, §6, §14).
18
+ * Clients attach to root sessions to receive the events of the whole tree. A root
19
+ * with no attached client is closed as soon as it is idle, so work started by a
20
+ * viewer finishes even after the viewer goes away. With a store, every session is
21
+ * recorded and every tree's events are kept, so a closed root can be resumed later.
22
+ */
23
+
24
+
25
+
26
+ const log = createLogger({ component: 'alpd.ipc' });
27
+ const recoveryLog = createLogger({ component: 'alpd.recovery' });
28
+
29
+
30
+ /** A request id v1 accepts: a string of at most 128 characters or a safe integer (docs/protocol/alp-json-rpc-v1.md §3). */
31
+ function validId(id: unknown): id is string | number {
32
+ if (typeof id !== 'string') return Number.isSafeInteger(id);
33
+ let length = 0;
34
+ for (const _point of id) if (++length > 128) return false;
35
+ return true;
36
+ }
37
+
38
+ /** The bytes a frame takes on a newline-delimited stream, its newline included. */
39
+ const frameBytes = (message: unknown) => Buffer.byteLength(encodeFrame(message), 'utf8');
40
+
41
+ const invalidParams = (issues: Array<{ path: string; message: string }>) =>
42
+ new RpcError(RPC_ERROR.invalidParams, `Invalid params: ${issues.map(issue => `${issue.path || 'params'} ${issue.message}`).join('; ')}`, { reason: 'invalid_params', issues });
43
+
44
+ /**
45
+ * Crash points for the crash-recovery tests (ALPD §66): with ALP_TEST_CRASH_AT naming one,
46
+ * alpd kills itself there as a crash would. Unset, they do nothing.
47
+ */
48
+ function crashPoint(name: string) {
49
+ if (process.env.ALP_TEST_CRASH_AT !== name) return;
50
+ createLogger({ component: 'alpd' }).error(`ALP_TEST_CRASH_AT=${name}: killing alpd`, { code: 'ALP_TEST_CRASH' });
51
+ process.kill(process.pid, 'SIGKILL');
52
+ }
53
+
54
+ const persistenceFailed = (what: string, error: unknown) =>
55
+ new RpcError(ERROR.failed, `alpd could not record ${what}: ${error instanceof Error ? error.message : String(error)}`, { reason: 'persistence_failed' });
56
+
57
+ /** A stable hash of JSON data, independent of key order (as Paseo's receipts). */
58
+ function digest(value: unknown) {
59
+ return createHash('sha256').update(JSON.stringify(value, (_key, candidate) =>
60
+ candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)
61
+ ? Object.fromEntries(Object.entries(candidate).sort(([a], [b]) => a.localeCompare(b)))
62
+ : candidate)).digest('hex');
63
+ }
64
+
65
+ type Connection = {
66
+ socket?: net.Socket;
67
+ helloed: boolean;
68
+ roots: Set<string>;
69
+ send(message: unknown): void;
70
+ nextId: number;
71
+ pending: Map<number, { resolve(value: unknown): void; reject(error: Error): void; timer: NodeJS.Timeout; caller: Connection }>;
72
+ };
73
+
74
+ /** Retained events per live tree, for attach and replay. */
75
+ const TREE_LOG_LIMIT = 20_000;
76
+ const SESSION_ID = /^[\w.:-]{1,128}$/;
77
+ const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
78
+ const RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
79
+ /** How often a running alpd applies retention, besides at start (ALPD §68). */
80
+ const RETENTION_SWEEP_MS = 6 * 60 * 60 * 1000;
81
+ const LIVE: SessionStatus[] = ['initializing', 'idle', 'running'];
82
+
83
+ /** What clients need from a daemon connection; AlpClient implements it over the socket. */
84
+ import type { DaemonConnection } from '@anhlp/alp-protocol/connection';
85
+ export type { DaemonConnection } from '@anhlp/alp-protocol/connection';
86
+
87
+ export type DaemonServer = {
88
+ listen(): Promise<void>;
89
+ /** An in-process connection that delivers events synchronously, for embedding. */
90
+ local(): DaemonConnection;
91
+ /**
92
+ * A connection over another transport, such as the web app's WebSocket (ALPD §61):
93
+ * it says daemon.hello first, as a socket client does, and gets JSON-RPC messages back through `send`.
94
+ */
95
+ accept(send: (message: unknown) => void): { receive(message: unknown): void; close(): void };
96
+ /** Adds a method that lives outside the runtime, such as the web app's pairing link (ALPD §64). */
97
+ extend(method: string, handler: (params: any) => Promise<unknown> | unknown): void;
98
+ close(): Promise<void>;
99
+ };
100
+
101
+ /** A session as clients list it: its last snapshot plus lifecycle (ALPD §18). The protocol owns the
102
+ * shape so every viewer agrees; re-exported here to keep `@anhlp/alp-daemon/server`'s API. */
103
+ export type { SessionSummary };
104
+
105
+ export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates }: {
106
+ runtime: AlpRuntime;
107
+ socketPath: string;
108
+ version: string;
109
+ onShutdown?: () => void;
110
+ /** Durable records and timelines; without it sessions live only in memory. */
111
+ store?: Store;
112
+ /** Where crash reconciliation reports assignments it ends, as the runtime does. */
113
+ runLogDir?: string;
114
+ /** How the previous alpd ended, for daemon.status. */
115
+ previousExit?: { kind: 'clean' | 'crash'; at?: string };
116
+ /** How often retention runs while alpd runs (ALPD §68); tests shorten it. */
117
+ retentionSweepMs?: number;
118
+ /** The daemon user's ALP_HOME, for the library, team and settings methods; without it alpd does not serve them. */
119
+ home?: OperationsOptions['home'];
120
+ /** ALP's built-in agents and teams, for the library and team methods. */
121
+ templates?: OperationsOptions['templates'];
122
+ }): DaemonServer {
123
+ const connections = new Set<Connection>();
124
+ /** Root of every live session. */
125
+ const rootOf = new Map<string, string>();
126
+ const attached = new Map<string, Set<Connection>>();
127
+ const logs = new Map<string, Envelope[]>();
128
+ const records = new Map<string, SessionRecord & { activeTurnId?: string }>();
129
+ /** Prompt deliveries in flight, so a repeated clientMessageId waits for the first. */
130
+ const delivering = new Map<string, Promise<object>>();
131
+ /** Completed deliveries whose receipt could not be written; this process still answers them. */
132
+ const unsaved = new Map<string, Receipt>();
133
+ /** The last timeline cursor of each tree (ALPD §66). */
134
+ const cursors = new Map<string, number>();
135
+ let closing = false;
136
+ let socketIdentity: { dev: number; ino: number } | undefined;
137
+ /** Roots alpd reopens after a restart; they stay open until their recovery has started. */
138
+ const recovering = new Map<string, Promise<void>>();
139
+ const startedAt = new Date().toISOString();
140
+ const restored = store ? restore() : Promise.resolve();
141
+
142
+ const deliver = (connection: Connection, envelope: Envelope) => connection.send({ jsonrpc: '2.0', method: 'event', params: envelope });
143
+
144
+ /** Records a change; the write is queued, and a failure is logged and counted in daemon.status. */
145
+ function save(record: SessionRecord & { activeTurnId?: string }, changes: Partial<SessionRecord & { activeTurnId?: string }> = {}) {
146
+ Object.assign(record, changes, { updatedAt: new Date().toISOString() });
147
+ records.set(record.id, record);
148
+ return store?.put(record).catch(() => {}) ?? Promise.resolve();
149
+ }
150
+
151
+ /** Gives an envelope of a tree its next cursor and queues it for the tree's timeline. */
152
+ function keep(root: string, envelope: Envelope): Envelope {
153
+ const cursor = (cursors.get(root) ?? 0) + 1;
154
+ cursors.set(root, cursor);
155
+ const kept = { ...envelope, cursor };
156
+ void store?.append(root, kept).catch(() => {});
157
+ return kept;
158
+ }
159
+
160
+ /** Continues a tree's cursors after what its stored timeline already holds. */
161
+ function seen(root: string, log: Envelope[]) {
162
+ const last = log.at(-1)?.cursor ?? 0;
163
+ if (last > (cursors.get(root) ?? 0)) cursors.set(root, last);
164
+ }
165
+
166
+ /** Lifecycle bookkeeping for one event; returns true when the record changed. */
167
+ function track(sessionId: string, root: string, event: AlpEvent) {
168
+ const now = new Date().toISOString();
169
+ let record = records.get(sessionId);
170
+ if (event.type === 'session.opened') {
171
+ record ??= { version: 1, id: sessionId, rootId: root, status: 'initializing', createdAt: now, updatedAt: now };
172
+ save(record, { rootId: root, session: event.session, status: 'idle', lastError: undefined, activeTurnId: undefined });
173
+ return;
174
+ }
175
+ if (!record) return;
176
+ if (event.type === 'session.updated') save(record, { session: { ...record.session, ...event.session, ...(event.session.parked ? {} : { parked: undefined }) } });
177
+ // Work on an archived session brings it back.
178
+ else if (event.type === 'turn.started') save(record, { status: 'running', activeTurnId: event.turnId, archived: undefined });
179
+ else if (event.type === 'turn.ended') save(record, { status: 'idle', activeTurnId: undefined, ...(event.state === 'failed' ? { lastError: { message: event.error?.message ?? 'Turn failed' } } : {}) });
180
+ else if (event.type === 'session.failed') save(record, { status: 'error', lastError: event.error });
181
+ else if (event.type === 'session.closed') save(record, { status: record.status === 'error' ? 'error' : 'closed', activeTurnId: undefined });
182
+ else if (event.type === 'item' && sessionId === root && !record.title && event.item.kind === 'user_message' && !event.item.clientMessageId?.startsWith('alp-')) {
183
+ save(record, { title: event.item.text.replace(/\s+/g, ' ').trim().slice(0, 80) });
184
+ }
185
+ }
186
+
187
+ runtime.onEvent(original => {
188
+ // While alpd stops, records keep what was running, so the next alpd continues it (ALPD §31).
189
+ if (closing) return;
190
+ let envelope = original;
191
+ const { sessionId, event } = envelope;
192
+ if (event.type === 'session.opened') {
193
+ const parent = event.session.parentId;
194
+ rootOf.set(sessionId, parent ? rootOf.get(parent) ?? parent : sessionId);
195
+ }
196
+ const root = rootOf.get(sessionId) ?? sessionId;
197
+ if (rootOf.has(sessionId)) {
198
+ envelope = keep(root, envelope);
199
+ const log = logs.get(root) ?? [];
200
+ log.push(envelope);
201
+ if (log.length > TREE_LOG_LIMIT) log.splice(0, log.length - TREE_LOG_LIMIT);
202
+ logs.set(root, log);
203
+ track(sessionId, root, event);
204
+ }
205
+ for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
206
+ if (event.type === 'session.closed' && sessionId === root) {
207
+ setImmediate(() => forget(root));
208
+ } else {
209
+ setImmediate(() => void reap(root));
210
+ }
211
+ });
212
+
213
+ /**
214
+ * Loads records, settles sessions a crash or a stop left working, and prunes expired
215
+ * trees. Trees with assignments the runtime can continue, or whose root was working,
216
+ * are reopened afterwards (ALPD §31).
217
+ */
218
+ async function restore() {
219
+ await store!.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: true });
220
+ const loaded = await store!.list();
221
+ await reconcileReceipts(loaded);
222
+ const now = Date.now();
223
+ const ended = { code: 'daemon_restarted', message: 'alpd stopped while this session was working' };
224
+ const epoch = `restart-${startedAt}`;
225
+ const continuing = new Set(runtime.recoverable().map(entry => entry.assignmentId));
226
+ const reopen: Array<{ record: SessionRecord; working: boolean }> = [];
227
+ const byRoot = trees(loaded);
228
+ const removed = await expire(byRoot, now);
229
+ for (const [root, tree] of byRoot) {
230
+ const head = tree.find(record => record.id === root);
231
+ if (removed.has(root)) continue;
232
+ if (head && resumable(head) && (head.status === 'running' || tree.some(record => continuing.has(record.id)))) reopen.push({ record: head, working: head.status === 'running' });
233
+ if (tree.some(record => LIVE.includes(record.status))) seen(root, await store!.timeline(root));
234
+ for (const record of tree as Array<SessionRecord & { activeTurnId?: string }>) {
235
+ records.set(record.id, record);
236
+ if (!LIVE.includes(record.status)) continue;
237
+ const envelope = (event: AlpEvent): Envelope => ({ sessionId: record.id, epoch, seq: 0, ts: new Date().toISOString(), event });
238
+ // The turn a crash or a stop cut off is reported interrupted, never continued as if nothing happened.
239
+ if (record.activeTurnId) keep(root, envelope({ type: 'turn.ended', turnId: record.activeTurnId, state: 'failed', error: { message: ended.message, code: ended.code } }));
240
+ if (record.id === root) {
241
+ save(record, record.status === 'idle' ? { status: 'closed', activeTurnId: undefined } : { status: 'error', lastError: ended, activeTurnId: undefined });
242
+ } else if (continuing.has(record.id) && reopen.some(entry => entry.record.id === root)) {
243
+ // The runtime reopens it under the same id; until then it is closed.
244
+ save(record, { status: 'closed', activeTurnId: undefined });
245
+ } else {
246
+ // Children never survive their runtime; their requester learns the assignment failed.
247
+ keep(root, envelope({ type: 'session.closed' }));
248
+ save(record, { status: 'closed', lastError: ended, activeTurnId: undefined });
249
+ if (runLogDir && !continuing.has(record.id)) {
250
+ const line = JSON.stringify({ ts: new Date().toISOString(), rootSessionId: root, event: 'assignment.finished', assignmentId: record.id, agent: record.session?.agent, sessionId: record.id, status: 'failed', error: ended.message, reconciled: true }) + '\n';
251
+ await mkdir(runLogDir, { recursive: true }).then(() => appendFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`), line)).catch(() => {});
252
+ }
253
+ }
254
+ }
255
+ }
256
+ // Assignments whose tree cannot be reopened end now, and their tasks go back to open.
257
+ const reopened = new Set(reopen.map(entry => entry.record.id));
258
+ for (const rootId of new Set(runtime.recoverable().map(entry => entry.rootId))) {
259
+ if (!reopened.has(rootId)) await runtime.abandon(rootId, 'its root session cannot be reopened').catch(() => {});
260
+ }
261
+ for (const { record, working } of reopen) recovering.set(record.id, recoverTree(record, working));
262
+ }
263
+
264
+ function trees(list: Iterable<SessionRecord>) {
265
+ const byRoot = new Map<string, SessionRecord[]>();
266
+ for (const record of list) byRoot.set(record.rootId, [...(byRoot.get(record.rootId) ?? []), record]);
267
+ return byRoot;
268
+ }
269
+
270
+ /**
271
+ * Retention (ALPD §68): deletes trees nobody needs any more, with their records, timeline and
272
+ * run log. A tree stays while any of its sessions is live or was written in the last 30 days,
273
+ * while a receipt of one of its sessions is still honoured (7 days from its last write, so a
274
+ * retried prompt is answered from it), while the runtime can continue one of its assignments,
275
+ * and while it is open, attached or being recovered. Timelines are never trimmed while their
276
+ * tree stays, so every cursor a client holds for it replays.
277
+ */
278
+ async function expire(byRoot: Map<string, SessionRecord[]>, now = Date.now()) {
279
+ const removed = new Set<string>();
280
+ const receiptWritten = new Map<string, number>();
281
+ // Receipts age as the store prunes them: by when their file was written, and by what they say.
282
+ for (const { receipt, writtenAt } of await store!.receipts()) {
283
+ const at = Date.parse(receipt.updatedAt);
284
+ receiptWritten.set(receipt.sessionId, Math.max(receiptWritten.get(receipt.sessionId) ?? 0, Number.isNaN(at) ? now : at, writtenAt));
285
+ }
286
+ const continuing = new Set(runtime.recoverable().map(entry => entry.rootId));
287
+ for (const [root, tree] of byRoot) {
288
+ if (!tree.some(record => record.id === root)) continue;
289
+ if (tree.some(record => LIVE.includes(record.status))) continue;
290
+ if (now - Math.max(...tree.map(record => Date.parse(record.updatedAt) || now)) <= RETENTION_MS) continue;
291
+ if (tree.some(record => now - (receiptWritten.get(record.id) ?? 0) <= RECEIPT_RETENTION_MS)) continue;
292
+ if (continuing.has(root) || rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) continue;
293
+ const ids = tree.map(record => record.id);
294
+ // A tree restored from a backup counts from its restore: its files were written then.
295
+ if (now - await store!.writtenAt(ids) <= RETENTION_MS) continue;
296
+ if (rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) continue;
297
+ // Forgotten before the files go, so a resume arriving meanwhile finds nothing to reopen.
298
+ for (const id of ids) records.delete(id);
299
+ cursors.delete(root);
300
+ await store!.remove(root, ids);
301
+ if (runLogDir) await unlink(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`)).catch(() => {});
302
+ removed.add(root);
303
+ }
304
+ if (removed.size) recoveryLog.info(`retention removed ${removed.size} session tree${removed.size > 1 ? 's' : ''} unused for ${RETENTION_MS / 86_400_000} days`, { code: 'ALP_RETENTION_REMOVED', trees: removed.size });
305
+ return removed;
306
+ }
307
+
308
+ /** Retention while alpd runs: receipts past their window, then expired trees; temporary files stay, as writes may be under way. */
309
+ async function sweep() {
310
+ if (closing || !store) return;
311
+ try {
312
+ await restored;
313
+ await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
314
+ await expire(trees(records.values()));
315
+ } catch (error) {
316
+ recoveryLog.warn('retention sweep failed', { code: 'ALP_RETENTION_FAILED', error });
317
+ }
318
+ }
319
+ const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : undefined;
320
+ sweeper?.unref();
321
+
322
+ /**
323
+ * Completes receipts a crash left pending when the tree's timeline shows how the runtime
324
+ * answered; the rest stay pending, so their prompt answers outcome_unknown and is never
325
+ * sent again by itself.
326
+ */
327
+ async function reconcileReceipts(loaded: SessionRecord[]) {
328
+ const rootOfRecord = new Map(loaded.map(record => [record.id, record.rootId]));
329
+ const timelines = new Map<string, Envelope[]>();
330
+ for (const { key, receipt } of await store!.receipts()) {
331
+ if (receipt.state !== 'pending') continue;
332
+ const root = rootOfRecord.get(receipt.sessionId);
333
+ if (!root) continue;
334
+ if (!timelines.has(root)) timelines.set(root, await store!.timeline(root).catch(() => []));
335
+ const answer = timelines.get(root)!.find(({ sessionId, event }) => sessionId === receipt.sessionId
336
+ && (event.type === 'prompt.accepted' || event.type === 'prompt.failed') && event.clientMessageId === receipt.clientMessageId);
337
+ if (!answer) continue;
338
+ const event = answer.event as Extract<AlpEvent, { type: 'prompt.accepted' | 'prompt.failed' }>;
339
+ const outcome = event.type === 'prompt.accepted' ? 'accepted' : event.error.code === 'outcome_unknown' ? 'unknown' : 'failed';
340
+ await store!.putReceipt(key, { ...receipt, state: 'completed', outcome, ...(event.type === 'prompt.failed' ? { error: event.error } : {}), reconciled: true, updatedAt: new Date().toISOString() })
341
+ .catch(() => {});
342
+ }
343
+ }
344
+
345
+ function resumable(record: SessionRecord) {
346
+ return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
347
+ }
348
+
349
+ /** Reopens a root nobody watches yet and continues what it and its assignments were doing. */
350
+ async function recoverTree(record: SessionRecord, working: boolean) {
351
+ const session = record.session!;
352
+ try {
353
+ const stored = await treeLog(record.id);
354
+ seen(record.id, stored);
355
+ logs.set(record.id, [...stored]);
356
+ await runtime.open(record.id, {
357
+ ...record.spec!,
358
+ persist: true,
359
+ restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
360
+ }, { history: 'skip', delegation: record.delegation ?? true });
361
+ const outcomes = await runtime.recover(record.id, { continueRoot: working });
362
+ recoveryLog.info(`recovered ${record.id}: ${outcomes.map(outcome => `${outcome.agent} ${outcome.outcome}`).join(', ') || 'root'}`, { event: 'recovered', sessionId: record.id, rootId: record.rootId });
363
+ } catch (error: any) {
364
+ recoveryLog.error(`could not recover ${record.id}`, { code: 'ALP_RECOVERY_FAILED', sessionId: record.id, rootId: record.rootId, error });
365
+ await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {});
366
+ } finally {
367
+ recovering.delete(record.id);
368
+ setImmediate(() => void reap(record.id));
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Sends a prompt at most once per (session, clientMessageId), as Paseo's MessageReceipts
374
+ * (ALPD §15, §66). The answer comes only after the receipt holds the runtime's outcome
375
+ * and the tree's timeline holds its events. A repeat with the same content answers what
376
+ * the first delivery did, with other content a conflict; a receipt left pending by a
377
+ * crash, or a delivery the provider may or may not have received, is outcome_unknown.
378
+ */
379
+ function deliverOnce(sessionId: string, clientMessageId: string, fingerprint: string, send: () => Promise<void>) {
380
+ const key = digest(['prompt', sessionId, clientMessageId]);
381
+ const unknown = () => new RpcError(ERROR.conflict, `alpd cannot tell whether message ${clientMessageId} reached the agent; check the session, then send it again with a new id`, { reason: 'outcome_unknown' });
382
+ const answer = (receipt: Receipt, extra: object = {}) => ({ outcome: receipt.outcome ?? 'accepted', ...(receipt.error ? { error: receipt.error } : {}), ...extra });
383
+ const attempt = async () => {
384
+ let existing: Receipt | UnreadableReceipt | undefined = unsaved.get(key);
385
+ if (!existing) {
386
+ try { existing = await store!.receipt(key); }
387
+ catch (error) { throw persistenceFailed(`message ${clientMessageId}`, error); }
388
+ }
389
+ if (existing) {
390
+ if (existing.state === 'unreadable') throw unknown();
391
+ if (existing.fingerprint !== fingerprint) throw new RpcError(ERROR.conflict, `Message ${clientMessageId} was already sent with different content`, { reason: 'key_conflict' });
392
+ if (existing.state === 'pending' || existing.outcome === 'unknown') throw unknown();
393
+ return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
394
+ }
395
+ const receipt = (state: Receipt['state'], changes: Partial<Receipt> = {}): Receipt => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: new Date().toISOString() });
396
+ live(sessionId);
397
+ crashPoint('prompt.before-receipt');
398
+ // Nothing is sent unless the pending receipt is on disk: a crash from here on answers outcome_unknown.
399
+ try { await store!.putReceipt(key, receipt('pending')); }
400
+ catch (error) { throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error); }
401
+ crashPoint('prompt.after-receipt');
402
+ // The runtime reports how the provider answered as an event, before prompt() resolves.
403
+ let reply: { outcome: 'accepted' | 'failed' | 'unknown'; error?: { message: string; code?: string } } = { outcome: 'accepted' };
404
+ const stop = runtime.onEvent(({ sessionId: from, event }) => {
405
+ if (from !== sessionId) return;
406
+ if (event.type === 'prompt.accepted' && event.clientMessageId === clientMessageId) reply = { outcome: 'accepted' };
407
+ if (event.type === 'prompt.failed' && event.clientMessageId === clientMessageId) reply = { outcome: event.error.code === 'outcome_unknown' ? 'unknown' : 'failed', error: event.error };
408
+ });
409
+ try {
410
+ await send();
411
+ } catch (error) {
412
+ // The runtime refused it before reaching the provider (the session closed meanwhile): not sent.
413
+ await store!.removeReceipt(key).catch(() => {});
414
+ throw error;
415
+ } finally {
416
+ stop();
417
+ }
418
+ const root = rootOf.get(sessionId) ?? sessionId;
419
+ const lost = await store!.drain({ records: [sessionId], timelines: [root] });
420
+ crashPoint('prompt.after-send');
421
+ const done = receipt('completed', reply);
422
+ let durable = lost.length === 0;
423
+ try { await store!.putReceipt(key, done); }
424
+ catch {
425
+ unsaved.set(key, done);
426
+ durable = false;
427
+ }
428
+ crashPoint('prompt.after-completed');
429
+ if (reply.outcome === 'unknown') throw unknown();
430
+ return answer(done, { durable });
431
+ };
432
+ const previous = delivering.get(key) ?? Promise.resolve();
433
+ const result = previous.catch(() => {}).then(attempt);
434
+ delivering.set(key, result);
435
+ void result.finally(() => { if (delivering.get(key) === result) delivering.delete(key); }).catch(() => {});
436
+ return result;
437
+ }
438
+
439
+ /**
440
+ * Waits for an opened root's record and timeline (its native thread) to be written, so a
441
+ * crash after the answer can still resume it (ALPD §66); `durable: false` when they were not.
442
+ */
443
+ async function persisted(root: string) {
444
+ if (!store) return {};
445
+ return { durable: (await store.drain({ records: [root], timelines: [root] })).length === 0 };
446
+ }
447
+
448
+ function forget(root: string) {
449
+ if (runtime.snapshot(root)) return;
450
+ for (const [id, candidate] of rootOf) if (candidate === root) rootOf.delete(id);
451
+ logs.delete(root);
452
+ }
453
+
454
+ /** Closes an idle root that no client watches. */
455
+ async function reap(root: string) {
456
+ if (closing || attached.get(root)?.size || recovering.has(root)) return false;
457
+ const session = runtime.snapshot(root);
458
+ if (!session || session.busy) return false;
459
+ await runtime.close(root).catch(() => {});
460
+ return true;
461
+ }
462
+
463
+ function attach(connection: Connection, root: string) {
464
+ const set = attached.get(root) ?? new Set();
465
+ set.add(connection);
466
+ attached.set(root, set);
467
+ connection.roots.add(root);
468
+ }
469
+
470
+ function detach(connection: Connection, root: string) {
471
+ attached.get(root)?.delete(connection);
472
+ if (!attached.get(root)?.size) attached.delete(root);
473
+ connection.roots.delete(root);
474
+ }
475
+
476
+ function summary(id: string): SessionSummary | undefined {
477
+ const record = records.get(id);
478
+ const live = runtime.snapshot(id);
479
+ const session = live ?? record?.session;
480
+ if (!session) return undefined;
481
+ const status: SessionStatus = live ? (live.activeTurnId ? 'running' : 'idle') : record?.status === 'error' ? 'error' : 'closed';
482
+ return { ...session, ...(live ? {} : { busy: false, activeTurnId: undefined }), status, title: record?.title, ...(record?.archived ? { archived: true } : {}), lastError: record?.lastError, createdAt: record?.createdAt, updatedAt: record?.updatedAt };
483
+ }
484
+
485
+ /** The record of a root the user acts on. */
486
+ function rootRecord(sessionId: string) {
487
+ if (typeof sessionId !== 'string') throw new RpcError(-32602, 'sessionId is required');
488
+ const record = records.get(sessionId);
489
+ if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
490
+ if (record.rootId !== record.id) throw new RpcError(-32602, 'Only a root session can be renamed or archived');
491
+ return record;
492
+ }
493
+
494
+ function known(sessionId: string) {
495
+ const found = summary(sessionId);
496
+ if (!found) throw new RpcError(ERROR.notFound, 'Session is not open');
497
+ return found;
498
+ }
499
+
500
+ function live(sessionId: string) {
501
+ const session = runtime.snapshot(sessionId);
502
+ if (!session) throw new RpcError(ERROR.notFound, 'Session is not open');
503
+ return session;
504
+ }
505
+
506
+ async function treeLog(root: string) {
507
+ return logs.get(root) ?? await store?.timeline(root) ?? [];
508
+ }
509
+
510
+ /**
511
+ * Delivers a tree's history: the root's latest items, then the children's events in their
512
+ * original order, so a grandchild opens while its parent is still open.
513
+ */
514
+ function replayHistory(connection: Connection, root: string, log: Envelope[], { children = true } = {}) {
515
+ const items = new Map<string, Envelope>();
516
+ for (const envelope of log) {
517
+ if (envelope.sessionId === root && envelope.event.type === 'item') items.set(envelope.event.item.id, envelope);
518
+ }
519
+ for (const item of items.values()) deliver(connection, item);
520
+ if (children) for (const envelope of log) if (envelope.sessionId !== root && current(envelope)) deliver(connection, envelope);
521
+ }
522
+
523
+ /** Questions in a log are history; announceQuestions delivers the ones still waiting. */
524
+ function current(envelope: Envelope) {
525
+ return envelope.event.type !== 'question' && envelope.event.type !== 'question.resolved';
526
+ }
527
+
528
+ function announceQuestions(connection: Connection, root: string) {
529
+ for (const question of runtime.questions()) {
530
+ if (question.rootId !== root) continue;
531
+ deliver(connection, { sessionId: question.sessionId, epoch: `announce-${startedAt}`, seq: 0, ts: new Date().toISOString(), event: { type: 'question', question } });
532
+ }
533
+ }
534
+
535
+ /**
536
+ * Re-announces a live tree to a client that reopens its root: the root as it is now,
537
+ * its timeline when asked, then live children and running turns.
538
+ */
539
+ function announce(connection: Connection, root: string, history: 'replay' | 'skip') {
540
+ const log = logs.get(root) ?? [];
541
+ const sessions = runtime.list().filter(session => (rootOf.get(session.id) ?? session.id) === root);
542
+ for (const session of sessions) {
543
+ const opened = log.find(envelope => envelope.sessionId === session.id && envelope.event.type === 'session.opened');
544
+ if (!opened || opened.event.type !== 'session.opened') continue;
545
+ const seq = Math.max(...log.filter(envelope => envelope.sessionId === session.id).map(envelope => envelope.seq));
546
+ const envelope = (event: Envelope['event']): Envelope => ({ sessionId: session.id, epoch: opened.epoch, seq, ts: new Date().toISOString(), event });
547
+ deliver(connection, envelope({ ...opened.event, session }));
548
+ if (history === 'replay' && session.id === root) replayHistory(connection, root, log, { children: false });
549
+ deliver(connection, envelope({ type: 'session.ready' }));
550
+ if (session.activeTurnId) deliver(connection, envelope({ type: 'turn.started', turnId: session.activeTurnId, origin: 'user' }));
551
+ }
552
+ announceQuestions(connection, root);
553
+ }
554
+
555
+ /** Reopens a closed root from its record: the native thread resumes, alpd replays the history. */
556
+ async function resume(connection: Connection, record: SessionRecord, spec: any, history: 'replay' | 'skip', delegation: boolean) {
557
+ const session = record.session;
558
+ if (record.rootId !== record.id) throw new RpcError(ERROR.failed, 'Only root sessions can be resumed');
559
+ if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, 'This session cannot be resumed');
560
+ const agent = spec.agent ?? spec.restore?.agent;
561
+ if (agent !== undefined && agent !== session.agent) throw new RpcError(ERROR.failed, 'Cannot resume a session as a different ALP agent');
562
+ const stored = await treeLog(record.id);
563
+ seen(record.id, stored);
564
+ logs.set(record.id, [...stored]);
565
+ attach(connection, record.id);
566
+ try {
567
+ const opened = await runtime.open(record.id, {
568
+ ...record.spec,
569
+ ...(spec.mode !== undefined ? { mode: spec.mode } : {}),
570
+ ...(spec.thinking !== undefined ? { thinking: spec.thinking } : {}),
571
+ persist: true,
572
+ restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
573
+ }, { history: stored.length ? 'skip' : history, delegation: record.delegation ?? delegation });
574
+ if (history === 'replay') replayHistory(connection, record.id, stored);
575
+ return opened;
576
+ } catch (error) {
577
+ detach(connection, record.id);
578
+ throw error;
579
+ }
580
+ }
581
+
582
+ /** Projects, tasks, library and settings (docs/protocol/alp-json-rpc-v1.md §15); a team save syncs the projects sessions ran in. */
583
+ const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap(record => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
584
+ const extensionOwners = new Map<string, Connection>();
585
+ const handlers: Record<string, (connection: Connection, params: any) => Promise<unknown> | unknown> = {
586
+ 'extension.register': async (connection, params) => {
587
+ const method = params?.method;
588
+ if (typeof method !== 'string' || !/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(method) || method === '__proto__' || method === 'constructor' || method === 'toString') throw new RpcError(ERROR.protocol, 'extension.register requires a safe method name');
589
+ if (method.length > 128 || (reservedNamespaces.has(method.split('.')[0]) && !originalMethods.has(method))) throw new RpcError(ERROR.protocol, 'extension.register requires an extension namespace and a name of at most 128 characters');
590
+ if (originalMethods.has(method) || extensionOwners.has(method) || Object.hasOwn(handlers, method)) throw new RpcError(ERROR.conflict, `${method} is already registered`);
591
+ if ((methodOwners.get(connection)?.size ?? 0) >= 128 || extensionOwners.size >= 1024) throw new RpcError(ERROR.conflict, 'too many registered extension methods');
592
+ extensionOwners.set(method, connection);
593
+ if (!methodOwners.has(connection)) methodOwners.set(connection, new Set());
594
+ methodOwners.get(connection).add(method);
595
+ handlers[method] = async (_connection, invokeParams) => {
596
+ const owner = extensionOwners.get(method);
597
+ if (!owner || !connections.has(owner)) { delete handlers[method]; extensionOwners.delete(method); throw new RpcError(ERROR.notFound, `${method} is not available`); }
598
+ return invokeExtended(owner, _connection, method, invokeParams ?? {});
599
+ };
600
+ return { registered: method };
601
+ },
602
+ 'extension.unregister': async (connection, params) => {
603
+ const method = params?.method;
604
+ if (typeof method !== 'string' || !method.trim()) throw new RpcError(ERROR.protocol, 'extension.unregister requires a method name');
605
+ const owner = extensionOwners.get(method);
606
+ if (!owner) throw new RpcError(ERROR.notFound, `${method} is not registered`);
607
+ if (owner !== connection) throw new RpcError(ERROR.conflict, `${method} is owned by another connection`);
608
+ delete handlers[method];
609
+ extensionOwners.delete(method);
610
+ const owned = methodOwners.get(connection);
611
+ owned?.delete(method);
612
+ return { unregistered: method };
613
+ },
614
+ 'daemon.status': async () => ({ pid: process.pid, startedAt, version, protocolVersion: PROTOCOL_VERSION, sessions: runtime.list().length, questions: runtime.questions().length, ...(previousExit ? { previousExit } : {}), ...(store ? { persistence: store.health() } : {}), health: await health() }),
615
+
616
+ 'session.status'(_connection, { sessionId }) {
617
+ if (typeof sessionId !== 'string') throw new RpcError(-32602, 'sessionId is required');
618
+ const status = runtime.status(sessionId);
619
+ if (!status) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not live`);
620
+ return { status };
621
+ },
622
+
623
+ 'session.message'(_connection, { sessionId, text }) {
624
+ runtime.message(sessionId, text);
625
+ return {};
626
+ },
627
+
628
+ /** The assignment log of a session's tree, from the run log. */
629
+ async 'session.log'(_connection, { sessionId }) {
630
+ const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
631
+ if (!runLogDir) return { rootId: root, entries: [] };
632
+ const text = await readFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`), 'utf8').catch(() => '');
633
+ const entries = text.split('\n').filter(Boolean).flatMap(line => { try { return [JSON.parse(line)]; } catch { return []; } });
634
+ return { rootId: root, entries };
635
+ },
636
+
637
+ 'question.list'(_connection, { projectRoot } = {}) {
638
+ const questions = runtime.questions().filter(question => projectRoot === undefined || runtime.snapshot(question.rootId)?.projectRoot === projectRoot);
639
+ return { questions };
640
+ },
641
+
642
+ /** The project board: live claims, decisions and findings (ALPD §18). */
643
+ async 'board.list'(_connection, { projectRoot } = {}) {
644
+ if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, 'An absolute projectRoot is required');
645
+ return { pins: await runtime.board(projectRoot) };
646
+ },
647
+
648
+ /** Pauses delegation and wakes on a runtime, or everywhere (ALPD §29). */
649
+ 'daemon.pause'(_connection, { runtime: kind, now = false, reason } = {}) {
650
+ try { return runtime.pause({ ...(kind === undefined ? {} : { runtime: kind }), now: now === true, ...(reason === undefined ? {} : { reason }) }); }
651
+ catch (error: any) { throw new RpcError(-32602, error?.message ?? String(error)); }
652
+ },
653
+
654
+ 'daemon.resume'(_connection, { runtime: kind } = {}) {
655
+ try { return runtime.resume(kind === undefined ? {} : { runtime: kind }); }
656
+ catch (error: any) { throw new RpcError(-32602, error?.message ?? String(error)); }
657
+ },
658
+
659
+ 'daemon.pauses'() {
660
+ return runtime.pauses();
661
+ },
662
+ 'daemon.usage': (_connection, { refresh = false } = {}) => runtime.usage(refresh === true),
663
+
664
+ /** Asks a finished assignment, or the last one on a task, about its work (ALPD §27). */
665
+ async 'assignment.recall'(_connection, { assignmentId, taskId, projectRoot, question } = {}) {
666
+ if (projectRoot !== undefined && (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot))) throw new RpcError(-32602, 'projectRoot must be absolute');
667
+ try {
668
+ return await runtime.recall({ assignmentId, taskId, projectRoot }, question);
669
+ } catch (error: any) {
670
+ throw new RpcError(ERROR.failed, error?.message ?? String(error));
671
+ }
672
+ },
673
+
674
+ 'question.answer'(_connection, { questionId, text, dismiss = false, reason }) {
675
+ if (typeof questionId !== 'string') throw new RpcError(-32602, 'questionId is required');
676
+ if (dismiss !== true && typeof text !== 'string') throw new RpcError(-32602, 'text or dismiss is required');
677
+ // A unique prefix is enough, as in the CLI.
678
+ const matches = runtime.questions().filter(question => question.id === questionId || question.id.startsWith(questionId));
679
+ if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
680
+ runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason } : { text });
681
+ return { questionId: matches[0].id };
682
+ },
683
+
684
+ 'daemon.shutdown': () => {
685
+ setImmediate(() => onShutdown?.());
686
+ return {};
687
+ },
688
+
689
+ 'catalog.get': () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
690
+
691
+ async 'session.create'(connection, { sessionId, spec, history = 'skip', delegation = true, resume: resuming = false }) {
692
+ if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
693
+ if (sessionId !== undefined && (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, 'Invalid session id');
694
+ if (history !== 'replay' && history !== 'skip') throw new RpcError(-32602, 'history must be replay or skip');
695
+ const id = sessionId ?? `ses_${randomBytes(8).toString('hex')}`;
696
+ // A root alpd is reopening after a restart: attach once it is open, rather than open it twice.
697
+ await recovering.get(id);
698
+ const existing = runtime.snapshot(id);
699
+ if (existing) {
700
+ // Reopening a root that kept working after its viewer left: attach to it.
701
+ const agent = spec.agent ?? spec.restore?.agent;
702
+ if (existing.parentId || (agent !== undefined && agent !== existing.agent)) throw new RpcError(ERROR.failed, 'Session is already open');
703
+ attach(connection, id);
704
+ announce(connection, id, history);
705
+ return { session: existing, attached: true };
706
+ }
707
+ const record = records.get(id);
708
+ if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
709
+ if (record) {
710
+ const session = await resume(connection, record, spec, history, delegation);
711
+ return { session, attached: false, resumed: true, ...await persisted(id) };
712
+ }
713
+ const { restore: _restore, ...kept } = spec;
714
+ const now = new Date().toISOString();
715
+ const created: SessionRecord = { version: 1, id, rootId: id, spec: kept, delegation, status: 'initializing', createdAt: now, updatedAt: now };
716
+ records.set(id, created);
717
+ // A root is resumable only once its record is on disk; without it the create fails and nothing starts.
718
+ try { await store?.put(created); }
719
+ catch (error) {
720
+ if (records.get(id) === created) records.delete(id);
721
+ throw persistenceFailed(`session ${id}; it was not started`, error);
722
+ }
723
+ attach(connection, id);
724
+ try {
725
+ const session = await runtime.open(id, spec, { history, delegation });
726
+ return { session, attached: false, ...await persisted(id) };
727
+ } catch (error) {
728
+ detach(connection, id);
729
+ records.delete(id);
730
+ await store?.remove(id, [id]);
731
+ throw error;
732
+ }
733
+ },
734
+
735
+ /** The team and main a new root would run with, and the teams it may choose (ALPD §60). */
736
+ async 'session.preview'(_connection, { spec }) {
737
+ if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
738
+ return { preview: await runtime.preview(spec) };
739
+ },
740
+
741
+ /**
742
+ * Watches a tree. With `after`, the cursor of the last event a client has, only later
743
+ * events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
744
+ * with the whole timeline. The replay and the live events that follow are in cursor order.
745
+ */
746
+ async 'session.attach'(connection, { sessionId, replay = true, after }) {
747
+ if (after !== undefined && (!Number.isSafeInteger(after) || after < 0)) throw new RpcError(-32602, 'after must be a cursor');
748
+ const found = known(sessionId);
749
+ const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
750
+ let stored: Envelope[] = [];
751
+ if (replay || (store && !cursors.has(root))) {
752
+ // The in-memory log keeps a live tree's latest events only; older ones come from the store.
753
+ const memory = logs.get(root);
754
+ const covered = !!memory?.length && (memory[0].cursor ?? 1) <= (after ?? 0) + 1;
755
+ if (!covered) stored = store ? await store.timeline(root) : memory ?? [];
756
+ }
757
+ // From here to the return nothing awaits, so no live event slips between replay and attach.
758
+ const live = logs.get(root) ?? [];
759
+ const tip = Math.max(cursors.get(root) ?? 0, stored.at(-1)?.cursor ?? 0, live.at(-1)?.cursor ?? 0);
760
+ // Without a store the in-memory log keeps only the latest events: a cursor before them cannot continue either.
761
+ const first = replay ? [...stored, ...live].find(envelope => envelope.cursor !== undefined)?.cursor : undefined;
762
+ const reset = after !== undefined && (after > tip || (replay && after < tip && (first === undefined || first > after + 1)));
763
+ const from = reset ? 0 : after ?? 0;
764
+ attach(connection, root);
765
+ if (replay) {
766
+ let last = from;
767
+ for (const envelope of stored) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
768
+ for (const envelope of live) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
769
+ }
770
+ announceQuestions(connection, root);
771
+ return { session: root === found.id ? found : summary(root), cursor: tip, ...(reset ? { reset: true } : {}) };
772
+ },
773
+
774
+ async 'session.release'(connection, { sessionId }) {
775
+ const root = rootOf.get(sessionId) ?? sessionId;
776
+ detach(connection, root);
777
+ return { closed: await reap(root) };
778
+ },
779
+
780
+ async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content }) {
781
+ if (typeof clientMessageId !== 'string' || !Array.isArray(content)) throw new RpcError(-32602, 'clientMessageId and content are required');
782
+ if (delivery !== 'auto' && delivery !== 'steer') throw new RpcError(-32602, 'delivery must be auto or steer');
783
+ const send = async () => {
784
+ // Failures of an open session arrive as prompt.failed events; an unknown session has no watcher.
785
+ live(sessionId);
786
+ await runtime.prompt(sessionId, { clientMessageId, delivery, content });
787
+ };
788
+ if (!store) {
789
+ await send();
790
+ return {};
791
+ }
792
+ return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
793
+ },
794
+
795
+ async 'session.interrupt'(_connection, { sessionId }) {
796
+ await runtime.interrupt(sessionId);
797
+ return {};
798
+ },
799
+
800
+ async 'session.configure'(_connection, { sessionId, mode }) {
801
+ return { session: await runtime.configure(sessionId, { mode }) };
802
+ },
803
+
804
+ async 'session.close'(_connection, { sessionId }) {
805
+ await runtime.close(sessionId);
806
+ return {};
807
+ },
808
+
809
+ /** The user's name for a root, in place of its first prompt (ALPD §61). */
810
+ async 'session.rename'(_connection, { sessionId, title }) {
811
+ if (typeof title !== 'string' || !title.trim() || [...title].length > 200) throw new RpcError(-32602, 'title must be 1 to 200 characters');
812
+ const record = rootRecord(sessionId);
813
+ // A name is not activity: the record keeps its time.
814
+ const before = record.title;
815
+ Object.assign(record, { title: title.replace(/\s+/g, ' ').trim() });
816
+ try { await store?.put(record); }
817
+ catch (error) { record.title = before; throw persistenceFailed(`the name of ${record.id}`, error); }
818
+ return { session: summary(record.id) };
819
+ },
820
+
821
+ /** Sets a root aside: it closes, with its tree, and leaves the lists until unarchived (ALPD §61). */
822
+ async 'session.archive'(_connection, { sessionId, archived = true }) {
823
+ const record = rootRecord(sessionId);
824
+ if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
825
+ const before = record.archived;
826
+ Object.assign(record, { archived: archived === true ? true : undefined });
827
+ try { await store?.put(record); }
828
+ catch (error) { record.archived = before; throw persistenceFailed(`the archive state of ${record.id}`, error); }
829
+ return { session: summary(record.id) };
830
+ },
831
+
832
+ 'session.get'(_connection, { sessionId }) {
833
+ return { session: known(sessionId) };
834
+ },
835
+
836
+ 'session.list'(_connection, { projectRoot, rootsOnly = false, includeClosed = false, includeArchived = false } = {}): { sessions: SessionSummary[] } {
837
+ const ids = new Set([...runtime.list().map(session => session.id), ...records.keys()]);
838
+ const sessions = [...ids].map(summary).filter((session): session is SessionSummary => !!session)
839
+ .filter(session => includeClosed || session.status === 'idle' || session.status === 'running')
840
+ .filter(session => includeArchived || !session.archived)
841
+ .filter(session => !rootsOnly || !session.parentId)
842
+ .filter(session => projectRoot === undefined || session.projectRoot === projectRoot)
843
+ .sort((a, b) => Number(!!a.parentId) - Number(!!b.parentId) || (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''));
844
+ return { sessions };
845
+ },
846
+ };
847
+ for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
848
+ Object.setPrototypeOf(handlers, null);
849
+ // Every v1 method name stays the daemon's, served here or not, so no extension takes one.
850
+ const originalMethods = new Set([...Object.keys(handlers), ...RPC_METHODS]);
851
+ const reservedNamespaces = new Set([...originalMethods].map(method => method.split('.')[0]));
852
+
853
+ async function invokeExtended(owner: Connection, caller: Connection, method: string, params: any) {
854
+ if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, 'too many pending extension calls');
855
+ const id = ++owner.nextId;
856
+ const invocation = { jsonrpc: '2.0', id, method: 'extension.invoke', params: { method, params } };
857
+ if (Buffer.byteLength(encodeFrame(invocation), 'utf8') > MAX_FRAME) throw new RpcError(-32600, 'ALP daemon frame exceeds size limit');
858
+ return new Promise((resolve, reject) => {
859
+ const timer = setTimeout(() => {
860
+ owner.pending.delete(id);
861
+ reject(new RpcError(ERROR.failed, `${method} timed out`));
862
+ }, 30_000);
863
+ owner.pending.set(id, { resolve, reject, timer, caller });
864
+ try { owner.send(invocation); }
865
+ catch (error) { clearTimeout(timer); owner.pending.delete(id); reject(error); }
866
+ });
867
+ }
868
+
869
+ /**
870
+ * Liveness is that alpd answers at all. Readiness is that it can do its work: it accepts
871
+ * connections, and its state directory can be read and written now with no write failing.
872
+ * Not ready is a state to fix, not a reason to stop: the checks say what and the codes
873
+ * match alpd's log.
874
+ */
875
+ async function health() {
876
+ const checks: Array<{ id: string; ok: boolean; code?: string; message?: string }> = [{ id: 'accepting', ok: !closing, ...(closing ? { code: 'ALP_SHUTTING_DOWN', message: 'alpd is shutting down' } : {}) }];
877
+ if (store) {
878
+ const probe = await store.probe();
879
+ checks.push({ id: 'state', ...probe });
880
+ const failing = store.failing();
881
+ checks.push({ id: 'persistence', ok: failing === 0, ...(failing ? { code: 'ALP_PERSISTENCE_FAILING', message: `${failing} write${failing > 1 ? 's' : ''} of sessions or timelines failed and have not been written since` } : {}) });
882
+ }
883
+ return { live: true, ready: checks.every(check => check.ok), checks };
884
+ }
885
+
886
+ /** What this daemon lists in daemon.hello: only features it serves now (docs/protocol/alp-json-rpc-v1.md §6). */
887
+ const capabilities = [CAPABILITY.attachAfter, CAPABILITY.extensionMethods, ...(store ? [CAPABILITY.promptReceipts] : []), ...operations.capabilities];
888
+
889
+ /** A response too large for the wire becomes an error the client can read. */
890
+ function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
891
+ if (frameBytes(response) <= MAX_FRAME) return response;
892
+ log.warn('a response exceeded the frame size limit', { code: 'ALP_IPC_RESPONSE_TOO_LARGE', requestId: String(response.id) });
893
+ return { jsonrpc: '2.0', id: response.id, error: { code: ERROR.failed, message: 'The response exceeds the ALP frame size limit', data: { reason: 'response_too_large' } } };
894
+ }
895
+
896
+ /**
897
+ * One incoming message, in the order docs/protocol/alp-json-rpc-v1.md §5 fixes: a message that is
898
+ * not a single JSON-RPC 2.0 object, a frame over the limit, a notification, an invalid id or params,
899
+ * the handshake, an unknown method, then the method's own params. Nothing runs before all of them pass.
900
+ */
901
+ async function dispatch(connection: Connection, message: any, receivedBytes?: number) {
902
+ const single = !!message && typeof message === 'object' && !Array.isArray(message);
903
+ const { id, method, params } = single ? message : {} as any;
904
+ const respond = (body: object) => connection.send(fits({ jsonrpc: '2.0', id: validId(id) ? id : null, ...body }));
905
+ try {
906
+ if (Array.isArray(message)) throw new RpcError(RPC_ERROR.invalidRequest, 'Batch requests are not supported', { reason: 'batch_unsupported' });
907
+ // Validate the envelope before anything else: a frame that is not JSON-RPC 2.0 must never be
908
+ // correlated against (or consume) a pending extension call, however it is shaped.
909
+ if (!single || message.jsonrpc !== '2.0') throw new RpcError(RPC_ERROR.invalidRequest, 'Invalid request');
910
+ const oversized = (receivedBytes ?? frameBytes(message)) > MAX_FRAME;
911
+ // A frame with no `method` property is a response to an outgoing extension.invoke. It must carry
912
+ // exactly one of result/error and an id; a malformed or unknown one is dropped, leaving any
913
+ // pending invocation intact (never mis-correlated, never leaked).
914
+ if (!Object.prototype.hasOwnProperty.call(message, 'method')) {
915
+ const hasResult = Object.prototype.hasOwnProperty.call(message, 'result');
916
+ const hasError = Object.prototype.hasOwnProperty.call(message, 'error');
917
+ if (id === undefined || id === null || hasResult === hasError) return;
918
+ const waiter = connection.pending.get(id);
919
+ if (!waiter) return;
920
+ connection.pending.delete(id);
921
+ clearTimeout(waiter.timer);
922
+ if (oversized) { waiter.reject(new RpcError(RPC_ERROR.invalidRequest, 'ALP daemon frame exceeds size limit')); return; }
923
+ if (hasError) waiter.reject(new RpcError(message.error?.code ?? ERROR.failed, message.error?.message ?? 'extension call failed', message.error?.data));
924
+ else waiter.resolve(message.result);
925
+ return;
926
+ }
927
+ if (oversized) throw new RpcError(RPC_ERROR.invalidRequest, 'ALP daemon frame exceeds size limit', { reason: 'frame_too_large' });
928
+ if (typeof method !== 'string') throw new RpcError(RPC_ERROR.invalidRequest, 'Invalid request');
929
+ // v1 defines no notifications to the daemon: one is dropped unrun, and JSON-RPC forbids answering it.
930
+ if (id === undefined) { log.debug('ignored a notification', { code: 'ALP_IPC_NOTIFICATION_IGNORED', method }); return; }
931
+ if (!validId(id)) throw new RpcError(RPC_ERROR.invalidRequest, 'A request id must be a string of at most 128 characters or a safe integer', { reason: 'invalid_id' });
932
+ if (params !== undefined && (params === null || typeof params !== 'object' || Array.isArray(params))) throw new RpcError(RPC_ERROR.invalidParams, 'params must be an object', { reason: 'invalid_params' });
933
+ if (method === 'daemon.hello') {
934
+ if (params?.protocolVersion !== PROTOCOL_VERSION) throw new RpcError(ERROR.protocol, `ALP daemon speaks protocol ${PROTOCOL_VERSION}; restart it after upgrading (alp daemon restart)`, { reason: 'protocol_version', supported: [PROTOCOL_VERSION] });
935
+ const issues = validateParams(method, params)!;
936
+ if (issues.length) throw invalidParams(issues);
937
+ connection.helloed = true;
938
+ respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, capabilities } });
939
+ return;
940
+ }
941
+ if (!connection.helloed) throw new RpcError(ERROR.protocol, 'daemon.hello is required first', { reason: 'hello_required' });
942
+ await restored;
943
+ if (!connections.has(connection)) return;
944
+ const handler = Object.hasOwn(handlers, method) ? handlers[method] : undefined;
945
+ if (!handler) throw new RpcError(RPC_ERROR.methodNotFound, `Unknown method '${method}'`);
946
+ // Built-in methods are checked against the v1 schema; extension methods own their params.
947
+ const issues = validateParams(method, params);
948
+ if (issues?.length) throw invalidParams(issues);
949
+ respond({ result: await handler(connection, params ?? {}) });
950
+ } catch (error) {
951
+ const code = error instanceof RpcError ? error.code : /is not open/.test(String((error as Error)?.message)) ? ERROR.notFound : ERROR.failed;
952
+ const data = error instanceof RpcError && error.data !== undefined ? { data: error.data } : {};
953
+ // Plain errors are mostly refusals of bad input; logged so an unexpected one can be traced by its request.
954
+ if (!(error instanceof RpcError) && code === ERROR.failed) log.warn(`${method} failed`, { code: 'ALP_RPC_FAILED', requestId: id, sessionId: params?.sessionId, method, error });
955
+ else if (error instanceof RpcError && (error.data as { reason?: string } | undefined)?.reason === 'persistence_failed') log.warn(`${method} failed`, { code: 'ALP_PERSISTENCE_FAILED', requestId: id, sessionId: params?.sessionId, method, error });
956
+ respond({ error: { code, message: error instanceof Error ? error.message : String(error), ...data } });
957
+ }
958
+ }
959
+
960
+ const methodOwners = new Map();
961
+ function disconnect(connection: Connection) {
962
+ const owned = methodOwners.get(connection);
963
+ if (owned) for (const method of owned) { delete handlers[method]; extensionOwners.delete(method); }
964
+ methodOwners.delete(connection);
965
+ for (const [id, waiting] of connection.pending) { clearTimeout(waiting.timer); waiting.reject(new Error('ALP daemon connection closed')); }
966
+ connection.pending.clear();
967
+ for (const owner of connections) for (const [id, waiting] of owner.pending) {
968
+ if (waiting.caller !== connection) continue;
969
+ clearTimeout(waiting.timer);
970
+ owner.pending.delete(id);
971
+ waiting.reject(new Error('ALP daemon caller connection closed'));
972
+ }
973
+ connections.delete(connection);
974
+ for (const root of [...connection.roots]) {
975
+ detach(connection, root);
976
+ void reap(root);
977
+ }
978
+ }
979
+
980
+ const server = net.createServer(socket => {
981
+ if (closing) { socket.destroy(); return; }
982
+ const connection: Connection = {
983
+ socket,
984
+ helloed: false,
985
+ roots: new Set(),
986
+ send(message) { if (!socket.destroyed) socket.write(encodeFrame(message)); },
987
+ nextId: 0,
988
+ pending: new Map(),
989
+ };
990
+ connections.add(connection);
991
+ let buffer = '';
992
+ /** UTF-8 bytes of `buffer`, kept as chunks arrive so a large frame costs linear time. */
993
+ let bytes = 0;
994
+ socket.setEncoding('utf8');
995
+ // A frame over MAX_FRAME bytes, its newline included, ends the connection: nothing after it can be trusted to align.
996
+ const tooLarge = () => { log.warn('closed a connection that sent a frame over the size limit', { code: 'ALP_IPC_FRAME_TOO_LARGE' }); buffer = ''; bytes = 0; socket.destroy(); };
997
+ socket.on('data', (chunk: string) => {
998
+ buffer += chunk;
999
+ bytes += Buffer.byteLength(chunk, 'utf8');
1000
+ // Only the new chunk can hold a newline: the buffer before it had none.
1001
+ if (!chunk.includes('\n')) {
1002
+ if (bytes >= MAX_FRAME) tooLarge();
1003
+ return;
1004
+ }
1005
+ let start = 0;
1006
+ for (let index = buffer.indexOf('\n', buffer.length - chunk.length); index >= 0; index = buffer.indexOf('\n', start)) {
1007
+ const line = buffer.slice(start, index);
1008
+ start = index + 1;
1009
+ if (Buffer.byteLength(line, 'utf8') + 1 > MAX_FRAME) { tooLarge(); return; }
1010
+ if (!line.trim()) continue;
1011
+ let message;
1012
+ try { message = JSON.parse(line); } catch { log.warn('a client sent a line that is not JSON', { code: 'ALP_IPC_PARSE_ERROR', bytes: line.length }); connection.send({ jsonrpc: '2.0', id: null, error: { code: RPC_ERROR.parseError, message: 'Parse error' } }); continue; }
1013
+ void dispatch(connection, message, Buffer.byteLength(line, 'utf8') + 1);
1014
+ }
1015
+ // What is left has no newline yet; with one it would already be over the limit.
1016
+ buffer = buffer.slice(start);
1017
+ bytes = Buffer.byteLength(buffer, 'utf8');
1018
+ if (bytes >= MAX_FRAME) tooLarge();
1019
+ });
1020
+ // A client that goes away mid-write resets its connection; that alone is no trouble.
1021
+ socket.on('error', (error: NodeJS.ErrnoException) => log[error.code === 'ECONNRESET' || error.code === 'EPIPE' ? 'debug' : 'warn']('a client connection failed', { code: 'ALP_IPC_SOCKET_ERROR', error }));
1022
+ socket.on('close', () => disconnect(connection));
1023
+ });
1024
+
1025
+ return {
1026
+ extend(method, handler, owner = null) {
1027
+ if (typeof method !== 'string' || !method.trim()) throw new Error('extend needs a method name');
1028
+ if (originalMethods.has(method)) throw new Error(`${method} is a built-in method and cannot be overridden`);
1029
+ if (Object.hasOwn(handlers, method)) throw new Error(`${method} is already registered`);
1030
+ handlers[method] = async (_connection, params) => {
1031
+ try {
1032
+ const result = await handler(params ?? {});
1033
+ return result === undefined ? {} : result;
1034
+ } catch (error) {
1035
+ const message = error instanceof Error ? error.message : String(error);
1036
+ throw new Error(message.length > 2000 ? `${message.slice(0, 2000)}...` : message);
1037
+ }
1038
+ };
1039
+ if (owner) {
1040
+ if (!methodOwners.has(owner)) methodOwners.set(owner, new Set());
1041
+ methodOwners.get(owner).add(method);
1042
+ }
1043
+ },
1044
+
1045
+ async listen() {
1046
+ if (process.platform !== 'win32') {
1047
+ await assertPrivateDirectory(path.dirname(socketPath), { create: true });
1048
+ const existing = await lstat(socketPath).catch(error => { if (error.code === 'ENOENT') return undefined; throw error; });
1049
+ if (existing) {
1050
+ await assertPrivateSocket(socketPath);
1051
+ // Never unlink a live daemon; only ECONNREFUSED proves a stale Unix socket.
1052
+ const active = await new Promise<boolean>((resolve, reject) => {
1053
+ const probe = net.createConnection(socketPath);
1054
+ probe.once('connect', () => { probe.destroy(); resolve(true); });
1055
+ probe.once('error', error => { probe.destroy(); if ((error as NodeJS.ErrnoException).code === 'ECONNREFUSED') resolve(false); else reject(error); });
1056
+ probe.setTimeout(1000, () => { probe.destroy(); reject(new Error('IPC endpoint probe timed out')); });
1057
+ });
1058
+ if (active) throw new Error('IPC endpoint already in use by a running daemon');
1059
+ const current = await assertPrivateSocket(socketPath);
1060
+ if (!current || current.dev !== existing.dev || current.ino !== existing.ino) throw new Error('IPC endpoint changed during validation');
1061
+ await unlink(socketPath);
1062
+ }
1063
+ }
1064
+ // libuv unlinks its bind path on close without checking inode identity. Bind at an
1065
+ // unpublished sibling, then publish; cleanup of the public endpoint is ours alone.
1066
+ const bindPath = process.platform === 'win32' ? socketPath : path.join(path.dirname(socketPath), `.s${randomBytes(3).toString('hex')}`);
1067
+ await new Promise<void>((resolve, reject) => {
1068
+ server.once('error', reject);
1069
+ server.listen(bindPath, () => { server.off('error', reject); resolve(); });
1070
+ });
1071
+ if (process.platform !== 'win32') {
1072
+ try {
1073
+ await chmod(bindPath, 0o600);
1074
+ const info = await lstat(bindPath);
1075
+ await rename(bindPath, socketPath);
1076
+ socketIdentity = { dev: info.dev, ino: info.ino };
1077
+ }
1078
+ catch (error) { await new Promise<void>(resolve => server.close(() => resolve())); throw error; }
1079
+ }
1080
+ },
1081
+
1082
+ local() {
1083
+ const events = new Set<(envelope: Envelope) => void>();
1084
+ const closes = new Set<(error: Error) => void>();
1085
+ const pending = new Map<number, { resolve: (value: any) => void; reject: (error: Error) => void }>();
1086
+ let sequence = 0;
1087
+ let ended = false;
1088
+ const connection: Connection = {
1089
+ helloed: true,
1090
+ roots: new Set(),
1091
+ nextId: 0,
1092
+ pending: new Map(),
1093
+ send(message: any) {
1094
+ if (message.method === 'event') {
1095
+ for (const listener of events) listener(message.params);
1096
+ return;
1097
+ }
1098
+ const waiter = pending.get(message.id);
1099
+ if (!waiter) return;
1100
+ pending.delete(message.id);
1101
+ if (message.error) waiter.reject(new AlpRpcError(message.error));
1102
+ else waiter.resolve(message.result);
1103
+ },
1104
+ };
1105
+ connections.add(connection);
1106
+ return {
1107
+ request(method, params = {}) {
1108
+ if (ended) return Promise.reject(new Error('ALP daemon connection closed'));
1109
+ const id = ++sequence;
1110
+ return new Promise((resolve, reject) => {
1111
+ pending.set(id, { resolve, reject });
1112
+ void dispatch(connection, { jsonrpc: '2.0', id, method, params });
1113
+ });
1114
+ },
1115
+ onEvent(listener) { events.add(listener); return () => events.delete(listener); },
1116
+ onClose(listener) { closes.add(listener); return () => closes.delete(listener); },
1117
+ close() {
1118
+ if (ended) return;
1119
+ ended = true;
1120
+ disconnect(connection);
1121
+ // Match the socket client's teardown: in-flight requests fail and close listeners fire.
1122
+ const error = new Error('ALP daemon connection closed');
1123
+ for (const waiter of pending.values()) waiter.reject(error);
1124
+ pending.clear();
1125
+ for (const listener of closes) listener(error);
1126
+ closes.clear();
1127
+ },
1128
+ };
1129
+ },
1130
+
1131
+ accept(send) {
1132
+ const connection: Connection = { helloed: false, roots: new Set(), send, nextId: 0, pending: new Map() };
1133
+ connections.add(connection);
1134
+ let ended = false;
1135
+ return {
1136
+ receive(message) { if (!ended) void dispatch(connection, message); },
1137
+ close() {
1138
+ if (ended) return;
1139
+ ended = true;
1140
+ disconnect(connection);
1141
+ },
1142
+ };
1143
+ },
1144
+
1145
+ async close() {
1146
+ closing = true;
1147
+ if (sweeper) clearInterval(sweeper);
1148
+ const stopped = new Promise<void>(resolve => server.close(() => resolve()));
1149
+ for (const connection of connections) connection.socket?.destroy();
1150
+ await stopped;
1151
+ if (socketIdentity) {
1152
+ const current = await lstat(socketPath).catch(error => { if (error.code === 'ENOENT') return undefined; throw error; });
1153
+ if (current?.isSocket() && current.dev === socketIdentity.dev && current.ino === socketIdentity.ino) await unlink(socketPath);
1154
+ socketIdentity = undefined;
1155
+ }
1156
+ await store?.flush();
1157
+ },
1158
+ };
1159
+ }