@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/dist/server.js ADDED
@@ -0,0 +1,1020 @@
1
+ // packages/daemon/src/server.ts
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { appendFile, chmod, mkdir, readFile, unlink, lstat, rename } from "node:fs/promises";
4
+ import net from "node:net";
5
+ import { assertPrivateDirectory, assertPrivateSocket } from "@anhlp/alp-client/index";
6
+ import path from "node:path";
7
+ import { createLogger } from "@anhlp/alp-core/log";
8
+ import { AlpRpcError, CAPABILITY, MAX_FRAME, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, encodeFrame } from "@anhlp/alp-protocol";
9
+ import { validateParams } from "@anhlp/alp-protocol/contract";
10
+ import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
11
+ import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
12
+ import { RpcError } from "./rpc-error.js";
13
+ import { createOperations } from "./operations.js";
14
+ var log = createLogger({ component: "alpd.ipc" });
15
+ var recoveryLog = createLogger({ component: "alpd.recovery" });
16
+ function validId(id) {
17
+ if (typeof id !== "string") return Number.isSafeInteger(id);
18
+ let length = 0;
19
+ for (const _point of id) if (++length > 128) return false;
20
+ return true;
21
+ }
22
+ var frameBytes = (message) => Buffer.byteLength(encodeFrame(message), "utf8");
23
+ var invalidParams = (issues) => new RpcError(RPC_ERROR.invalidParams, `Invalid params: ${issues.map((issue) => `${issue.path || "params"} ${issue.message}`).join("; ")}`, { reason: "invalid_params", issues });
24
+ function crashPoint(name) {
25
+ if (process.env.ALP_TEST_CRASH_AT !== name) return;
26
+ createLogger({ component: "alpd" }).error(`ALP_TEST_CRASH_AT=${name}: killing alpd`, { code: "ALP_TEST_CRASH" });
27
+ process.kill(process.pid, "SIGKILL");
28
+ }
29
+ var persistenceFailed = (what, error) => new RpcError(ERROR.failed, `alpd could not record ${what}: ${error instanceof Error ? error.message : String(error)}`, { reason: "persistence_failed" });
30
+ function digest(value) {
31
+ return createHash("sha256").update(JSON.stringify(value, (_key, candidate) => candidate !== null && typeof candidate === "object" && !Array.isArray(candidate) ? Object.fromEntries(Object.entries(candidate).sort(([a], [b]) => a.localeCompare(b))) : candidate)).digest("hex");
32
+ }
33
+ var TREE_LOG_LIMIT = 2e4;
34
+ var SESSION_ID = /^[\w.:-]{1,128}$/;
35
+ var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
36
+ var RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
37
+ var RETENTION_SWEEP_MS = 6 * 60 * 60 * 1e3;
38
+ var LIVE = ["initializing", "idle", "running"];
39
+ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates }) {
40
+ const connections = /* @__PURE__ */ new Set();
41
+ const rootOf = /* @__PURE__ */ new Map();
42
+ const attached = /* @__PURE__ */ new Map();
43
+ const logs = /* @__PURE__ */ new Map();
44
+ const records = /* @__PURE__ */ new Map();
45
+ const delivering = /* @__PURE__ */ new Map();
46
+ const unsaved = /* @__PURE__ */ new Map();
47
+ const cursors = /* @__PURE__ */ new Map();
48
+ let closing = false;
49
+ let socketIdentity;
50
+ const recovering = /* @__PURE__ */ new Map();
51
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
52
+ const restored = store ? restore() : Promise.resolve();
53
+ const deliver = (connection, envelope) => connection.send({ jsonrpc: "2.0", method: "event", params: envelope });
54
+ function save(record, changes = {}) {
55
+ Object.assign(record, changes, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
56
+ records.set(record.id, record);
57
+ return store?.put(record).catch(() => {
58
+ }) ?? Promise.resolve();
59
+ }
60
+ function keep(root, envelope) {
61
+ const cursor = (cursors.get(root) ?? 0) + 1;
62
+ cursors.set(root, cursor);
63
+ const kept = { ...envelope, cursor };
64
+ void store?.append(root, kept).catch(() => {
65
+ });
66
+ return kept;
67
+ }
68
+ function seen(root, log2) {
69
+ const last = log2.at(-1)?.cursor ?? 0;
70
+ if (last > (cursors.get(root) ?? 0)) cursors.set(root, last);
71
+ }
72
+ function track(sessionId, root, event) {
73
+ const now = (/* @__PURE__ */ new Date()).toISOString();
74
+ let record = records.get(sessionId);
75
+ if (event.type === "session.opened") {
76
+ record ??= { version: 1, id: sessionId, rootId: root, status: "initializing", createdAt: now, updatedAt: now };
77
+ save(record, { rootId: root, session: event.session, status: "idle", lastError: void 0, activeTurnId: void 0 });
78
+ return;
79
+ }
80
+ if (!record) return;
81
+ if (event.type === "session.updated") save(record, { session: { ...record.session, ...event.session, ...event.session.parked ? {} : { parked: void 0 } } });
82
+ else if (event.type === "turn.started") save(record, { status: "running", activeTurnId: event.turnId, archived: void 0 });
83
+ else if (event.type === "turn.ended") save(record, { status: "idle", activeTurnId: void 0, ...event.state === "failed" ? { lastError: { message: event.error?.message ?? "Turn failed" } } : {} });
84
+ else if (event.type === "session.failed") save(record, { status: "error", lastError: event.error });
85
+ else if (event.type === "session.closed") save(record, { status: record.status === "error" ? "error" : "closed", activeTurnId: void 0 });
86
+ else if (event.type === "item" && sessionId === root && !record.title && event.item.kind === "user_message" && !event.item.clientMessageId?.startsWith("alp-")) {
87
+ save(record, { title: event.item.text.replace(/\s+/g, " ").trim().slice(0, 80) });
88
+ }
89
+ }
90
+ runtime.onEvent((original) => {
91
+ if (closing) return;
92
+ let envelope = original;
93
+ const { sessionId, event } = envelope;
94
+ if (event.type === "session.opened") {
95
+ const parent = event.session.parentId;
96
+ rootOf.set(sessionId, parent ? rootOf.get(parent) ?? parent : sessionId);
97
+ }
98
+ const root = rootOf.get(sessionId) ?? sessionId;
99
+ if (rootOf.has(sessionId)) {
100
+ envelope = keep(root, envelope);
101
+ const log2 = logs.get(root) ?? [];
102
+ log2.push(envelope);
103
+ if (log2.length > TREE_LOG_LIMIT) log2.splice(0, log2.length - TREE_LOG_LIMIT);
104
+ logs.set(root, log2);
105
+ track(sessionId, root, event);
106
+ }
107
+ for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
108
+ if (event.type === "session.closed" && sessionId === root) {
109
+ setImmediate(() => forget(root));
110
+ } else {
111
+ setImmediate(() => void reap(root));
112
+ }
113
+ });
114
+ async function restore() {
115
+ await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: true });
116
+ const loaded = await store.list();
117
+ await reconcileReceipts(loaded);
118
+ const now = Date.now();
119
+ const ended = { code: "daemon_restarted", message: "alpd stopped while this session was working" };
120
+ const epoch = `restart-${startedAt}`;
121
+ const continuing = new Set(runtime.recoverable().map((entry) => entry.assignmentId));
122
+ const reopen = [];
123
+ const byRoot = trees(loaded);
124
+ const removed = await expire(byRoot, now);
125
+ for (const [root, tree] of byRoot) {
126
+ const head = tree.find((record) => record.id === root);
127
+ if (removed.has(root)) continue;
128
+ if (head && resumable(head) && (head.status === "running" || tree.some((record) => continuing.has(record.id)))) reopen.push({ record: head, working: head.status === "running" });
129
+ if (tree.some((record) => LIVE.includes(record.status))) seen(root, await store.timeline(root));
130
+ for (const record of tree) {
131
+ records.set(record.id, record);
132
+ if (!LIVE.includes(record.status)) continue;
133
+ const envelope = (event) => ({ sessionId: record.id, epoch, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event });
134
+ if (record.activeTurnId) keep(root, envelope({ type: "turn.ended", turnId: record.activeTurnId, state: "failed", error: { message: ended.message, code: ended.code } }));
135
+ if (record.id === root) {
136
+ save(record, record.status === "idle" ? { status: "closed", activeTurnId: void 0 } : { status: "error", lastError: ended, activeTurnId: void 0 });
137
+ } else if (continuing.has(record.id) && reopen.some((entry) => entry.record.id === root)) {
138
+ save(record, { status: "closed", activeTurnId: void 0 });
139
+ } else {
140
+ keep(root, envelope({ type: "session.closed" }));
141
+ save(record, { status: "closed", lastError: ended, activeTurnId: void 0 });
142
+ if (runLogDir && !continuing.has(record.id)) {
143
+ const line = JSON.stringify({ ts: (/* @__PURE__ */ 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";
144
+ await mkdir(runLogDir, { recursive: true }).then(() => appendFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`), line)).catch(() => {
145
+ });
146
+ }
147
+ }
148
+ }
149
+ }
150
+ const reopened = new Set(reopen.map((entry) => entry.record.id));
151
+ for (const rootId of new Set(runtime.recoverable().map((entry) => entry.rootId))) {
152
+ if (!reopened.has(rootId)) await runtime.abandon(rootId, "its root session cannot be reopened").catch(() => {
153
+ });
154
+ }
155
+ for (const { record, working } of reopen) recovering.set(record.id, recoverTree(record, working));
156
+ }
157
+ function trees(list) {
158
+ const byRoot = /* @__PURE__ */ new Map();
159
+ for (const record of list) byRoot.set(record.rootId, [...byRoot.get(record.rootId) ?? [], record]);
160
+ return byRoot;
161
+ }
162
+ async function expire(byRoot, now = Date.now()) {
163
+ const removed = /* @__PURE__ */ new Set();
164
+ const receiptWritten = /* @__PURE__ */ new Map();
165
+ for (const { receipt, writtenAt } of await store.receipts()) {
166
+ const at = Date.parse(receipt.updatedAt);
167
+ receiptWritten.set(receipt.sessionId, Math.max(receiptWritten.get(receipt.sessionId) ?? 0, Number.isNaN(at) ? now : at, writtenAt));
168
+ }
169
+ const continuing = new Set(runtime.recoverable().map((entry) => entry.rootId));
170
+ for (const [root, tree] of byRoot) {
171
+ if (!tree.some((record) => record.id === root)) continue;
172
+ if (tree.some((record) => LIVE.includes(record.status))) continue;
173
+ if (now - Math.max(...tree.map((record) => Date.parse(record.updatedAt) || now)) <= RETENTION_MS) continue;
174
+ if (tree.some((record) => now - (receiptWritten.get(record.id) ?? 0) <= RECEIPT_RETENTION_MS)) continue;
175
+ if (continuing.has(root) || rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) continue;
176
+ const ids = tree.map((record) => record.id);
177
+ if (now - await store.writtenAt(ids) <= RETENTION_MS) continue;
178
+ if (rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) continue;
179
+ for (const id of ids) records.delete(id);
180
+ cursors.delete(root);
181
+ await store.remove(root, ids);
182
+ if (runLogDir) await unlink(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`)).catch(() => {
183
+ });
184
+ removed.add(root);
185
+ }
186
+ if (removed.size) recoveryLog.info(`retention removed ${removed.size} session tree${removed.size > 1 ? "s" : ""} unused for ${RETENTION_MS / 864e5} days`, { code: "ALP_RETENTION_REMOVED", trees: removed.size });
187
+ return removed;
188
+ }
189
+ async function sweep() {
190
+ if (closing || !store) return;
191
+ try {
192
+ await restored;
193
+ await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
194
+ await expire(trees(records.values()));
195
+ } catch (error) {
196
+ recoveryLog.warn("retention sweep failed", { code: "ALP_RETENTION_FAILED", error });
197
+ }
198
+ }
199
+ const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : void 0;
200
+ sweeper?.unref();
201
+ async function reconcileReceipts(loaded) {
202
+ const rootOfRecord = new Map(loaded.map((record) => [record.id, record.rootId]));
203
+ const timelines = /* @__PURE__ */ new Map();
204
+ for (const { key, receipt } of await store.receipts()) {
205
+ if (receipt.state !== "pending") continue;
206
+ const root = rootOfRecord.get(receipt.sessionId);
207
+ if (!root) continue;
208
+ if (!timelines.has(root)) timelines.set(root, await store.timeline(root).catch(() => []));
209
+ const answer = timelines.get(root).find(({ sessionId, event: event2 }) => sessionId === receipt.sessionId && (event2.type === "prompt.accepted" || event2.type === "prompt.failed") && event2.clientMessageId === receipt.clientMessageId);
210
+ if (!answer) continue;
211
+ const event = answer.event;
212
+ const outcome = event.type === "prompt.accepted" ? "accepted" : event.error.code === "outcome_unknown" ? "unknown" : "failed";
213
+ await store.putReceipt(key, { ...receipt, state: "completed", outcome, ...event.type === "prompt.failed" ? { error: event.error } : {}, reconciled: true, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).catch(() => {
214
+ });
215
+ }
216
+ }
217
+ function resumable(record) {
218
+ return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
219
+ }
220
+ async function recoverTree(record, working) {
221
+ const session = record.session;
222
+ try {
223
+ const stored = await treeLog(record.id);
224
+ seen(record.id, stored);
225
+ logs.set(record.id, [...stored]);
226
+ await runtime.open(record.id, {
227
+ ...record.spec,
228
+ persist: true,
229
+ restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
230
+ }, { history: "skip", delegation: record.delegation ?? true });
231
+ const outcomes = await runtime.recover(record.id, { continueRoot: working });
232
+ recoveryLog.info(`recovered ${record.id}: ${outcomes.map((outcome) => `${outcome.agent} ${outcome.outcome}`).join(", ") || "root"}`, { event: "recovered", sessionId: record.id, rootId: record.rootId });
233
+ } catch (error) {
234
+ recoveryLog.error(`could not recover ${record.id}`, { code: "ALP_RECOVERY_FAILED", sessionId: record.id, rootId: record.rootId, error });
235
+ await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {
236
+ });
237
+ } finally {
238
+ recovering.delete(record.id);
239
+ setImmediate(() => void reap(record.id));
240
+ }
241
+ }
242
+ function deliverOnce(sessionId, clientMessageId, fingerprint, send) {
243
+ const key = digest(["prompt", sessionId, clientMessageId]);
244
+ 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" });
245
+ const answer = (receipt, extra = {}) => ({ outcome: receipt.outcome ?? "accepted", ...receipt.error ? { error: receipt.error } : {}, ...extra });
246
+ const attempt = async () => {
247
+ let existing = unsaved.get(key);
248
+ if (!existing) {
249
+ try {
250
+ existing = await store.receipt(key);
251
+ } catch (error) {
252
+ throw persistenceFailed(`message ${clientMessageId}`, error);
253
+ }
254
+ }
255
+ if (existing) {
256
+ if (existing.state === "unreadable") throw unknown();
257
+ if (existing.fingerprint !== fingerprint) throw new RpcError(ERROR.conflict, `Message ${clientMessageId} was already sent with different content`, { reason: "key_conflict" });
258
+ if (existing.state === "pending" || existing.outcome === "unknown") throw unknown();
259
+ return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
260
+ }
261
+ const receipt = (state, changes = {}) => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
262
+ live(sessionId);
263
+ crashPoint("prompt.before-receipt");
264
+ try {
265
+ await store.putReceipt(key, receipt("pending"));
266
+ } catch (error) {
267
+ throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error);
268
+ }
269
+ crashPoint("prompt.after-receipt");
270
+ let reply = { outcome: "accepted" };
271
+ const stop = runtime.onEvent(({ sessionId: from, event }) => {
272
+ if (from !== sessionId) return;
273
+ if (event.type === "prompt.accepted" && event.clientMessageId === clientMessageId) reply = { outcome: "accepted" };
274
+ if (event.type === "prompt.failed" && event.clientMessageId === clientMessageId) reply = { outcome: event.error.code === "outcome_unknown" ? "unknown" : "failed", error: event.error };
275
+ });
276
+ try {
277
+ await send();
278
+ } catch (error) {
279
+ await store.removeReceipt(key).catch(() => {
280
+ });
281
+ throw error;
282
+ } finally {
283
+ stop();
284
+ }
285
+ const root = rootOf.get(sessionId) ?? sessionId;
286
+ const lost = await store.drain({ records: [sessionId], timelines: [root] });
287
+ crashPoint("prompt.after-send");
288
+ const done = receipt("completed", reply);
289
+ let durable = lost.length === 0;
290
+ try {
291
+ await store.putReceipt(key, done);
292
+ } catch {
293
+ unsaved.set(key, done);
294
+ durable = false;
295
+ }
296
+ crashPoint("prompt.after-completed");
297
+ if (reply.outcome === "unknown") throw unknown();
298
+ return answer(done, { durable });
299
+ };
300
+ const previous = delivering.get(key) ?? Promise.resolve();
301
+ const result = previous.catch(() => {
302
+ }).then(attempt);
303
+ delivering.set(key, result);
304
+ void result.finally(() => {
305
+ if (delivering.get(key) === result) delivering.delete(key);
306
+ }).catch(() => {
307
+ });
308
+ return result;
309
+ }
310
+ async function persisted(root) {
311
+ if (!store) return {};
312
+ return { durable: (await store.drain({ records: [root], timelines: [root] })).length === 0 };
313
+ }
314
+ function forget(root) {
315
+ if (runtime.snapshot(root)) return;
316
+ for (const [id, candidate] of rootOf) if (candidate === root) rootOf.delete(id);
317
+ logs.delete(root);
318
+ }
319
+ async function reap(root) {
320
+ if (closing || attached.get(root)?.size || recovering.has(root)) return false;
321
+ const session = runtime.snapshot(root);
322
+ if (!session || session.busy) return false;
323
+ await runtime.close(root).catch(() => {
324
+ });
325
+ return true;
326
+ }
327
+ function attach(connection, root) {
328
+ const set = attached.get(root) ?? /* @__PURE__ */ new Set();
329
+ set.add(connection);
330
+ attached.set(root, set);
331
+ connection.roots.add(root);
332
+ }
333
+ function detach(connection, root) {
334
+ attached.get(root)?.delete(connection);
335
+ if (!attached.get(root)?.size) attached.delete(root);
336
+ connection.roots.delete(root);
337
+ }
338
+ function summary(id) {
339
+ const record = records.get(id);
340
+ const live2 = runtime.snapshot(id);
341
+ const session = live2 ?? record?.session;
342
+ if (!session) return void 0;
343
+ const status = live2 ? live2.activeTurnId ? "running" : "idle" : record?.status === "error" ? "error" : "closed";
344
+ return { ...session, ...live2 ? {} : { busy: false, activeTurnId: void 0 }, status, title: record?.title, ...record?.archived ? { archived: true } : {}, lastError: record?.lastError, createdAt: record?.createdAt, updatedAt: record?.updatedAt };
345
+ }
346
+ function rootRecord(sessionId) {
347
+ if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
348
+ const record = records.get(sessionId);
349
+ if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
350
+ if (record.rootId !== record.id) throw new RpcError(-32602, "Only a root session can be renamed or archived");
351
+ return record;
352
+ }
353
+ function known(sessionId) {
354
+ const found = summary(sessionId);
355
+ if (!found) throw new RpcError(ERROR.notFound, "Session is not open");
356
+ return found;
357
+ }
358
+ function live(sessionId) {
359
+ const session = runtime.snapshot(sessionId);
360
+ if (!session) throw new RpcError(ERROR.notFound, "Session is not open");
361
+ return session;
362
+ }
363
+ async function treeLog(root) {
364
+ return logs.get(root) ?? await store?.timeline(root) ?? [];
365
+ }
366
+ function replayHistory(connection, root, log2, { children = true } = {}) {
367
+ const items = /* @__PURE__ */ new Map();
368
+ for (const envelope of log2) {
369
+ if (envelope.sessionId === root && envelope.event.type === "item") items.set(envelope.event.item.id, envelope);
370
+ }
371
+ for (const item of items.values()) deliver(connection, item);
372
+ if (children) {
373
+ for (const envelope of log2) if (envelope.sessionId !== root && current(envelope)) deliver(connection, envelope);
374
+ }
375
+ }
376
+ function current(envelope) {
377
+ return envelope.event.type !== "question" && envelope.event.type !== "question.resolved";
378
+ }
379
+ function announceQuestions(connection, root) {
380
+ for (const question of runtime.questions()) {
381
+ if (question.rootId !== root) continue;
382
+ deliver(connection, { sessionId: question.sessionId, epoch: `announce-${startedAt}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "question", question } });
383
+ }
384
+ }
385
+ function announce(connection, root, history) {
386
+ const log2 = logs.get(root) ?? [];
387
+ const sessions = runtime.list().filter((session) => (rootOf.get(session.id) ?? session.id) === root);
388
+ for (const session of sessions) {
389
+ const opened = log2.find((envelope2) => envelope2.sessionId === session.id && envelope2.event.type === "session.opened");
390
+ if (!opened || opened.event.type !== "session.opened") continue;
391
+ const seq = Math.max(...log2.filter((envelope2) => envelope2.sessionId === session.id).map((envelope2) => envelope2.seq));
392
+ const envelope = (event) => ({ sessionId: session.id, epoch: opened.epoch, seq, ts: (/* @__PURE__ */ new Date()).toISOString(), event });
393
+ deliver(connection, envelope({ ...opened.event, session }));
394
+ if (history === "replay" && session.id === root) replayHistory(connection, root, log2, { children: false });
395
+ deliver(connection, envelope({ type: "session.ready" }));
396
+ if (session.activeTurnId) deliver(connection, envelope({ type: "turn.started", turnId: session.activeTurnId, origin: "user" }));
397
+ }
398
+ announceQuestions(connection, root);
399
+ }
400
+ async function resume(connection, record, spec, history, delegation) {
401
+ const session = record.session;
402
+ if (record.rootId !== record.id) throw new RpcError(ERROR.failed, "Only root sessions can be resumed");
403
+ if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, "This session cannot be resumed");
404
+ const agent = spec.agent ?? spec.restore?.agent;
405
+ if (agent !== void 0 && agent !== session.agent) throw new RpcError(ERROR.failed, "Cannot resume a session as a different ALP agent");
406
+ const stored = await treeLog(record.id);
407
+ seen(record.id, stored);
408
+ logs.set(record.id, [...stored]);
409
+ attach(connection, record.id);
410
+ try {
411
+ const opened = await runtime.open(record.id, {
412
+ ...record.spec,
413
+ ...spec.mode !== void 0 ? { mode: spec.mode } : {},
414
+ ...spec.thinking !== void 0 ? { thinking: spec.thinking } : {},
415
+ persist: true,
416
+ restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
417
+ }, { history: stored.length ? "skip" : history, delegation: record.delegation ?? delegation });
418
+ if (history === "replay") replayHistory(connection, record.id, stored);
419
+ return opened;
420
+ } catch (error) {
421
+ detach(connection, record.id);
422
+ throw error;
423
+ }
424
+ }
425
+ const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
426
+ const extensionOwners = /* @__PURE__ */ new Map();
427
+ const handlers = {
428
+ "extension.register": async (connection, params) => {
429
+ const method = params?.method;
430
+ 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");
431
+ 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");
432
+ if (originalMethods.has(method) || extensionOwners.has(method) || Object.hasOwn(handlers, method)) throw new RpcError(ERROR.conflict, `${method} is already registered`);
433
+ if ((methodOwners.get(connection)?.size ?? 0) >= 128 || extensionOwners.size >= 1024) throw new RpcError(ERROR.conflict, "too many registered extension methods");
434
+ extensionOwners.set(method, connection);
435
+ if (!methodOwners.has(connection)) methodOwners.set(connection, /* @__PURE__ */ new Set());
436
+ methodOwners.get(connection).add(method);
437
+ handlers[method] = async (_connection, invokeParams) => {
438
+ const owner = extensionOwners.get(method);
439
+ if (!owner || !connections.has(owner)) {
440
+ delete handlers[method];
441
+ extensionOwners.delete(method);
442
+ throw new RpcError(ERROR.notFound, `${method} is not available`);
443
+ }
444
+ return invokeExtended(owner, _connection, method, invokeParams ?? {});
445
+ };
446
+ return { registered: method };
447
+ },
448
+ "extension.unregister": async (connection, params) => {
449
+ const method = params?.method;
450
+ if (typeof method !== "string" || !method.trim()) throw new RpcError(ERROR.protocol, "extension.unregister requires a method name");
451
+ const owner = extensionOwners.get(method);
452
+ if (!owner) throw new RpcError(ERROR.notFound, `${method} is not registered`);
453
+ if (owner !== connection) throw new RpcError(ERROR.conflict, `${method} is owned by another connection`);
454
+ delete handlers[method];
455
+ extensionOwners.delete(method);
456
+ const owned = methodOwners.get(connection);
457
+ owned?.delete(method);
458
+ return { unregistered: method };
459
+ },
460
+ "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() }),
461
+ "session.status"(_connection, { sessionId }) {
462
+ if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
463
+ const status = runtime.status(sessionId);
464
+ if (!status) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not live`);
465
+ return { status };
466
+ },
467
+ "session.message"(_connection, { sessionId, text }) {
468
+ runtime.message(sessionId, text);
469
+ return {};
470
+ },
471
+ /** The assignment log of a session's tree, from the run log. */
472
+ async "session.log"(_connection, { sessionId }) {
473
+ const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
474
+ if (!runLogDir) return { rootId: root, entries: [] };
475
+ const text = await readFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`), "utf8").catch(() => "");
476
+ const entries = text.split("\n").filter(Boolean).flatMap((line) => {
477
+ try {
478
+ return [JSON.parse(line)];
479
+ } catch {
480
+ return [];
481
+ }
482
+ });
483
+ return { rootId: root, entries };
484
+ },
485
+ "question.list"(_connection, { projectRoot } = {}) {
486
+ const questions = runtime.questions().filter((question) => projectRoot === void 0 || runtime.snapshot(question.rootId)?.projectRoot === projectRoot);
487
+ return { questions };
488
+ },
489
+ /** The project board: live claims, decisions and findings (ALPD §18). */
490
+ async "board.list"(_connection, { projectRoot } = {}) {
491
+ if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, "An absolute projectRoot is required");
492
+ return { pins: await runtime.board(projectRoot) };
493
+ },
494
+ /** Pauses delegation and wakes on a runtime, or everywhere (ALPD §29). */
495
+ "daemon.pause"(_connection, { runtime: kind, now = false, reason } = {}) {
496
+ try {
497
+ return runtime.pause({ ...kind === void 0 ? {} : { runtime: kind }, now: now === true, ...reason === void 0 ? {} : { reason } });
498
+ } catch (error) {
499
+ throw new RpcError(-32602, error?.message ?? String(error));
500
+ }
501
+ },
502
+ "daemon.resume"(_connection, { runtime: kind } = {}) {
503
+ try {
504
+ return runtime.resume(kind === void 0 ? {} : { runtime: kind });
505
+ } catch (error) {
506
+ throw new RpcError(-32602, error?.message ?? String(error));
507
+ }
508
+ },
509
+ "daemon.pauses"() {
510
+ return runtime.pauses();
511
+ },
512
+ "daemon.usage": (_connection, { refresh = false } = {}) => runtime.usage(refresh === true),
513
+ /** Asks a finished assignment, or the last one on a task, about its work (ALPD §27). */
514
+ async "assignment.recall"(_connection, { assignmentId, taskId, projectRoot, question } = {}) {
515
+ if (projectRoot !== void 0 && (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot))) throw new RpcError(-32602, "projectRoot must be absolute");
516
+ try {
517
+ return await runtime.recall({ assignmentId, taskId, projectRoot }, question);
518
+ } catch (error) {
519
+ throw new RpcError(ERROR.failed, error?.message ?? String(error));
520
+ }
521
+ },
522
+ "question.answer"(_connection, { questionId, text, dismiss = false, reason }) {
523
+ if (typeof questionId !== "string") throw new RpcError(-32602, "questionId is required");
524
+ if (dismiss !== true && typeof text !== "string") throw new RpcError(-32602, "text or dismiss is required");
525
+ const matches = runtime.questions().filter((question) => question.id === questionId || question.id.startsWith(questionId));
526
+ if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
527
+ runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason } : { text });
528
+ return { questionId: matches[0].id };
529
+ },
530
+ "daemon.shutdown": () => {
531
+ setImmediate(() => onShutdown?.());
532
+ return {};
533
+ },
534
+ "catalog.get": () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
535
+ async "session.create"(connection, { sessionId, spec, history = "skip", delegation = true, resume: resuming = false }) {
536
+ if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
537
+ if (sessionId !== void 0 && (typeof sessionId !== "string" || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, "Invalid session id");
538
+ if (history !== "replay" && history !== "skip") throw new RpcError(-32602, "history must be replay or skip");
539
+ const id = sessionId ?? `ses_${randomBytes(8).toString("hex")}`;
540
+ await recovering.get(id);
541
+ const existing = runtime.snapshot(id);
542
+ if (existing) {
543
+ const agent = spec.agent ?? spec.restore?.agent;
544
+ if (existing.parentId || agent !== void 0 && agent !== existing.agent) throw new RpcError(ERROR.failed, "Session is already open");
545
+ attach(connection, id);
546
+ announce(connection, id, history);
547
+ return { session: existing, attached: true };
548
+ }
549
+ const record = records.get(id);
550
+ if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
551
+ if (record) {
552
+ const session = await resume(connection, record, spec, history, delegation);
553
+ return { session, attached: false, resumed: true, ...await persisted(id) };
554
+ }
555
+ const { restore: _restore, ...kept } = spec;
556
+ const now = (/* @__PURE__ */ new Date()).toISOString();
557
+ const created = { version: 1, id, rootId: id, spec: kept, delegation, status: "initializing", createdAt: now, updatedAt: now };
558
+ records.set(id, created);
559
+ try {
560
+ await store?.put(created);
561
+ } catch (error) {
562
+ if (records.get(id) === created) records.delete(id);
563
+ throw persistenceFailed(`session ${id}; it was not started`, error);
564
+ }
565
+ attach(connection, id);
566
+ try {
567
+ const session = await runtime.open(id, spec, { history, delegation });
568
+ return { session, attached: false, ...await persisted(id) };
569
+ } catch (error) {
570
+ detach(connection, id);
571
+ records.delete(id);
572
+ await store?.remove(id, [id]);
573
+ throw error;
574
+ }
575
+ },
576
+ /** The team and main a new root would run with, and the teams it may choose (ALPD §60). */
577
+ async "session.preview"(_connection, { spec }) {
578
+ if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
579
+ return { preview: await runtime.preview(spec) };
580
+ },
581
+ /**
582
+ * Watches a tree. With `after`, the cursor of the last event a client has, only later
583
+ * events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
584
+ * with the whole timeline. The replay and the live events that follow are in cursor order.
585
+ */
586
+ async "session.attach"(connection, { sessionId, replay = true, after }) {
587
+ if (after !== void 0 && (!Number.isSafeInteger(after) || after < 0)) throw new RpcError(-32602, "after must be a cursor");
588
+ const found = known(sessionId);
589
+ const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
590
+ let stored = [];
591
+ if (replay || store && !cursors.has(root)) {
592
+ const memory = logs.get(root);
593
+ const covered = !!memory?.length && (memory[0].cursor ?? 1) <= (after ?? 0) + 1;
594
+ if (!covered) stored = store ? await store.timeline(root) : memory ?? [];
595
+ }
596
+ const live2 = logs.get(root) ?? [];
597
+ const tip = Math.max(cursors.get(root) ?? 0, stored.at(-1)?.cursor ?? 0, live2.at(-1)?.cursor ?? 0);
598
+ const first = replay ? [...stored, ...live2].find((envelope) => envelope.cursor !== void 0)?.cursor : void 0;
599
+ const reset = after !== void 0 && (after > tip || replay && after < tip && (first === void 0 || first > after + 1));
600
+ const from = reset ? 0 : after ?? 0;
601
+ attach(connection, root);
602
+ if (replay) {
603
+ let last = from;
604
+ for (const envelope of stored) if ((envelope.cursor ?? 0) > last) {
605
+ if (current(envelope)) deliver(connection, envelope);
606
+ last = envelope.cursor ?? last;
607
+ }
608
+ for (const envelope of live2) if ((envelope.cursor ?? 0) > last) {
609
+ if (current(envelope)) deliver(connection, envelope);
610
+ last = envelope.cursor ?? last;
611
+ }
612
+ }
613
+ announceQuestions(connection, root);
614
+ return { session: root === found.id ? found : summary(root), cursor: tip, ...reset ? { reset: true } : {} };
615
+ },
616
+ async "session.release"(connection, { sessionId }) {
617
+ const root = rootOf.get(sessionId) ?? sessionId;
618
+ detach(connection, root);
619
+ return { closed: await reap(root) };
620
+ },
621
+ async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content }) {
622
+ if (typeof clientMessageId !== "string" || !Array.isArray(content)) throw new RpcError(-32602, "clientMessageId and content are required");
623
+ if (delivery !== "auto" && delivery !== "steer") throw new RpcError(-32602, "delivery must be auto or steer");
624
+ const send = async () => {
625
+ live(sessionId);
626
+ await runtime.prompt(sessionId, { clientMessageId, delivery, content });
627
+ };
628
+ if (!store) {
629
+ await send();
630
+ return {};
631
+ }
632
+ return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
633
+ },
634
+ async "session.interrupt"(_connection, { sessionId }) {
635
+ await runtime.interrupt(sessionId);
636
+ return {};
637
+ },
638
+ async "session.configure"(_connection, { sessionId, mode }) {
639
+ return { session: await runtime.configure(sessionId, { mode }) };
640
+ },
641
+ async "session.close"(_connection, { sessionId }) {
642
+ await runtime.close(sessionId);
643
+ return {};
644
+ },
645
+ /** The user's name for a root, in place of its first prompt (ALPD §61). */
646
+ async "session.rename"(_connection, { sessionId, title }) {
647
+ if (typeof title !== "string" || !title.trim() || [...title].length > 200) throw new RpcError(-32602, "title must be 1 to 200 characters");
648
+ const record = rootRecord(sessionId);
649
+ const before = record.title;
650
+ Object.assign(record, { title: title.replace(/\s+/g, " ").trim() });
651
+ try {
652
+ await store?.put(record);
653
+ } catch (error) {
654
+ record.title = before;
655
+ throw persistenceFailed(`the name of ${record.id}`, error);
656
+ }
657
+ return { session: summary(record.id) };
658
+ },
659
+ /** Sets a root aside: it closes, with its tree, and leaves the lists until unarchived (ALPD §61). */
660
+ async "session.archive"(_connection, { sessionId, archived = true }) {
661
+ const record = rootRecord(sessionId);
662
+ if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
663
+ const before = record.archived;
664
+ Object.assign(record, { archived: archived === true ? true : void 0 });
665
+ try {
666
+ await store?.put(record);
667
+ } catch (error) {
668
+ record.archived = before;
669
+ throw persistenceFailed(`the archive state of ${record.id}`, error);
670
+ }
671
+ return { session: summary(record.id) };
672
+ },
673
+ "session.get"(_connection, { sessionId }) {
674
+ return { session: known(sessionId) };
675
+ },
676
+ "session.list"(_connection, { projectRoot, rootsOnly = false, includeClosed = false, includeArchived = false } = {}) {
677
+ const ids = /* @__PURE__ */ new Set([...runtime.list().map((session) => session.id), ...records.keys()]);
678
+ const sessions = [...ids].map(summary).filter((session) => !!session).filter((session) => includeClosed || session.status === "idle" || session.status === "running").filter((session) => includeArchived || !session.archived).filter((session) => !rootsOnly || !session.parentId).filter((session) => projectRoot === void 0 || session.projectRoot === projectRoot).sort((a, b) => Number(!!a.parentId) - Number(!!b.parentId) || (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
679
+ return { sessions };
680
+ }
681
+ };
682
+ for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
683
+ Object.setPrototypeOf(handlers, null);
684
+ const originalMethods = /* @__PURE__ */ new Set([...Object.keys(handlers), ...RPC_METHODS]);
685
+ const reservedNamespaces = new Set([...originalMethods].map((method) => method.split(".")[0]));
686
+ async function invokeExtended(owner, caller, method, params) {
687
+ if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, "too many pending extension calls");
688
+ const id = ++owner.nextId;
689
+ const invocation = { jsonrpc: "2.0", id, method: "extension.invoke", params: { method, params } };
690
+ if (Buffer.byteLength(encodeFrame(invocation), "utf8") > MAX_FRAME) throw new RpcError(-32600, "ALP daemon frame exceeds size limit");
691
+ return new Promise((resolve, reject) => {
692
+ const timer = setTimeout(() => {
693
+ owner.pending.delete(id);
694
+ reject(new RpcError(ERROR.failed, `${method} timed out`));
695
+ }, 3e4);
696
+ owner.pending.set(id, { resolve, reject, timer, caller });
697
+ try {
698
+ owner.send(invocation);
699
+ } catch (error) {
700
+ clearTimeout(timer);
701
+ owner.pending.delete(id);
702
+ reject(error);
703
+ }
704
+ });
705
+ }
706
+ async function health() {
707
+ const checks = [{ id: "accepting", ok: !closing, ...closing ? { code: "ALP_SHUTTING_DOWN", message: "alpd is shutting down" } : {} }];
708
+ if (store) {
709
+ const probe = await store.probe();
710
+ checks.push({ id: "state", ...probe });
711
+ const failing = store.failing();
712
+ 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` } : {} });
713
+ }
714
+ return { live: true, ready: checks.every((check) => check.ok), checks };
715
+ }
716
+ const capabilities = [CAPABILITY.attachAfter, CAPABILITY.extensionMethods, ...store ? [CAPABILITY.promptReceipts] : [], ...operations.capabilities];
717
+ function fits(response) {
718
+ if (frameBytes(response) <= MAX_FRAME) return response;
719
+ log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
720
+ 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" } } };
721
+ }
722
+ async function dispatch(connection, message, receivedBytes) {
723
+ const single = !!message && typeof message === "object" && !Array.isArray(message);
724
+ const { id, method, params } = single ? message : {};
725
+ const respond = (body) => connection.send(fits({ jsonrpc: "2.0", id: validId(id) ? id : null, ...body }));
726
+ try {
727
+ if (Array.isArray(message)) throw new RpcError(RPC_ERROR.invalidRequest, "Batch requests are not supported", { reason: "batch_unsupported" });
728
+ if (!single || message.jsonrpc !== "2.0") throw new RpcError(RPC_ERROR.invalidRequest, "Invalid request");
729
+ const oversized = (receivedBytes ?? frameBytes(message)) > MAX_FRAME;
730
+ if (!Object.prototype.hasOwnProperty.call(message, "method")) {
731
+ const hasResult = Object.prototype.hasOwnProperty.call(message, "result");
732
+ const hasError = Object.prototype.hasOwnProperty.call(message, "error");
733
+ if (id === void 0 || id === null || hasResult === hasError) return;
734
+ const waiter = connection.pending.get(id);
735
+ if (!waiter) return;
736
+ connection.pending.delete(id);
737
+ clearTimeout(waiter.timer);
738
+ if (oversized) {
739
+ waiter.reject(new RpcError(RPC_ERROR.invalidRequest, "ALP daemon frame exceeds size limit"));
740
+ return;
741
+ }
742
+ if (hasError) waiter.reject(new RpcError(message.error?.code ?? ERROR.failed, message.error?.message ?? "extension call failed", message.error?.data));
743
+ else waiter.resolve(message.result);
744
+ return;
745
+ }
746
+ if (oversized) throw new RpcError(RPC_ERROR.invalidRequest, "ALP daemon frame exceeds size limit", { reason: "frame_too_large" });
747
+ if (typeof method !== "string") throw new RpcError(RPC_ERROR.invalidRequest, "Invalid request");
748
+ if (id === void 0) {
749
+ log.debug("ignored a notification", { code: "ALP_IPC_NOTIFICATION_IGNORED", method });
750
+ return;
751
+ }
752
+ 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" });
753
+ if (params !== void 0 && (params === null || typeof params !== "object" || Array.isArray(params))) throw new RpcError(RPC_ERROR.invalidParams, "params must be an object", { reason: "invalid_params" });
754
+ if (method === "daemon.hello") {
755
+ 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] });
756
+ const issues2 = validateParams(method, params);
757
+ if (issues2.length) throw invalidParams(issues2);
758
+ connection.helloed = true;
759
+ respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, capabilities } });
760
+ return;
761
+ }
762
+ if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first", { reason: "hello_required" });
763
+ await restored;
764
+ if (!connections.has(connection)) return;
765
+ const handler = Object.hasOwn(handlers, method) ? handlers[method] : void 0;
766
+ if (!handler) throw new RpcError(RPC_ERROR.methodNotFound, `Unknown method '${method}'`);
767
+ const issues = validateParams(method, params);
768
+ if (issues?.length) throw invalidParams(issues);
769
+ respond({ result: await handler(connection, params ?? {}) });
770
+ } catch (error) {
771
+ const code = error instanceof RpcError ? error.code : /is not open/.test(String(error?.message)) ? ERROR.notFound : ERROR.failed;
772
+ const data = error instanceof RpcError && error.data !== void 0 ? { data: error.data } : {};
773
+ if (!(error instanceof RpcError) && code === ERROR.failed) log.warn(`${method} failed`, { code: "ALP_RPC_FAILED", requestId: id, sessionId: params?.sessionId, method, error });
774
+ else if (error instanceof RpcError && error.data?.reason === "persistence_failed") log.warn(`${method} failed`, { code: "ALP_PERSISTENCE_FAILED", requestId: id, sessionId: params?.sessionId, method, error });
775
+ respond({ error: { code, message: error instanceof Error ? error.message : String(error), ...data } });
776
+ }
777
+ }
778
+ const methodOwners = /* @__PURE__ */ new Map();
779
+ function disconnect(connection) {
780
+ const owned = methodOwners.get(connection);
781
+ if (owned) for (const method of owned) {
782
+ delete handlers[method];
783
+ extensionOwners.delete(method);
784
+ }
785
+ methodOwners.delete(connection);
786
+ for (const [id, waiting] of connection.pending) {
787
+ clearTimeout(waiting.timer);
788
+ waiting.reject(new Error("ALP daemon connection closed"));
789
+ }
790
+ connection.pending.clear();
791
+ for (const owner of connections) for (const [id, waiting] of owner.pending) {
792
+ if (waiting.caller !== connection) continue;
793
+ clearTimeout(waiting.timer);
794
+ owner.pending.delete(id);
795
+ waiting.reject(new Error("ALP daemon caller connection closed"));
796
+ }
797
+ connections.delete(connection);
798
+ for (const root of [...connection.roots]) {
799
+ detach(connection, root);
800
+ void reap(root);
801
+ }
802
+ }
803
+ const server = net.createServer((socket) => {
804
+ if (closing) {
805
+ socket.destroy();
806
+ return;
807
+ }
808
+ const connection = {
809
+ socket,
810
+ helloed: false,
811
+ roots: /* @__PURE__ */ new Set(),
812
+ send(message) {
813
+ if (!socket.destroyed) socket.write(encodeFrame(message));
814
+ },
815
+ nextId: 0,
816
+ pending: /* @__PURE__ */ new Map()
817
+ };
818
+ connections.add(connection);
819
+ let buffer = "";
820
+ let bytes = 0;
821
+ socket.setEncoding("utf8");
822
+ const tooLarge = () => {
823
+ log.warn("closed a connection that sent a frame over the size limit", { code: "ALP_IPC_FRAME_TOO_LARGE" });
824
+ buffer = "";
825
+ bytes = 0;
826
+ socket.destroy();
827
+ };
828
+ socket.on("data", (chunk) => {
829
+ buffer += chunk;
830
+ bytes += Buffer.byteLength(chunk, "utf8");
831
+ if (!chunk.includes("\n")) {
832
+ if (bytes >= MAX_FRAME) tooLarge();
833
+ return;
834
+ }
835
+ let start = 0;
836
+ for (let index = buffer.indexOf("\n", buffer.length - chunk.length); index >= 0; index = buffer.indexOf("\n", start)) {
837
+ const line = buffer.slice(start, index);
838
+ start = index + 1;
839
+ if (Buffer.byteLength(line, "utf8") + 1 > MAX_FRAME) {
840
+ tooLarge();
841
+ return;
842
+ }
843
+ if (!line.trim()) continue;
844
+ let message;
845
+ try {
846
+ message = JSON.parse(line);
847
+ } catch {
848
+ log.warn("a client sent a line that is not JSON", { code: "ALP_IPC_PARSE_ERROR", bytes: line.length });
849
+ connection.send({ jsonrpc: "2.0", id: null, error: { code: RPC_ERROR.parseError, message: "Parse error" } });
850
+ continue;
851
+ }
852
+ void dispatch(connection, message, Buffer.byteLength(line, "utf8") + 1);
853
+ }
854
+ buffer = buffer.slice(start);
855
+ bytes = Buffer.byteLength(buffer, "utf8");
856
+ if (bytes >= MAX_FRAME) tooLarge();
857
+ });
858
+ socket.on("error", (error) => log[error.code === "ECONNRESET" || error.code === "EPIPE" ? "debug" : "warn"]("a client connection failed", { code: "ALP_IPC_SOCKET_ERROR", error }));
859
+ socket.on("close", () => disconnect(connection));
860
+ });
861
+ return {
862
+ extend(method, handler, owner = null) {
863
+ if (typeof method !== "string" || !method.trim()) throw new Error("extend needs a method name");
864
+ if (originalMethods.has(method)) throw new Error(`${method} is a built-in method and cannot be overridden`);
865
+ if (Object.hasOwn(handlers, method)) throw new Error(`${method} is already registered`);
866
+ handlers[method] = async (_connection, params) => {
867
+ try {
868
+ const result = await handler(params ?? {});
869
+ return result === void 0 ? {} : result;
870
+ } catch (error) {
871
+ const message = error instanceof Error ? error.message : String(error);
872
+ throw new Error(message.length > 2e3 ? `${message.slice(0, 2e3)}...` : message);
873
+ }
874
+ };
875
+ if (owner) {
876
+ if (!methodOwners.has(owner)) methodOwners.set(owner, /* @__PURE__ */ new Set());
877
+ methodOwners.get(owner).add(method);
878
+ }
879
+ },
880
+ async listen() {
881
+ if (process.platform !== "win32") {
882
+ await assertPrivateDirectory(path.dirname(socketPath), { create: true });
883
+ const existing = await lstat(socketPath).catch((error) => {
884
+ if (error.code === "ENOENT") return void 0;
885
+ throw error;
886
+ });
887
+ if (existing) {
888
+ await assertPrivateSocket(socketPath);
889
+ const active = await new Promise((resolve, reject) => {
890
+ const probe = net.createConnection(socketPath);
891
+ probe.once("connect", () => {
892
+ probe.destroy();
893
+ resolve(true);
894
+ });
895
+ probe.once("error", (error) => {
896
+ probe.destroy();
897
+ if (error.code === "ECONNREFUSED") resolve(false);
898
+ else reject(error);
899
+ });
900
+ probe.setTimeout(1e3, () => {
901
+ probe.destroy();
902
+ reject(new Error("IPC endpoint probe timed out"));
903
+ });
904
+ });
905
+ if (active) throw new Error("IPC endpoint already in use by a running daemon");
906
+ const current2 = await assertPrivateSocket(socketPath);
907
+ if (!current2 || current2.dev !== existing.dev || current2.ino !== existing.ino) throw new Error("IPC endpoint changed during validation");
908
+ await unlink(socketPath);
909
+ }
910
+ }
911
+ const bindPath = process.platform === "win32" ? socketPath : path.join(path.dirname(socketPath), `.s${randomBytes(3).toString("hex")}`);
912
+ await new Promise((resolve, reject) => {
913
+ server.once("error", reject);
914
+ server.listen(bindPath, () => {
915
+ server.off("error", reject);
916
+ resolve();
917
+ });
918
+ });
919
+ if (process.platform !== "win32") {
920
+ try {
921
+ await chmod(bindPath, 384);
922
+ const info = await lstat(bindPath);
923
+ await rename(bindPath, socketPath);
924
+ socketIdentity = { dev: info.dev, ino: info.ino };
925
+ } catch (error) {
926
+ await new Promise((resolve) => server.close(() => resolve()));
927
+ throw error;
928
+ }
929
+ }
930
+ },
931
+ local() {
932
+ const events = /* @__PURE__ */ new Set();
933
+ const closes = /* @__PURE__ */ new Set();
934
+ const pending = /* @__PURE__ */ new Map();
935
+ let sequence = 0;
936
+ let ended = false;
937
+ const connection = {
938
+ helloed: true,
939
+ roots: /* @__PURE__ */ new Set(),
940
+ nextId: 0,
941
+ pending: /* @__PURE__ */ new Map(),
942
+ send(message) {
943
+ if (message.method === "event") {
944
+ for (const listener of events) listener(message.params);
945
+ return;
946
+ }
947
+ const waiter = pending.get(message.id);
948
+ if (!waiter) return;
949
+ pending.delete(message.id);
950
+ if (message.error) waiter.reject(new AlpRpcError(message.error));
951
+ else waiter.resolve(message.result);
952
+ }
953
+ };
954
+ connections.add(connection);
955
+ return {
956
+ request(method, params = {}) {
957
+ if (ended) return Promise.reject(new Error("ALP daemon connection closed"));
958
+ const id = ++sequence;
959
+ return new Promise((resolve, reject) => {
960
+ pending.set(id, { resolve, reject });
961
+ void dispatch(connection, { jsonrpc: "2.0", id, method, params });
962
+ });
963
+ },
964
+ onEvent(listener) {
965
+ events.add(listener);
966
+ return () => events.delete(listener);
967
+ },
968
+ onClose(listener) {
969
+ closes.add(listener);
970
+ return () => closes.delete(listener);
971
+ },
972
+ close() {
973
+ if (ended) return;
974
+ ended = true;
975
+ disconnect(connection);
976
+ const error = new Error("ALP daemon connection closed");
977
+ for (const waiter of pending.values()) waiter.reject(error);
978
+ pending.clear();
979
+ for (const listener of closes) listener(error);
980
+ closes.clear();
981
+ }
982
+ };
983
+ },
984
+ accept(send) {
985
+ const connection = { helloed: false, roots: /* @__PURE__ */ new Set(), send, nextId: 0, pending: /* @__PURE__ */ new Map() };
986
+ connections.add(connection);
987
+ let ended = false;
988
+ return {
989
+ receive(message) {
990
+ if (!ended) void dispatch(connection, message);
991
+ },
992
+ close() {
993
+ if (ended) return;
994
+ ended = true;
995
+ disconnect(connection);
996
+ }
997
+ };
998
+ },
999
+ async close() {
1000
+ closing = true;
1001
+ if (sweeper) clearInterval(sweeper);
1002
+ const stopped = new Promise((resolve) => server.close(() => resolve()));
1003
+ for (const connection of connections) connection.socket?.destroy();
1004
+ await stopped;
1005
+ if (socketIdentity) {
1006
+ const current2 = await lstat(socketPath).catch((error) => {
1007
+ if (error.code === "ENOENT") return void 0;
1008
+ throw error;
1009
+ });
1010
+ if (current2?.isSocket() && current2.dev === socketIdentity.dev && current2.ino === socketIdentity.ino) await unlink(socketPath);
1011
+ socketIdentity = void 0;
1012
+ }
1013
+ await store?.flush();
1014
+ }
1015
+ };
1016
+ }
1017
+ export {
1018
+ ERROR2 as ERROR,
1019
+ createDaemonServer
1020
+ };