@anhlp/alp-daemon 0.0.0-stage → 0.10.0

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,718 @@
1
+ // packages/daemon/src/server.ts
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { appendFile, chmod, mkdir, readFile, unlink } from "node:fs/promises";
4
+ import net from "node:net";
5
+ import path from "node:path";
6
+ import { AlpRpcError, MAX_FRAME, PROTOCOL_VERSION, ERROR, encodeFrame } from "@anhlp/alp-protocol";
7
+ import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
8
+ import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
9
+ var RpcError = class extends Error {
10
+ constructor(code, message, data) {
11
+ super(message);
12
+ this.code = code;
13
+ this.data = data;
14
+ }
15
+ };
16
+ function digest(value) {
17
+ 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");
18
+ }
19
+ var TREE_LOG_LIMIT = 2e4;
20
+ var SESSION_ID = /^[\w.:-]{1,128}$/;
21
+ var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
22
+ var RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
23
+ var LIVE = ["initializing", "idle", "running"];
24
+ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit }) {
25
+ const connections = /* @__PURE__ */ new Set();
26
+ const rootOf = /* @__PURE__ */ new Map();
27
+ const attached = /* @__PURE__ */ new Map();
28
+ const logs = /* @__PURE__ */ new Map();
29
+ const records = /* @__PURE__ */ new Map();
30
+ const delivering = /* @__PURE__ */ new Map();
31
+ let closing = false;
32
+ const recovering = /* @__PURE__ */ new Set();
33
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
34
+ const restored = store ? restore() : Promise.resolve();
35
+ const deliver = (connection, envelope) => connection.send({ jsonrpc: "2.0", method: "event", params: envelope });
36
+ function save(record, changes = {}) {
37
+ Object.assign(record, changes, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
38
+ records.set(record.id, record);
39
+ void store?.put(record);
40
+ }
41
+ function track(sessionId, root, event) {
42
+ const now = (/* @__PURE__ */ new Date()).toISOString();
43
+ let record = records.get(sessionId);
44
+ if (event.type === "session.opened") {
45
+ record ??= { version: 1, id: sessionId, rootId: root, status: "initializing", createdAt: now, updatedAt: now };
46
+ save(record, { rootId: root, session: event.session, status: "idle", lastError: void 0, activeTurnId: void 0 });
47
+ return;
48
+ }
49
+ if (!record) return;
50
+ if (event.type === "session.updated") save(record, { session: { ...record.session, ...event.session, ...event.session.parked ? {} : { parked: void 0 } } });
51
+ else if (event.type === "turn.started") save(record, { status: "running", activeTurnId: event.turnId, archived: void 0 });
52
+ else if (event.type === "turn.ended") save(record, { status: "idle", activeTurnId: void 0, ...event.state === "failed" ? { lastError: { message: event.error?.message ?? "Turn failed" } } : {} });
53
+ else if (event.type === "session.failed") save(record, { status: "error", lastError: event.error });
54
+ else if (event.type === "session.closed") save(record, { status: record.status === "error" ? "error" : "closed", activeTurnId: void 0 });
55
+ else if (event.type === "item" && sessionId === root && !record.title && event.item.kind === "user_message" && !event.item.clientMessageId?.startsWith("alp-")) {
56
+ save(record, { title: event.item.text.replace(/\s+/g, " ").trim().slice(0, 80) });
57
+ }
58
+ }
59
+ runtime.onEvent((envelope) => {
60
+ if (closing) return;
61
+ const { sessionId, event } = envelope;
62
+ if (event.type === "session.opened") {
63
+ const parent = event.session.parentId;
64
+ rootOf.set(sessionId, parent ? rootOf.get(parent) ?? parent : sessionId);
65
+ }
66
+ const root = rootOf.get(sessionId) ?? sessionId;
67
+ if (rootOf.has(sessionId)) {
68
+ const log = logs.get(root) ?? [];
69
+ log.push(envelope);
70
+ if (log.length > TREE_LOG_LIMIT) log.splice(0, log.length - TREE_LOG_LIMIT);
71
+ logs.set(root, log);
72
+ void store?.append(root, envelope);
73
+ track(sessionId, root, event);
74
+ }
75
+ for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
76
+ if (event.type === "session.closed" && sessionId === root) {
77
+ setImmediate(() => forget(root));
78
+ } else {
79
+ setImmediate(() => void reap(root));
80
+ }
81
+ });
82
+ async function restore() {
83
+ await store.pruneReceipts(RECEIPT_RETENTION_MS);
84
+ const loaded = await store.list();
85
+ const now = Date.now();
86
+ const ended = { code: "daemon_restarted", message: "alpd stopped while this session was working" };
87
+ const epoch = `restart-${startedAt}`;
88
+ const continuing = new Set(runtime.recoverable().map((entry) => entry.assignmentId));
89
+ const reopen = [];
90
+ const byRoot = /* @__PURE__ */ new Map();
91
+ for (const record of loaded) byRoot.set(record.rootId, [...byRoot.get(record.rootId) ?? [], record]);
92
+ for (const [root, tree] of byRoot) {
93
+ const head = tree.find((record) => record.id === root);
94
+ if (head && !LIVE.includes(head.status) && now - Date.parse(head.updatedAt) > RETENTION_MS) {
95
+ await store.remove(root, tree.map((record) => record.id));
96
+ continue;
97
+ }
98
+ if (head && resumable(head) && (head.status === "running" || tree.some((record) => continuing.has(record.id)))) reopen.push({ record: head, working: head.status === "running" });
99
+ for (const record of tree) {
100
+ records.set(record.id, record);
101
+ if (!LIVE.includes(record.status)) continue;
102
+ const envelope = (event) => ({ sessionId: record.id, epoch, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event });
103
+ if (record.activeTurnId) void store.append(root, envelope({ type: "turn.ended", turnId: record.activeTurnId, state: "failed", error: { message: ended.message } }));
104
+ if (record.id === root) {
105
+ save(record, record.status === "idle" ? { status: "closed", activeTurnId: void 0 } : { status: "error", lastError: ended, activeTurnId: void 0 });
106
+ } else if (continuing.has(record.id) && reopen.some((entry) => entry.record.id === root)) {
107
+ save(record, { status: "closed", activeTurnId: void 0 });
108
+ } else {
109
+ void store.append(root, envelope({ type: "session.closed" }));
110
+ save(record, { status: "closed", lastError: ended, activeTurnId: void 0 });
111
+ if (runLogDir && !continuing.has(record.id)) {
112
+ 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";
113
+ await mkdir(runLogDir, { recursive: true }).then(() => appendFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`), line)).catch(() => {
114
+ });
115
+ }
116
+ }
117
+ }
118
+ }
119
+ const reopened = new Set(reopen.map((entry) => entry.record.id));
120
+ for (const rootId of new Set(runtime.recoverable().map((entry) => entry.rootId))) {
121
+ if (!reopened.has(rootId)) await runtime.abandon(rootId, "its root session cannot be reopened").catch(() => {
122
+ });
123
+ }
124
+ for (const { record } of reopen) recovering.add(record.id);
125
+ void Promise.all(reopen.map(({ record, working }) => recoverTree(record, working)));
126
+ }
127
+ function resumable(record) {
128
+ return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
129
+ }
130
+ async function recoverTree(record, working) {
131
+ const session = record.session;
132
+ try {
133
+ logs.set(record.id, [...await treeLog(record.id)]);
134
+ await runtime.open(record.id, {
135
+ ...record.spec,
136
+ persist: true,
137
+ restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
138
+ }, { history: "skip", delegation: record.delegation ?? true });
139
+ const outcomes = await runtime.recover(record.id, { continueRoot: working });
140
+ console.log(`${(/* @__PURE__ */ new Date()).toISOString()} recovered ${record.id}: ${outcomes.map((outcome) => `${outcome.agent} ${outcome.outcome}`).join(", ") || "root"}`);
141
+ } catch (error) {
142
+ console.error(`${(/* @__PURE__ */ new Date()).toISOString()} could not recover ${record.id}`, error);
143
+ await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {
144
+ });
145
+ } finally {
146
+ recovering.delete(record.id);
147
+ setImmediate(() => void reap(record.id));
148
+ }
149
+ }
150
+ function deliverOnce(sessionId, clientMessageId, fingerprint, send) {
151
+ const key = digest(["prompt", sessionId, clientMessageId]);
152
+ const attempt = async () => {
153
+ const existing = await store.receipt(key);
154
+ if (existing) {
155
+ if (existing.fingerprint !== fingerprint) throw new RpcError(ERROR.conflict, `Message ${clientMessageId} was already sent with different content`, { reason: "key_conflict" });
156
+ if (existing.state === "completed") return { duplicate: true };
157
+ throw new RpcError(ERROR.conflict, `alpd stopped while delivering message ${clientMessageId}; check the session, then send it again with a new id`, { reason: "outcome_unknown" });
158
+ }
159
+ const receipt = (state) => ({ version: 1, sessionId, clientMessageId, fingerprint, state, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
160
+ live(sessionId);
161
+ await store.putReceipt(key, receipt("pending"));
162
+ await send();
163
+ await store.putReceipt(key, receipt("completed"));
164
+ return {};
165
+ };
166
+ const previous = delivering.get(key) ?? Promise.resolve();
167
+ const result = previous.catch(() => {
168
+ }).then(attempt);
169
+ delivering.set(key, result);
170
+ void result.finally(() => {
171
+ if (delivering.get(key) === result) delivering.delete(key);
172
+ }).catch(() => {
173
+ });
174
+ return result;
175
+ }
176
+ function forget(root) {
177
+ if (runtime.snapshot(root)) return;
178
+ for (const [id, candidate] of rootOf) if (candidate === root) rootOf.delete(id);
179
+ logs.delete(root);
180
+ }
181
+ async function reap(root) {
182
+ if (closing || attached.get(root)?.size || recovering.has(root)) return false;
183
+ const session = runtime.snapshot(root);
184
+ if (!session || session.busy) return false;
185
+ await runtime.close(root).catch(() => {
186
+ });
187
+ return true;
188
+ }
189
+ function attach(connection, root) {
190
+ const set = attached.get(root) ?? /* @__PURE__ */ new Set();
191
+ set.add(connection);
192
+ attached.set(root, set);
193
+ connection.roots.add(root);
194
+ }
195
+ function detach(connection, root) {
196
+ attached.get(root)?.delete(connection);
197
+ if (!attached.get(root)?.size) attached.delete(root);
198
+ connection.roots.delete(root);
199
+ }
200
+ function summary(id) {
201
+ const record = records.get(id);
202
+ const live2 = runtime.snapshot(id);
203
+ const session = live2 ?? record?.session;
204
+ if (!session) return void 0;
205
+ const status = live2 ? live2.activeTurnId ? "running" : "idle" : record?.status === "error" ? "error" : "closed";
206
+ 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 };
207
+ }
208
+ function rootRecord(sessionId) {
209
+ if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
210
+ const record = records.get(sessionId);
211
+ if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
212
+ if (record.rootId !== record.id) throw new RpcError(-32602, "Only a root session can be renamed or archived");
213
+ return record;
214
+ }
215
+ function known(sessionId) {
216
+ const found = summary(sessionId);
217
+ if (!found) throw new RpcError(ERROR.notFound, "Session is not open");
218
+ return found;
219
+ }
220
+ function live(sessionId) {
221
+ const session = runtime.snapshot(sessionId);
222
+ if (!session) throw new RpcError(ERROR.notFound, "Session is not open");
223
+ return session;
224
+ }
225
+ async function treeLog(root) {
226
+ return logs.get(root) ?? await store?.timeline(root) ?? [];
227
+ }
228
+ function replayHistory(connection, root, log, { children = true } = {}) {
229
+ const items = /* @__PURE__ */ new Map();
230
+ for (const envelope of log) {
231
+ if (envelope.sessionId === root && envelope.event.type === "item") items.set(envelope.event.item.id, envelope);
232
+ }
233
+ for (const item of items.values()) deliver(connection, item);
234
+ if (children) {
235
+ for (const envelope of log) if (envelope.sessionId !== root && current(envelope)) deliver(connection, envelope);
236
+ }
237
+ }
238
+ function current(envelope) {
239
+ return envelope.event.type !== "question" && envelope.event.type !== "question.resolved";
240
+ }
241
+ function announceQuestions(connection, root) {
242
+ for (const question of runtime.questions()) {
243
+ if (question.rootId !== root) continue;
244
+ deliver(connection, { sessionId: question.sessionId, epoch: `announce-${startedAt}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "question", question } });
245
+ }
246
+ }
247
+ function announce(connection, root, history) {
248
+ const log = logs.get(root) ?? [];
249
+ const sessions = runtime.list().filter((session) => (rootOf.get(session.id) ?? session.id) === root);
250
+ for (const session of sessions) {
251
+ const opened = log.find((envelope2) => envelope2.sessionId === session.id && envelope2.event.type === "session.opened");
252
+ if (!opened || opened.event.type !== "session.opened") continue;
253
+ const seq = Math.max(...log.filter((envelope2) => envelope2.sessionId === session.id).map((envelope2) => envelope2.seq));
254
+ const envelope = (event) => ({ sessionId: session.id, epoch: opened.epoch, seq, ts: (/* @__PURE__ */ new Date()).toISOString(), event });
255
+ deliver(connection, envelope({ ...opened.event, session }));
256
+ if (history === "replay" && session.id === root) replayHistory(connection, root, log, { children: false });
257
+ deliver(connection, envelope({ type: "session.ready" }));
258
+ if (session.activeTurnId) deliver(connection, envelope({ type: "turn.started", turnId: session.activeTurnId, origin: "user" }));
259
+ }
260
+ announceQuestions(connection, root);
261
+ }
262
+ async function resume(connection, record, spec, history, delegation) {
263
+ const session = record.session;
264
+ if (record.rootId !== record.id) throw new RpcError(ERROR.failed, "Only root sessions can be resumed");
265
+ if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, "This session cannot be resumed");
266
+ const agent = spec.agent ?? spec.restore?.agent;
267
+ if (agent !== void 0 && agent !== session.agent) throw new RpcError(ERROR.failed, "Cannot resume a session as a different ALP agent");
268
+ const stored = await treeLog(record.id);
269
+ logs.set(record.id, [...stored]);
270
+ attach(connection, record.id);
271
+ try {
272
+ const opened = await runtime.open(record.id, {
273
+ ...record.spec,
274
+ ...spec.mode !== void 0 ? { mode: spec.mode } : {},
275
+ ...spec.thinking !== void 0 ? { thinking: spec.thinking } : {},
276
+ persist: true,
277
+ restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
278
+ }, { history: stored.length ? "skip" : history, delegation: record.delegation ?? delegation });
279
+ if (history === "replay") replayHistory(connection, record.id, stored);
280
+ return opened;
281
+ } catch (error) {
282
+ detach(connection, record.id);
283
+ throw error;
284
+ }
285
+ }
286
+ const extensionOwners = /* @__PURE__ */ new Map();
287
+ const handlers = {
288
+ "extension.register": async (connection, params) => {
289
+ const method = params?.method;
290
+ 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");
291
+ if (typeof method !== "string" || !method.trim()) throw new RpcError(ERROR.protocol, "extension.register requires a method name");
292
+ if (originalMethods.has(method) || extensionOwners.has(method) || Object.hasOwn(handlers, method)) throw new RpcError(ERROR.conflict, `${method} is already registered`);
293
+ extensionOwners.set(method, connection);
294
+ if (!methodOwners.has(connection)) methodOwners.set(connection, /* @__PURE__ */ new Set());
295
+ methodOwners.get(connection).add(method);
296
+ handlers[method] = async (_connection, invokeParams) => {
297
+ const owner = extensionOwners.get(method);
298
+ if (!owner || !connections.has(owner)) {
299
+ delete handlers[method];
300
+ extensionOwners.delete(method);
301
+ throw new RpcError(ERROR.notFound, `${method} is not available`);
302
+ }
303
+ return invokeExtended(owner, method, invokeParams ?? {});
304
+ };
305
+ return { registered: method };
306
+ },
307
+ "extension.unregister": async (connection, params) => {
308
+ const method = params?.method;
309
+ if (typeof method !== "string" || !method.trim()) throw new RpcError(ERROR.protocol, "extension.unregister requires a method name");
310
+ const owner = extensionOwners.get(method);
311
+ if (!owner) throw new RpcError(ERROR.notFound, `${method} is not registered`);
312
+ if (owner !== connection) throw new RpcError(ERROR.conflict, `${method} is owned by another connection`);
313
+ delete handlers[method];
314
+ extensionOwners.delete(method);
315
+ const owned = methodOwners.get(connection);
316
+ owned?.delete(method);
317
+ return { unregistered: method };
318
+ },
319
+ "daemon.status": () => ({ pid: process.pid, startedAt, version, protocolVersion: PROTOCOL_VERSION, sessions: runtime.list().length, questions: runtime.questions().length, ...previousExit ? { previousExit } : {} }),
320
+ "session.status"(_connection, { sessionId }) {
321
+ if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
322
+ const status = runtime.status(sessionId);
323
+ if (!status) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not live`);
324
+ return { status };
325
+ },
326
+ "session.message"(_connection, { sessionId, text }) {
327
+ runtime.message(sessionId, text);
328
+ return {};
329
+ },
330
+ /** The assignment log of a session's tree, from the run log. */
331
+ async "session.log"(_connection, { sessionId }) {
332
+ const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
333
+ if (!runLogDir) return { rootId: root, entries: [] };
334
+ const text = await readFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`), "utf8").catch(() => "");
335
+ const entries = text.split("\n").filter(Boolean).flatMap((line) => {
336
+ try {
337
+ return [JSON.parse(line)];
338
+ } catch {
339
+ return [];
340
+ }
341
+ });
342
+ return { rootId: root, entries };
343
+ },
344
+ "question.list"(_connection, { projectRoot } = {}) {
345
+ const questions = runtime.questions().filter((question) => projectRoot === void 0 || runtime.snapshot(question.rootId)?.projectRoot === projectRoot);
346
+ return { questions };
347
+ },
348
+ /** The project board: live claims, decisions and findings (ALPD §18). */
349
+ async "board.list"(_connection, { projectRoot } = {}) {
350
+ if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, "An absolute projectRoot is required");
351
+ return { pins: await runtime.board(projectRoot) };
352
+ },
353
+ /** Pauses delegation and wakes on a runtime, or everywhere (ALPD §29). */
354
+ "daemon.pause"(_connection, { runtime: kind, now = false, reason } = {}) {
355
+ try {
356
+ return runtime.pause({ ...kind === void 0 ? {} : { runtime: kind }, now: now === true, ...reason === void 0 ? {} : { reason } });
357
+ } catch (error) {
358
+ throw new RpcError(-32602, error?.message ?? String(error));
359
+ }
360
+ },
361
+ "daemon.resume"(_connection, { runtime: kind } = {}) {
362
+ try {
363
+ return runtime.resume(kind === void 0 ? {} : { runtime: kind });
364
+ } catch (error) {
365
+ throw new RpcError(-32602, error?.message ?? String(error));
366
+ }
367
+ },
368
+ "daemon.pauses"() {
369
+ return runtime.pauses();
370
+ },
371
+ "daemon.usage": (_connection, { refresh = false } = {}) => runtime.usage(refresh === true),
372
+ /** Asks a finished assignment, or the last one on a task, about its work (ALPD §27). */
373
+ async "assignment.recall"(_connection, { assignmentId, taskId, projectRoot, question } = {}) {
374
+ if (projectRoot !== void 0 && (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot))) throw new RpcError(-32602, "projectRoot must be absolute");
375
+ try {
376
+ return await runtime.recall({ assignmentId, taskId, projectRoot }, question);
377
+ } catch (error) {
378
+ throw new RpcError(ERROR.failed, error?.message ?? String(error));
379
+ }
380
+ },
381
+ "question.answer"(_connection, { questionId, text, dismiss = false, reason }) {
382
+ if (typeof questionId !== "string") throw new RpcError(-32602, "questionId is required");
383
+ if (dismiss !== true && typeof text !== "string") throw new RpcError(-32602, "text or dismiss is required");
384
+ const matches = runtime.questions().filter((question) => question.id === questionId || question.id.startsWith(questionId));
385
+ if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
386
+ runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason } : { text });
387
+ return { questionId: matches[0].id };
388
+ },
389
+ "daemon.shutdown": () => {
390
+ setImmediate(() => onShutdown?.());
391
+ return {};
392
+ },
393
+ "catalog.get": () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
394
+ async "session.create"(connection, { sessionId, spec, history = "skip", delegation = true, resume: resuming = false }) {
395
+ if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
396
+ if (sessionId !== void 0 && (typeof sessionId !== "string" || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, "Invalid session id");
397
+ if (history !== "replay" && history !== "skip") throw new RpcError(-32602, "history must be replay or skip");
398
+ const id = sessionId ?? `ses_${randomBytes(8).toString("hex")}`;
399
+ const existing = runtime.snapshot(id);
400
+ if (existing) {
401
+ const agent = spec.agent ?? spec.restore?.agent;
402
+ if (existing.parentId || agent !== void 0 && agent !== existing.agent) throw new RpcError(ERROR.failed, "Session is already open");
403
+ attach(connection, id);
404
+ announce(connection, id, history);
405
+ return { session: existing, attached: true };
406
+ }
407
+ const record = records.get(id);
408
+ if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
409
+ if (record) return { session: await resume(connection, record, spec, history, delegation), attached: false, resumed: true };
410
+ const { restore: _restore, ...kept } = spec;
411
+ const now = (/* @__PURE__ */ new Date()).toISOString();
412
+ save({ version: 1, id, rootId: id, spec: kept, delegation, status: "initializing", createdAt: now, updatedAt: now });
413
+ attach(connection, id);
414
+ try {
415
+ return { session: await runtime.open(id, spec, { history, delegation }), attached: false };
416
+ } catch (error) {
417
+ detach(connection, id);
418
+ records.delete(id);
419
+ await store?.remove(id, [id]);
420
+ throw error;
421
+ }
422
+ },
423
+ /** The team and main a new root would run with, and the teams it may choose (ALPD §60). */
424
+ async "session.preview"(_connection, { spec }) {
425
+ if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
426
+ return { preview: await runtime.preview(spec) };
427
+ },
428
+ async "session.attach"(connection, { sessionId, replay = true }) {
429
+ const found = known(sessionId);
430
+ const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
431
+ attach(connection, root);
432
+ if (replay) {
433
+ for (const envelope of await treeLog(root)) if (current(envelope)) deliver(connection, envelope);
434
+ }
435
+ announceQuestions(connection, root);
436
+ return { session: root === found.id ? found : summary(root) };
437
+ },
438
+ async "session.release"(connection, { sessionId }) {
439
+ const root = rootOf.get(sessionId) ?? sessionId;
440
+ detach(connection, root);
441
+ return { closed: await reap(root) };
442
+ },
443
+ async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content }) {
444
+ if (typeof clientMessageId !== "string" || !Array.isArray(content)) throw new RpcError(-32602, "clientMessageId and content are required");
445
+ if (delivery !== "auto" && delivery !== "steer") throw new RpcError(-32602, "delivery must be auto or steer");
446
+ const send = async () => {
447
+ live(sessionId);
448
+ await runtime.prompt(sessionId, { clientMessageId, delivery, content });
449
+ };
450
+ if (!store) {
451
+ await send();
452
+ return {};
453
+ }
454
+ return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
455
+ },
456
+ async "session.interrupt"(_connection, { sessionId }) {
457
+ await runtime.interrupt(sessionId);
458
+ return {};
459
+ },
460
+ async "session.configure"(_connection, { sessionId, mode }) {
461
+ return { session: await runtime.configure(sessionId, { mode }) };
462
+ },
463
+ async "session.close"(_connection, { sessionId }) {
464
+ await runtime.close(sessionId);
465
+ return {};
466
+ },
467
+ /** The user's name for a root, in place of its first prompt (ALPD §61). */
468
+ "session.rename"(_connection, { sessionId, title }) {
469
+ if (typeof title !== "string" || !title.trim() || title.length > 200) throw new RpcError(-32602, "title must be 1 to 200 characters");
470
+ const record = rootRecord(sessionId);
471
+ Object.assign(record, { title: title.replace(/\s+/g, " ").trim() });
472
+ void store?.put(record);
473
+ return { session: summary(record.id) };
474
+ },
475
+ /** Sets a root aside: it closes, with its tree, and leaves the lists until unarchived (ALPD §61). */
476
+ async "session.archive"(_connection, { sessionId, archived = true }) {
477
+ const record = rootRecord(sessionId);
478
+ if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
479
+ Object.assign(record, { archived: archived === true ? true : void 0 });
480
+ void store?.put(record);
481
+ return { session: summary(record.id) };
482
+ },
483
+ "session.get"(_connection, { sessionId }) {
484
+ return { session: known(sessionId) };
485
+ },
486
+ "session.list"(_connection, { projectRoot, rootsOnly = false, includeClosed = false, includeArchived = false } = {}) {
487
+ const ids = /* @__PURE__ */ new Set([...runtime.list().map((session) => session.id), ...records.keys()]);
488
+ 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 ?? ""));
489
+ return { sessions };
490
+ }
491
+ };
492
+ Object.setPrototypeOf(handlers, null);
493
+ const originalMethods = new Set(Object.keys(handlers));
494
+ originalMethods.add("daemon.hello");
495
+ async function invokeExtended(owner, method, params) {
496
+ if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, "too many pending extension calls");
497
+ const id = ++owner.nextId;
498
+ return new Promise((resolve, reject) => {
499
+ const timer = setTimeout(() => {
500
+ owner.pending.delete(id);
501
+ reject(new RpcError(ERROR.failed, `${method} timed out`));
502
+ }, 3e4);
503
+ owner.pending.set(id, { resolve, reject, timer });
504
+ owner.send({ jsonrpc: "2.0", id, method: "extension.invoke", params: { method, params } });
505
+ });
506
+ }
507
+ async function dispatch(connection, message) {
508
+ const { id, method, params } = message ?? {};
509
+ const respond = (body) => {
510
+ if (id !== void 0 && id !== null) connection.send({ jsonrpc: "2.0", id, ...body });
511
+ };
512
+ try {
513
+ if (!message || typeof message !== "object" || Array.isArray(message) || message.jsonrpc !== "2.0") throw new RpcError(-32600, "Invalid request");
514
+ if (!Object.prototype.hasOwnProperty.call(message, "method")) {
515
+ const hasResult = Object.prototype.hasOwnProperty.call(message, "result");
516
+ const hasError = Object.prototype.hasOwnProperty.call(message, "error");
517
+ if (id === void 0 || id === null || hasResult === hasError) return;
518
+ const waiter = connection.pending.get(id);
519
+ if (!waiter) return;
520
+ connection.pending.delete(id);
521
+ clearTimeout(waiter.timer);
522
+ if (hasError) waiter.reject(new RpcError(message.error?.code ?? ERROR.failed, message.error?.message ?? "extension call failed", message.error?.data));
523
+ else waiter.resolve(message.result);
524
+ return;
525
+ }
526
+ if (typeof method !== "string") throw new RpcError(-32600, "Invalid request");
527
+ if (method === "daemon.hello") {
528
+ if (params?.protocolVersion !== PROTOCOL_VERSION) throw new RpcError(ERROR.protocol, `ALP daemon speaks protocol ${PROTOCOL_VERSION}; restart it after upgrading (alp daemon restart)`);
529
+ connection.helloed = true;
530
+ respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid } });
531
+ return;
532
+ }
533
+ if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first");
534
+ await restored;
535
+ const handler = Object.hasOwn(handlers, method) ? handlers[method] : void 0;
536
+ if (!handler) throw new RpcError(-32601, `Unknown method '${method}'`);
537
+ respond({ result: await handler(connection, params ?? {}) });
538
+ } catch (error) {
539
+ const code = error instanceof RpcError ? error.code : /is not open/.test(String(error?.message)) ? ERROR.notFound : ERROR.failed;
540
+ const data = error instanceof RpcError && error.data !== void 0 ? { data: error.data } : {};
541
+ respond({ error: { code, message: error instanceof Error ? error.message : String(error), ...data } });
542
+ }
543
+ }
544
+ const methodOwners = /* @__PURE__ */ new Map();
545
+ function disconnect(connection) {
546
+ const owned = methodOwners.get(connection);
547
+ if (owned) for (const method of owned) {
548
+ delete handlers[method];
549
+ extensionOwners.delete(method);
550
+ }
551
+ methodOwners.delete(connection);
552
+ for (const [id, waiting] of connection.pending) {
553
+ clearTimeout(waiting.timer);
554
+ waiting.reject(new Error("ALP daemon connection closed"));
555
+ }
556
+ connection.pending.clear();
557
+ connections.delete(connection);
558
+ for (const root of [...connection.roots]) {
559
+ detach(connection, root);
560
+ void reap(root);
561
+ }
562
+ }
563
+ const server = net.createServer((socket) => {
564
+ if (closing) {
565
+ socket.destroy();
566
+ return;
567
+ }
568
+ const connection = {
569
+ socket,
570
+ helloed: false,
571
+ roots: /* @__PURE__ */ new Set(),
572
+ send(message) {
573
+ if (!socket.destroyed) socket.write(encodeFrame(message));
574
+ },
575
+ nextId: 0,
576
+ pending: /* @__PURE__ */ new Map()
577
+ };
578
+ connections.add(connection);
579
+ let buffer = "";
580
+ socket.setEncoding("utf8");
581
+ socket.on("data", (chunk) => {
582
+ buffer += chunk;
583
+ if (buffer.length > MAX_FRAME) {
584
+ socket.destroy();
585
+ return;
586
+ }
587
+ for (let index = buffer.indexOf("\n"); index >= 0; index = buffer.indexOf("\n")) {
588
+ const line = buffer.slice(0, index);
589
+ buffer = buffer.slice(index + 1);
590
+ if (!line.trim()) continue;
591
+ let message;
592
+ try {
593
+ message = JSON.parse(line);
594
+ } catch {
595
+ connection.send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
596
+ continue;
597
+ }
598
+ void dispatch(connection, message);
599
+ }
600
+ });
601
+ socket.on("error", () => {
602
+ });
603
+ socket.on("close", () => disconnect(connection));
604
+ });
605
+ return {
606
+ extend(method, handler, owner = null) {
607
+ if (typeof method !== "string" || !method.trim()) throw new Error("extend needs a method name");
608
+ if (originalMethods.has(method)) throw new Error(`${method} is a built-in method and cannot be overridden`);
609
+ if (Object.hasOwn(handlers, method)) throw new Error(`${method} is already registered`);
610
+ handlers[method] = async (_connection, params) => {
611
+ try {
612
+ const result = await handler(params ?? {});
613
+ return result === void 0 ? {} : result;
614
+ } catch (error) {
615
+ const message = error instanceof Error ? error.message : String(error);
616
+ throw new Error(message.length > 2e3 ? `${message.slice(0, 2e3)}...` : message);
617
+ }
618
+ };
619
+ if (owner) {
620
+ if (!methodOwners.has(owner)) methodOwners.set(owner, /* @__PURE__ */ new Set());
621
+ methodOwners.get(owner).add(method);
622
+ }
623
+ },
624
+ async listen() {
625
+ if (process.platform !== "win32") await unlink(socketPath).catch(() => {
626
+ });
627
+ await new Promise((resolve, reject) => {
628
+ server.once("error", reject);
629
+ server.listen(socketPath, () => {
630
+ server.off("error", reject);
631
+ resolve();
632
+ });
633
+ });
634
+ if (process.platform !== "win32") await chmod(socketPath, 384);
635
+ },
636
+ local() {
637
+ const events = /* @__PURE__ */ new Set();
638
+ const closes = /* @__PURE__ */ new Set();
639
+ const pending = /* @__PURE__ */ new Map();
640
+ let sequence = 0;
641
+ let ended = false;
642
+ const connection = {
643
+ helloed: true,
644
+ roots: /* @__PURE__ */ new Set(),
645
+ nextId: 0,
646
+ pending: /* @__PURE__ */ new Map(),
647
+ send(message) {
648
+ if (message.method === "event") {
649
+ for (const listener of events) listener(message.params);
650
+ return;
651
+ }
652
+ const waiter = pending.get(message.id);
653
+ if (!waiter) return;
654
+ pending.delete(message.id);
655
+ if (message.error) waiter.reject(new AlpRpcError(message.error));
656
+ else waiter.resolve(message.result);
657
+ }
658
+ };
659
+ connections.add(connection);
660
+ return {
661
+ request(method, params = {}) {
662
+ if (ended) return Promise.reject(new Error("ALP daemon connection closed"));
663
+ const id = ++sequence;
664
+ return new Promise((resolve, reject) => {
665
+ pending.set(id, { resolve, reject });
666
+ void dispatch(connection, { jsonrpc: "2.0", id, method, params });
667
+ });
668
+ },
669
+ onEvent(listener) {
670
+ events.add(listener);
671
+ return () => events.delete(listener);
672
+ },
673
+ onClose(listener) {
674
+ closes.add(listener);
675
+ return () => closes.delete(listener);
676
+ },
677
+ close() {
678
+ if (ended) return;
679
+ ended = true;
680
+ disconnect(connection);
681
+ const error = new Error("ALP daemon connection closed");
682
+ for (const waiter of pending.values()) waiter.reject(error);
683
+ pending.clear();
684
+ for (const listener of closes) listener(error);
685
+ closes.clear();
686
+ }
687
+ };
688
+ },
689
+ accept(send) {
690
+ const connection = { helloed: false, roots: /* @__PURE__ */ new Set(), send, nextId: 0, pending: /* @__PURE__ */ new Map() };
691
+ connections.add(connection);
692
+ let ended = false;
693
+ return {
694
+ receive(message) {
695
+ if (!ended) void dispatch(connection, message);
696
+ },
697
+ close() {
698
+ if (ended) return;
699
+ ended = true;
700
+ disconnect(connection);
701
+ }
702
+ };
703
+ },
704
+ async close() {
705
+ closing = true;
706
+ const stopped = new Promise((resolve) => server.close(() => resolve()));
707
+ for (const connection of connections) connection.socket?.destroy();
708
+ await stopped;
709
+ if (process.platform !== "win32") await unlink(socketPath).catch(() => {
710
+ });
711
+ await store?.flush();
712
+ }
713
+ };
714
+ }
715
+ export {
716
+ ERROR2 as ERROR,
717
+ createDaemonServer
718
+ };