@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/README.md +8 -2
- package/dist/alpd.js +38612 -0
- package/dist/build-manifest.json +81 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +8 -0
- package/dist/lock.d.ts +16 -0
- package/dist/lock.js +48 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +175 -0
- package/dist/server.d.ts +41 -0
- package/dist/server.js +718 -0
- package/dist/store.d.ts +47 -0
- package/dist/store.js +117 -0
- package/package.json +85 -4
- package/src/index.ts +5 -0
- package/src/lock.ts +56 -0
- package/src/main.ts +172 -0
- package/src/server.ts +812 -0
- package/src/store.ts +156 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,812 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { appendFile, chmod, mkdir, readFile, unlink } from 'node:fs/promises';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { AlpRpcError, MAX_FRAME, PROTOCOL_VERSION, ERROR, encodeFrame } from '@anhlp/alp-protocol';
|
|
6
|
+
export { ERROR } from '@anhlp/alp-protocol';
|
|
7
|
+
import { DEFAULT_MODEL, models, modes, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
|
|
8
|
+
import type { Receipt, SessionRecord, SessionStatus, Store } from './store.js';
|
|
9
|
+
import type { SessionSummary } from '@anhlp/alp-protocol/session';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* alpd's JSON-RPC surface over one shared runtime (plans/reference/ALPD.md §3, §6, §14).
|
|
13
|
+
* Clients attach to root sessions to receive the events of the whole tree. A root
|
|
14
|
+
* with no attached client is closed as soon as it is idle, so work started by a
|
|
15
|
+
* viewer finishes even after the viewer goes away. With a store, every session is
|
|
16
|
+
* recorded and every tree's events are kept, so a closed root can be resumed later.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RpcError extends Error {
|
|
22
|
+
constructor(public code: number, message: string, public data?: unknown) { super(message); }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A stable hash of JSON data, independent of key order (as Paseo's receipts). */
|
|
26
|
+
function digest(value: unknown) {
|
|
27
|
+
return createHash('sha256').update(JSON.stringify(value, (_key, candidate) =>
|
|
28
|
+
candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)
|
|
29
|
+
? Object.fromEntries(Object.entries(candidate).sort(([a], [b]) => a.localeCompare(b)))
|
|
30
|
+
: candidate)).digest('hex');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type Connection = {
|
|
34
|
+
socket?: net.Socket;
|
|
35
|
+
helloed: boolean;
|
|
36
|
+
roots: Set<string>;
|
|
37
|
+
send(message: unknown): void;
|
|
38
|
+
nextId: number;
|
|
39
|
+
pending: Map<number, { resolve(value: unknown): void; reject(error: Error): void; timer: NodeJS.Timeout }>;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** Retained events per live tree, for attach and replay. */
|
|
43
|
+
const TREE_LOG_LIMIT = 20_000;
|
|
44
|
+
const SESSION_ID = /^[\w.:-]{1,128}$/;
|
|
45
|
+
const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
46
|
+
const RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
47
|
+
const LIVE: SessionStatus[] = ['initializing', 'idle', 'running'];
|
|
48
|
+
|
|
49
|
+
/** What clients need from a daemon connection; AlpClient implements it over the socket. */
|
|
50
|
+
import type { DaemonConnection } from '@anhlp/alp-protocol/connection';
|
|
51
|
+
export type { DaemonConnection } from '@anhlp/alp-protocol/connection';
|
|
52
|
+
|
|
53
|
+
export type DaemonServer = {
|
|
54
|
+
listen(): Promise<void>;
|
|
55
|
+
/** An in-process connection that delivers events synchronously, for embedding. */
|
|
56
|
+
local(): DaemonConnection;
|
|
57
|
+
/**
|
|
58
|
+
* A connection over another transport, such as the web app's WebSocket (ALPD §61):
|
|
59
|
+
* it says daemon.hello first, as a socket client does, and gets JSON-RPC messages back through `send`.
|
|
60
|
+
*/
|
|
61
|
+
accept(send: (message: unknown) => void): { receive(message: unknown): void; close(): void };
|
|
62
|
+
/** Adds a method that lives outside the runtime, such as the web app's pairing link (ALPD §64). */
|
|
63
|
+
extend(method: string, handler: (params: any) => Promise<unknown> | unknown): void;
|
|
64
|
+
close(): Promise<void>;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** A session as clients list it: its last snapshot plus lifecycle (ALPD §18). The protocol owns the
|
|
68
|
+
* shape so every viewer agrees; re-exported here to keep `@anhlp/alp-daemon/server`'s API. */
|
|
69
|
+
export type { SessionSummary };
|
|
70
|
+
|
|
71
|
+
export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit }: {
|
|
72
|
+
runtime: AlpRuntime;
|
|
73
|
+
socketPath: string;
|
|
74
|
+
version: string;
|
|
75
|
+
onShutdown?: () => void;
|
|
76
|
+
/** Durable records and timelines; without it sessions live only in memory. */
|
|
77
|
+
store?: Store;
|
|
78
|
+
/** Where crash reconciliation reports assignments it ends, as the runtime does. */
|
|
79
|
+
runLogDir?: string;
|
|
80
|
+
/** How the previous alpd ended, for daemon.status. */
|
|
81
|
+
previousExit?: { kind: 'clean' | 'crash'; at?: string };
|
|
82
|
+
}): DaemonServer {
|
|
83
|
+
const connections = new Set<Connection>();
|
|
84
|
+
/** Root of every live session. */
|
|
85
|
+
const rootOf = new Map<string, string>();
|
|
86
|
+
const attached = new Map<string, Set<Connection>>();
|
|
87
|
+
const logs = new Map<string, Envelope[]>();
|
|
88
|
+
const records = new Map<string, SessionRecord & { activeTurnId?: string }>();
|
|
89
|
+
/** Prompt deliveries in flight, so a repeated clientMessageId waits for the first. */
|
|
90
|
+
const delivering = new Map<string, Promise<object>>();
|
|
91
|
+
let closing = false;
|
|
92
|
+
/** Roots alpd reopens after a restart; they stay open until their recovery has started. */
|
|
93
|
+
const recovering = new Set<string>();
|
|
94
|
+
const startedAt = new Date().toISOString();
|
|
95
|
+
const restored = store ? restore() : Promise.resolve();
|
|
96
|
+
|
|
97
|
+
const deliver = (connection: Connection, envelope: Envelope) => connection.send({ jsonrpc: '2.0', method: 'event', params: envelope });
|
|
98
|
+
|
|
99
|
+
function save(record: SessionRecord & { activeTurnId?: string }, changes: Partial<SessionRecord & { activeTurnId?: string }> = {}) {
|
|
100
|
+
Object.assign(record, changes, { updatedAt: new Date().toISOString() });
|
|
101
|
+
records.set(record.id, record);
|
|
102
|
+
void store?.put(record);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Lifecycle bookkeeping for one event; returns true when the record changed. */
|
|
106
|
+
function track(sessionId: string, root: string, event: AlpEvent) {
|
|
107
|
+
const now = new Date().toISOString();
|
|
108
|
+
let record = records.get(sessionId);
|
|
109
|
+
if (event.type === 'session.opened') {
|
|
110
|
+
record ??= { version: 1, id: sessionId, rootId: root, status: 'initializing', createdAt: now, updatedAt: now };
|
|
111
|
+
save(record, { rootId: root, session: event.session, status: 'idle', lastError: undefined, activeTurnId: undefined });
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (!record) return;
|
|
115
|
+
if (event.type === 'session.updated') save(record, { session: { ...record.session, ...event.session, ...(event.session.parked ? {} : { parked: undefined }) } });
|
|
116
|
+
// Work on an archived session brings it back.
|
|
117
|
+
else if (event.type === 'turn.started') save(record, { status: 'running', activeTurnId: event.turnId, archived: undefined });
|
|
118
|
+
else if (event.type === 'turn.ended') save(record, { status: 'idle', activeTurnId: undefined, ...(event.state === 'failed' ? { lastError: { message: event.error?.message ?? 'Turn failed' } } : {}) });
|
|
119
|
+
else if (event.type === 'session.failed') save(record, { status: 'error', lastError: event.error });
|
|
120
|
+
else if (event.type === 'session.closed') save(record, { status: record.status === 'error' ? 'error' : 'closed', activeTurnId: undefined });
|
|
121
|
+
else if (event.type === 'item' && sessionId === root && !record.title && event.item.kind === 'user_message' && !event.item.clientMessageId?.startsWith('alp-')) {
|
|
122
|
+
save(record, { title: event.item.text.replace(/\s+/g, ' ').trim().slice(0, 80) });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
runtime.onEvent(envelope => {
|
|
127
|
+
// While alpd stops, records keep what was running, so the next alpd continues it (ALPD §31).
|
|
128
|
+
if (closing) return;
|
|
129
|
+
const { sessionId, event } = envelope;
|
|
130
|
+
if (event.type === 'session.opened') {
|
|
131
|
+
const parent = event.session.parentId;
|
|
132
|
+
rootOf.set(sessionId, parent ? rootOf.get(parent) ?? parent : sessionId);
|
|
133
|
+
}
|
|
134
|
+
const root = rootOf.get(sessionId) ?? sessionId;
|
|
135
|
+
if (rootOf.has(sessionId)) {
|
|
136
|
+
const log = logs.get(root) ?? [];
|
|
137
|
+
log.push(envelope);
|
|
138
|
+
if (log.length > TREE_LOG_LIMIT) log.splice(0, log.length - TREE_LOG_LIMIT);
|
|
139
|
+
logs.set(root, log);
|
|
140
|
+
void store?.append(root, envelope);
|
|
141
|
+
track(sessionId, root, event);
|
|
142
|
+
}
|
|
143
|
+
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
144
|
+
if (event.type === 'session.closed' && sessionId === root) {
|
|
145
|
+
setImmediate(() => forget(root));
|
|
146
|
+
} else {
|
|
147
|
+
setImmediate(() => void reap(root));
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Loads records, settles sessions a crash or a stop left working, and prunes expired
|
|
153
|
+
* trees. Trees with assignments the runtime can continue, or whose root was working,
|
|
154
|
+
* are reopened afterwards (ALPD §31).
|
|
155
|
+
*/
|
|
156
|
+
async function restore() {
|
|
157
|
+
await store!.pruneReceipts(RECEIPT_RETENTION_MS);
|
|
158
|
+
const loaded = await store!.list();
|
|
159
|
+
const now = Date.now();
|
|
160
|
+
const ended = { code: 'daemon_restarted', message: 'alpd stopped while this session was working' };
|
|
161
|
+
const epoch = `restart-${startedAt}`;
|
|
162
|
+
const continuing = new Set(runtime.recoverable().map(entry => entry.assignmentId));
|
|
163
|
+
const reopen: Array<{ record: SessionRecord; working: boolean }> = [];
|
|
164
|
+
const byRoot = new Map<string, SessionRecord[]>();
|
|
165
|
+
for (const record of loaded) byRoot.set(record.rootId, [...(byRoot.get(record.rootId) ?? []), record]);
|
|
166
|
+
for (const [root, tree] of byRoot) {
|
|
167
|
+
const head = tree.find(record => record.id === root);
|
|
168
|
+
if (head && !LIVE.includes(head.status) && now - Date.parse(head.updatedAt) > RETENTION_MS) {
|
|
169
|
+
await store!.remove(root, tree.map(record => record.id));
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (head && resumable(head) && (head.status === 'running' || tree.some(record => continuing.has(record.id)))) reopen.push({ record: head, working: head.status === 'running' });
|
|
173
|
+
for (const record of tree as Array<SessionRecord & { activeTurnId?: string }>) {
|
|
174
|
+
records.set(record.id, record);
|
|
175
|
+
if (!LIVE.includes(record.status)) continue;
|
|
176
|
+
const envelope = (event: AlpEvent): Envelope => ({ sessionId: record.id, epoch, seq: 0, ts: new Date().toISOString(), event });
|
|
177
|
+
if (record.activeTurnId) void store!.append(root, envelope({ type: 'turn.ended', turnId: record.activeTurnId, state: 'failed', error: { message: ended.message } }));
|
|
178
|
+
if (record.id === root) {
|
|
179
|
+
save(record, record.status === 'idle' ? { status: 'closed', activeTurnId: undefined } : { status: 'error', lastError: ended, activeTurnId: undefined });
|
|
180
|
+
} else if (continuing.has(record.id) && reopen.some(entry => entry.record.id === root)) {
|
|
181
|
+
// The runtime reopens it under the same id; until then it is closed.
|
|
182
|
+
save(record, { status: 'closed', activeTurnId: undefined });
|
|
183
|
+
} else {
|
|
184
|
+
// Children never survive their runtime; their requester learns the assignment failed.
|
|
185
|
+
void store!.append(root, envelope({ type: 'session.closed' }));
|
|
186
|
+
save(record, { status: 'closed', lastError: ended, activeTurnId: undefined });
|
|
187
|
+
if (runLogDir && !continuing.has(record.id)) {
|
|
188
|
+
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';
|
|
189
|
+
await mkdir(runLogDir, { recursive: true }).then(() => appendFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`), line)).catch(() => {});
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
// Assignments whose tree cannot be reopened end now, and their tasks go back to open.
|
|
195
|
+
const reopened = new Set(reopen.map(entry => entry.record.id));
|
|
196
|
+
for (const rootId of new Set(runtime.recoverable().map(entry => entry.rootId))) {
|
|
197
|
+
if (!reopened.has(rootId)) await runtime.abandon(rootId, 'its root session cannot be reopened').catch(() => {});
|
|
198
|
+
}
|
|
199
|
+
for (const { record } of reopen) recovering.add(record.id);
|
|
200
|
+
void Promise.all(reopen.map(({ record, working }) => recoverTree(record, working)));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function resumable(record: SessionRecord) {
|
|
204
|
+
return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Reopens a root nobody watches yet and continues what it and its assignments were doing. */
|
|
208
|
+
async function recoverTree(record: SessionRecord, working: boolean) {
|
|
209
|
+
const session = record.session!;
|
|
210
|
+
try {
|
|
211
|
+
logs.set(record.id, [...await treeLog(record.id)]);
|
|
212
|
+
await runtime.open(record.id, {
|
|
213
|
+
...record.spec!,
|
|
214
|
+
persist: true,
|
|
215
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
|
|
216
|
+
}, { history: 'skip', delegation: record.delegation ?? true });
|
|
217
|
+
const outcomes = await runtime.recover(record.id, { continueRoot: working });
|
|
218
|
+
console.log(`${new Date().toISOString()} recovered ${record.id}: ${outcomes.map(outcome => `${outcome.agent} ${outcome.outcome}`).join(', ') || 'root'}`);
|
|
219
|
+
} catch (error: any) {
|
|
220
|
+
console.error(`${new Date().toISOString()} could not recover ${record.id}`, error);
|
|
221
|
+
await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {});
|
|
222
|
+
} finally {
|
|
223
|
+
recovering.delete(record.id);
|
|
224
|
+
setImmediate(() => void reap(record.id));
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Sends a prompt at most once per (session, clientMessageId), as Paseo's MessageReceipts:
|
|
230
|
+
* a repeat with the same content is a no-op, with other content a conflict, and a
|
|
231
|
+
* receipt left pending by a crash means the outcome is unknown.
|
|
232
|
+
*/
|
|
233
|
+
function deliverOnce(sessionId: string, clientMessageId: string, fingerprint: string, send: () => Promise<void>) {
|
|
234
|
+
const key = digest(['prompt', sessionId, clientMessageId]);
|
|
235
|
+
const attempt = async () => {
|
|
236
|
+
const existing = await store!.receipt(key);
|
|
237
|
+
if (existing) {
|
|
238
|
+
if (existing.fingerprint !== fingerprint) throw new RpcError(ERROR.conflict, `Message ${clientMessageId} was already sent with different content`, { reason: 'key_conflict' });
|
|
239
|
+
if (existing.state === 'completed') return { duplicate: true };
|
|
240
|
+
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' });
|
|
241
|
+
}
|
|
242
|
+
const receipt = (state: Receipt['state']): Receipt => ({ version: 1, sessionId, clientMessageId, fingerprint, state, updatedAt: new Date().toISOString() });
|
|
243
|
+
live(sessionId);
|
|
244
|
+
await store!.putReceipt(key, receipt('pending'));
|
|
245
|
+
await send();
|
|
246
|
+
await store!.putReceipt(key, receipt('completed'));
|
|
247
|
+
return {};
|
|
248
|
+
};
|
|
249
|
+
const previous = delivering.get(key) ?? Promise.resolve();
|
|
250
|
+
const result = previous.catch(() => {}).then(attempt);
|
|
251
|
+
delivering.set(key, result);
|
|
252
|
+
void result.finally(() => { if (delivering.get(key) === result) delivering.delete(key); }).catch(() => {});
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function forget(root: string) {
|
|
257
|
+
if (runtime.snapshot(root)) return;
|
|
258
|
+
for (const [id, candidate] of rootOf) if (candidate === root) rootOf.delete(id);
|
|
259
|
+
logs.delete(root);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Closes an idle root that no client watches. */
|
|
263
|
+
async function reap(root: string) {
|
|
264
|
+
if (closing || attached.get(root)?.size || recovering.has(root)) return false;
|
|
265
|
+
const session = runtime.snapshot(root);
|
|
266
|
+
if (!session || session.busy) return false;
|
|
267
|
+
await runtime.close(root).catch(() => {});
|
|
268
|
+
return true;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function attach(connection: Connection, root: string) {
|
|
272
|
+
const set = attached.get(root) ?? new Set();
|
|
273
|
+
set.add(connection);
|
|
274
|
+
attached.set(root, set);
|
|
275
|
+
connection.roots.add(root);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function detach(connection: Connection, root: string) {
|
|
279
|
+
attached.get(root)?.delete(connection);
|
|
280
|
+
if (!attached.get(root)?.size) attached.delete(root);
|
|
281
|
+
connection.roots.delete(root);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function summary(id: string): SessionSummary | undefined {
|
|
285
|
+
const record = records.get(id);
|
|
286
|
+
const live = runtime.snapshot(id);
|
|
287
|
+
const session = live ?? record?.session;
|
|
288
|
+
if (!session) return undefined;
|
|
289
|
+
const status: SessionStatus = live ? (live.activeTurnId ? 'running' : 'idle') : record?.status === 'error' ? 'error' : 'closed';
|
|
290
|
+
return { ...session, ...(live ? {} : { busy: false, activeTurnId: undefined }), status, title: record?.title, ...(record?.archived ? { archived: true } : {}), lastError: record?.lastError, createdAt: record?.createdAt, updatedAt: record?.updatedAt };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** The record of a root the user acts on. */
|
|
294
|
+
function rootRecord(sessionId: string) {
|
|
295
|
+
if (typeof sessionId !== 'string') throw new RpcError(-32602, 'sessionId is required');
|
|
296
|
+
const record = records.get(sessionId);
|
|
297
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
|
|
298
|
+
if (record.rootId !== record.id) throw new RpcError(-32602, 'Only a root session can be renamed or archived');
|
|
299
|
+
return record;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function known(sessionId: string) {
|
|
303
|
+
const found = summary(sessionId);
|
|
304
|
+
if (!found) throw new RpcError(ERROR.notFound, 'Session is not open');
|
|
305
|
+
return found;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function live(sessionId: string) {
|
|
309
|
+
const session = runtime.snapshot(sessionId);
|
|
310
|
+
if (!session) throw new RpcError(ERROR.notFound, 'Session is not open');
|
|
311
|
+
return session;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function treeLog(root: string) {
|
|
315
|
+
return logs.get(root) ?? await store?.timeline(root) ?? [];
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Delivers a tree's history: the root's latest items, then the children's events in their
|
|
320
|
+
* original order, so a grandchild opens while its parent is still open.
|
|
321
|
+
*/
|
|
322
|
+
function replayHistory(connection: Connection, root: string, log: Envelope[], { children = true } = {}) {
|
|
323
|
+
const items = new Map<string, Envelope>();
|
|
324
|
+
for (const envelope of log) {
|
|
325
|
+
if (envelope.sessionId === root && envelope.event.type === 'item') items.set(envelope.event.item.id, envelope);
|
|
326
|
+
}
|
|
327
|
+
for (const item of items.values()) deliver(connection, item);
|
|
328
|
+
if (children) for (const envelope of log) if (envelope.sessionId !== root && current(envelope)) deliver(connection, envelope);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Questions in a log are history; announceQuestions delivers the ones still waiting. */
|
|
332
|
+
function current(envelope: Envelope) {
|
|
333
|
+
return envelope.event.type !== 'question' && envelope.event.type !== 'question.resolved';
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function announceQuestions(connection: Connection, root: string) {
|
|
337
|
+
for (const question of runtime.questions()) {
|
|
338
|
+
if (question.rootId !== root) continue;
|
|
339
|
+
deliver(connection, { sessionId: question.sessionId, epoch: `announce-${startedAt}`, seq: 0, ts: new Date().toISOString(), event: { type: 'question', question } });
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Re-announces a live tree to a client that reopens its root: the root as it is now,
|
|
345
|
+
* its timeline when asked, then live children and running turns.
|
|
346
|
+
*/
|
|
347
|
+
function announce(connection: Connection, root: string, history: 'replay' | 'skip') {
|
|
348
|
+
const log = logs.get(root) ?? [];
|
|
349
|
+
const sessions = runtime.list().filter(session => (rootOf.get(session.id) ?? session.id) === root);
|
|
350
|
+
for (const session of sessions) {
|
|
351
|
+
const opened = log.find(envelope => envelope.sessionId === session.id && envelope.event.type === 'session.opened');
|
|
352
|
+
if (!opened || opened.event.type !== 'session.opened') continue;
|
|
353
|
+
const seq = Math.max(...log.filter(envelope => envelope.sessionId === session.id).map(envelope => envelope.seq));
|
|
354
|
+
const envelope = (event: Envelope['event']): Envelope => ({ sessionId: session.id, epoch: opened.epoch, seq, ts: new Date().toISOString(), event });
|
|
355
|
+
deliver(connection, envelope({ ...opened.event, session }));
|
|
356
|
+
if (history === 'replay' && session.id === root) replayHistory(connection, root, log, { children: false });
|
|
357
|
+
deliver(connection, envelope({ type: 'session.ready' }));
|
|
358
|
+
if (session.activeTurnId) deliver(connection, envelope({ type: 'turn.started', turnId: session.activeTurnId, origin: 'user' }));
|
|
359
|
+
}
|
|
360
|
+
announceQuestions(connection, root);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Reopens a closed root from its record: the native thread resumes, alpd replays the history. */
|
|
364
|
+
async function resume(connection: Connection, record: SessionRecord, spec: any, history: 'replay' | 'skip', delegation: boolean) {
|
|
365
|
+
const session = record.session;
|
|
366
|
+
if (record.rootId !== record.id) throw new RpcError(ERROR.failed, 'Only root sessions can be resumed');
|
|
367
|
+
if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, 'This session cannot be resumed');
|
|
368
|
+
const agent = spec.agent ?? spec.restore?.agent;
|
|
369
|
+
if (agent !== undefined && agent !== session.agent) throw new RpcError(ERROR.failed, 'Cannot resume a session as a different ALP agent');
|
|
370
|
+
const stored = await treeLog(record.id);
|
|
371
|
+
logs.set(record.id, [...stored]);
|
|
372
|
+
attach(connection, record.id);
|
|
373
|
+
try {
|
|
374
|
+
const opened = await runtime.open(record.id, {
|
|
375
|
+
...record.spec,
|
|
376
|
+
...(spec.mode !== undefined ? { mode: spec.mode } : {}),
|
|
377
|
+
...(spec.thinking !== undefined ? { thinking: spec.thinking } : {}),
|
|
378
|
+
persist: true,
|
|
379
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
|
|
380
|
+
}, { history: stored.length ? 'skip' : history, delegation: record.delegation ?? delegation });
|
|
381
|
+
if (history === 'replay') replayHistory(connection, record.id, stored);
|
|
382
|
+
return opened;
|
|
383
|
+
} catch (error) {
|
|
384
|
+
detach(connection, record.id);
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const extensionOwners = new Map<string, Connection>();
|
|
390
|
+
const handlers: Record<string, (connection: Connection, params: any) => Promise<unknown> | unknown> = {
|
|
391
|
+
'extension.register': async (connection, params) => {
|
|
392
|
+
const method = params?.method;
|
|
393
|
+
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');
|
|
394
|
+
if (typeof method !== 'string' || !method.trim()) throw new RpcError(ERROR.protocol, 'extension.register requires a method name');
|
|
395
|
+
if (originalMethods.has(method) || extensionOwners.has(method) || Object.hasOwn(handlers, method)) throw new RpcError(ERROR.conflict, `${method} is already registered`);
|
|
396
|
+
extensionOwners.set(method, connection);
|
|
397
|
+
if (!methodOwners.has(connection)) methodOwners.set(connection, new Set());
|
|
398
|
+
methodOwners.get(connection).add(method);
|
|
399
|
+
handlers[method] = async (_connection, invokeParams) => {
|
|
400
|
+
const owner = extensionOwners.get(method);
|
|
401
|
+
if (!owner || !connections.has(owner)) { delete handlers[method]; extensionOwners.delete(method); throw new RpcError(ERROR.notFound, `${method} is not available`); }
|
|
402
|
+
return invokeExtended(owner, method, invokeParams ?? {});
|
|
403
|
+
};
|
|
404
|
+
return { registered: method };
|
|
405
|
+
},
|
|
406
|
+
'extension.unregister': async (connection, params) => {
|
|
407
|
+
const method = params?.method;
|
|
408
|
+
if (typeof method !== 'string' || !method.trim()) throw new RpcError(ERROR.protocol, 'extension.unregister requires a method name');
|
|
409
|
+
const owner = extensionOwners.get(method);
|
|
410
|
+
if (!owner) throw new RpcError(ERROR.notFound, `${method} is not registered`);
|
|
411
|
+
if (owner !== connection) throw new RpcError(ERROR.conflict, `${method} is owned by another connection`);
|
|
412
|
+
delete handlers[method];
|
|
413
|
+
extensionOwners.delete(method);
|
|
414
|
+
const owned = methodOwners.get(connection);
|
|
415
|
+
owned?.delete(method);
|
|
416
|
+
return { unregistered: method };
|
|
417
|
+
},
|
|
418
|
+
'daemon.status': () => ({ pid: process.pid, startedAt, version, protocolVersion: PROTOCOL_VERSION, sessions: runtime.list().length, questions: runtime.questions().length, ...(previousExit ? { previousExit } : {}) }),
|
|
419
|
+
|
|
420
|
+
'session.status'(_connection, { sessionId }) {
|
|
421
|
+
if (typeof sessionId !== 'string') throw new RpcError(-32602, 'sessionId is required');
|
|
422
|
+
const status = runtime.status(sessionId);
|
|
423
|
+
if (!status) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not live`);
|
|
424
|
+
return { status };
|
|
425
|
+
},
|
|
426
|
+
|
|
427
|
+
'session.message'(_connection, { sessionId, text }) {
|
|
428
|
+
runtime.message(sessionId, text);
|
|
429
|
+
return {};
|
|
430
|
+
},
|
|
431
|
+
|
|
432
|
+
/** The assignment log of a session's tree, from the run log. */
|
|
433
|
+
async 'session.log'(_connection, { sessionId }) {
|
|
434
|
+
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
435
|
+
if (!runLogDir) return { rootId: root, entries: [] };
|
|
436
|
+
const text = await readFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`), 'utf8').catch(() => '');
|
|
437
|
+
const entries = text.split('\n').filter(Boolean).flatMap(line => { try { return [JSON.parse(line)]; } catch { return []; } });
|
|
438
|
+
return { rootId: root, entries };
|
|
439
|
+
},
|
|
440
|
+
|
|
441
|
+
'question.list'(_connection, { projectRoot } = {}) {
|
|
442
|
+
const questions = runtime.questions().filter(question => projectRoot === undefined || runtime.snapshot(question.rootId)?.projectRoot === projectRoot);
|
|
443
|
+
return { questions };
|
|
444
|
+
},
|
|
445
|
+
|
|
446
|
+
/** The project board: live claims, decisions and findings (ALPD §18). */
|
|
447
|
+
async 'board.list'(_connection, { projectRoot } = {}) {
|
|
448
|
+
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, 'An absolute projectRoot is required');
|
|
449
|
+
return { pins: await runtime.board(projectRoot) };
|
|
450
|
+
},
|
|
451
|
+
|
|
452
|
+
/** Pauses delegation and wakes on a runtime, or everywhere (ALPD §29). */
|
|
453
|
+
'daemon.pause'(_connection, { runtime: kind, now = false, reason } = {}) {
|
|
454
|
+
try { return runtime.pause({ ...(kind === undefined ? {} : { runtime: kind }), now: now === true, ...(reason === undefined ? {} : { reason }) }); }
|
|
455
|
+
catch (error: any) { throw new RpcError(-32602, error?.message ?? String(error)); }
|
|
456
|
+
},
|
|
457
|
+
|
|
458
|
+
'daemon.resume'(_connection, { runtime: kind } = {}) {
|
|
459
|
+
try { return runtime.resume(kind === undefined ? {} : { runtime: kind }); }
|
|
460
|
+
catch (error: any) { throw new RpcError(-32602, error?.message ?? String(error)); }
|
|
461
|
+
},
|
|
462
|
+
|
|
463
|
+
'daemon.pauses'() {
|
|
464
|
+
return runtime.pauses();
|
|
465
|
+
},
|
|
466
|
+
'daemon.usage': (_connection, { refresh = false } = {}) => runtime.usage(refresh === true),
|
|
467
|
+
|
|
468
|
+
/** Asks a finished assignment, or the last one on a task, about its work (ALPD §27). */
|
|
469
|
+
async 'assignment.recall'(_connection, { assignmentId, taskId, projectRoot, question } = {}) {
|
|
470
|
+
if (projectRoot !== undefined && (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot))) throw new RpcError(-32602, 'projectRoot must be absolute');
|
|
471
|
+
try {
|
|
472
|
+
return await runtime.recall({ assignmentId, taskId, projectRoot }, question);
|
|
473
|
+
} catch (error: any) {
|
|
474
|
+
throw new RpcError(ERROR.failed, error?.message ?? String(error));
|
|
475
|
+
}
|
|
476
|
+
},
|
|
477
|
+
|
|
478
|
+
'question.answer'(_connection, { questionId, text, dismiss = false, reason }) {
|
|
479
|
+
if (typeof questionId !== 'string') throw new RpcError(-32602, 'questionId is required');
|
|
480
|
+
if (dismiss !== true && typeof text !== 'string') throw new RpcError(-32602, 'text or dismiss is required');
|
|
481
|
+
// A unique prefix is enough, as in the CLI.
|
|
482
|
+
const matches = runtime.questions().filter(question => question.id === questionId || question.id.startsWith(questionId));
|
|
483
|
+
if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
|
|
484
|
+
runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason } : { text });
|
|
485
|
+
return { questionId: matches[0].id };
|
|
486
|
+
},
|
|
487
|
+
|
|
488
|
+
'daemon.shutdown': () => {
|
|
489
|
+
setImmediate(() => onShutdown?.());
|
|
490
|
+
return {};
|
|
491
|
+
},
|
|
492
|
+
|
|
493
|
+
'catalog.get': () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
|
|
494
|
+
|
|
495
|
+
async 'session.create'(connection, { sessionId, spec, history = 'skip', delegation = true, resume: resuming = false }) {
|
|
496
|
+
if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
|
|
497
|
+
if (sessionId !== undefined && (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, 'Invalid session id');
|
|
498
|
+
if (history !== 'replay' && history !== 'skip') throw new RpcError(-32602, 'history must be replay or skip');
|
|
499
|
+
const id = sessionId ?? `ses_${randomBytes(8).toString('hex')}`;
|
|
500
|
+
const existing = runtime.snapshot(id);
|
|
501
|
+
if (existing) {
|
|
502
|
+
// Reopening a root that kept working after its viewer left: attach to it.
|
|
503
|
+
const agent = spec.agent ?? spec.restore?.agent;
|
|
504
|
+
if (existing.parentId || (agent !== undefined && agent !== existing.agent)) throw new RpcError(ERROR.failed, 'Session is already open');
|
|
505
|
+
attach(connection, id);
|
|
506
|
+
announce(connection, id, history);
|
|
507
|
+
return { session: existing, attached: true };
|
|
508
|
+
}
|
|
509
|
+
const record = records.get(id);
|
|
510
|
+
if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
|
|
511
|
+
if (record) return { session: await resume(connection, record, spec, history, delegation), attached: false, resumed: true };
|
|
512
|
+
const { restore: _restore, ...kept } = spec;
|
|
513
|
+
const now = new Date().toISOString();
|
|
514
|
+
save({ version: 1, id, rootId: id, spec: kept, delegation, status: 'initializing', createdAt: now, updatedAt: now });
|
|
515
|
+
attach(connection, id);
|
|
516
|
+
try {
|
|
517
|
+
return { session: await runtime.open(id, spec, { history, delegation }), attached: false };
|
|
518
|
+
} catch (error) {
|
|
519
|
+
detach(connection, id);
|
|
520
|
+
records.delete(id);
|
|
521
|
+
await store?.remove(id, [id]);
|
|
522
|
+
throw error;
|
|
523
|
+
}
|
|
524
|
+
},
|
|
525
|
+
|
|
526
|
+
/** The team and main a new root would run with, and the teams it may choose (ALPD §60). */
|
|
527
|
+
async 'session.preview'(_connection, { spec }) {
|
|
528
|
+
if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
|
|
529
|
+
return { preview: await runtime.preview(spec) };
|
|
530
|
+
},
|
|
531
|
+
|
|
532
|
+
async 'session.attach'(connection, { sessionId, replay = true }) {
|
|
533
|
+
const found = known(sessionId);
|
|
534
|
+
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
535
|
+
attach(connection, root);
|
|
536
|
+
if (replay) for (const envelope of await treeLog(root)) if (current(envelope)) deliver(connection, envelope);
|
|
537
|
+
announceQuestions(connection, root);
|
|
538
|
+
return { session: root === found.id ? found : summary(root) };
|
|
539
|
+
},
|
|
540
|
+
|
|
541
|
+
async 'session.release'(connection, { sessionId }) {
|
|
542
|
+
const root = rootOf.get(sessionId) ?? sessionId;
|
|
543
|
+
detach(connection, root);
|
|
544
|
+
return { closed: await reap(root) };
|
|
545
|
+
},
|
|
546
|
+
|
|
547
|
+
async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content }) {
|
|
548
|
+
if (typeof clientMessageId !== 'string' || !Array.isArray(content)) throw new RpcError(-32602, 'clientMessageId and content are required');
|
|
549
|
+
if (delivery !== 'auto' && delivery !== 'steer') throw new RpcError(-32602, 'delivery must be auto or steer');
|
|
550
|
+
const send = async () => {
|
|
551
|
+
// Failures of an open session arrive as prompt.failed events; an unknown session has no watcher.
|
|
552
|
+
live(sessionId);
|
|
553
|
+
await runtime.prompt(sessionId, { clientMessageId, delivery, content });
|
|
554
|
+
};
|
|
555
|
+
if (!store) {
|
|
556
|
+
await send();
|
|
557
|
+
return {};
|
|
558
|
+
}
|
|
559
|
+
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
560
|
+
},
|
|
561
|
+
|
|
562
|
+
async 'session.interrupt'(_connection, { sessionId }) {
|
|
563
|
+
await runtime.interrupt(sessionId);
|
|
564
|
+
return {};
|
|
565
|
+
},
|
|
566
|
+
|
|
567
|
+
async 'session.configure'(_connection, { sessionId, mode }) {
|
|
568
|
+
return { session: await runtime.configure(sessionId, { mode }) };
|
|
569
|
+
},
|
|
570
|
+
|
|
571
|
+
async 'session.close'(_connection, { sessionId }) {
|
|
572
|
+
await runtime.close(sessionId);
|
|
573
|
+
return {};
|
|
574
|
+
},
|
|
575
|
+
|
|
576
|
+
/** The user's name for a root, in place of its first prompt (ALPD §61). */
|
|
577
|
+
'session.rename'(_connection, { sessionId, title }) {
|
|
578
|
+
if (typeof title !== 'string' || !title.trim() || title.length > 200) throw new RpcError(-32602, 'title must be 1 to 200 characters');
|
|
579
|
+
const record = rootRecord(sessionId);
|
|
580
|
+
// A name is not activity: the record keeps its time.
|
|
581
|
+
Object.assign(record, { title: title.replace(/\s+/g, ' ').trim() });
|
|
582
|
+
void store?.put(record);
|
|
583
|
+
return { session: summary(record.id) };
|
|
584
|
+
},
|
|
585
|
+
|
|
586
|
+
/** Sets a root aside: it closes, with its tree, and leaves the lists until unarchived (ALPD §61). */
|
|
587
|
+
async 'session.archive'(_connection, { sessionId, archived = true }) {
|
|
588
|
+
const record = rootRecord(sessionId);
|
|
589
|
+
if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
|
|
590
|
+
Object.assign(record, { archived: archived === true ? true : undefined });
|
|
591
|
+
void store?.put(record);
|
|
592
|
+
return { session: summary(record.id) };
|
|
593
|
+
},
|
|
594
|
+
|
|
595
|
+
'session.get'(_connection, { sessionId }) {
|
|
596
|
+
return { session: known(sessionId) };
|
|
597
|
+
},
|
|
598
|
+
|
|
599
|
+
'session.list'(_connection, { projectRoot, rootsOnly = false, includeClosed = false, includeArchived = false } = {}): { sessions: SessionSummary[] } {
|
|
600
|
+
const ids = new Set([...runtime.list().map(session => session.id), ...records.keys()]);
|
|
601
|
+
const sessions = [...ids].map(summary).filter((session): session is SessionSummary => !!session)
|
|
602
|
+
.filter(session => includeClosed || session.status === 'idle' || session.status === 'running')
|
|
603
|
+
.filter(session => includeArchived || !session.archived)
|
|
604
|
+
.filter(session => !rootsOnly || !session.parentId)
|
|
605
|
+
.filter(session => projectRoot === undefined || session.projectRoot === projectRoot)
|
|
606
|
+
.sort((a, b) => Number(!!a.parentId) - Number(!!b.parentId) || (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''));
|
|
607
|
+
return { sessions };
|
|
608
|
+
},
|
|
609
|
+
};
|
|
610
|
+
Object.setPrototypeOf(handlers, null);
|
|
611
|
+
const originalMethods = new Set(Object.keys(handlers));
|
|
612
|
+
originalMethods.add('daemon.hello');
|
|
613
|
+
|
|
614
|
+
async function invokeExtended(owner: Connection, method: string, params: any) {
|
|
615
|
+
if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, 'too many pending extension calls');
|
|
616
|
+
const id = ++owner.nextId;
|
|
617
|
+
return new Promise((resolve, reject) => {
|
|
618
|
+
const timer = setTimeout(() => {
|
|
619
|
+
owner.pending.delete(id);
|
|
620
|
+
reject(new RpcError(ERROR.failed, `${method} timed out`));
|
|
621
|
+
}, 30_000);
|
|
622
|
+
owner.pending.set(id, { resolve, reject, timer });
|
|
623
|
+
owner.send({ jsonrpc: '2.0', id, method: 'extension.invoke', params: { method, params } });
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
async function dispatch(connection: Connection, message: any) {
|
|
628
|
+
const { id, method, params } = message ?? {};
|
|
629
|
+
const respond = (body: object) => { if (id !== undefined && id !== null) connection.send({ jsonrpc: '2.0', id, ...body }); };
|
|
630
|
+
try {
|
|
631
|
+
// Validate the envelope before anything else: a frame that is not JSON-RPC 2.0 must never be
|
|
632
|
+
// correlated against (or consume) a pending extension call, however it is shaped.
|
|
633
|
+
if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0') throw new RpcError(-32600, 'Invalid request');
|
|
634
|
+
// A frame with no `method` property is a response to an outgoing extension.invoke. It must carry
|
|
635
|
+
// exactly one of result/error and an id; a malformed or unknown one is dropped, leaving any
|
|
636
|
+
// pending invocation intact (never mis-correlated, never leaked).
|
|
637
|
+
if (!Object.prototype.hasOwnProperty.call(message, 'method')) {
|
|
638
|
+
const hasResult = Object.prototype.hasOwnProperty.call(message, 'result');
|
|
639
|
+
const hasError = Object.prototype.hasOwnProperty.call(message, 'error');
|
|
640
|
+
if (id === undefined || id === null || hasResult === hasError) return;
|
|
641
|
+
const waiter = connection.pending.get(id);
|
|
642
|
+
if (!waiter) return;
|
|
643
|
+
connection.pending.delete(id);
|
|
644
|
+
clearTimeout(waiter.timer);
|
|
645
|
+
if (hasError) waiter.reject(new RpcError(message.error?.code ?? ERROR.failed, message.error?.message ?? 'extension call failed', message.error?.data));
|
|
646
|
+
else waiter.resolve(message.result);
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
if (typeof method !== 'string') throw new RpcError(-32600, 'Invalid request');
|
|
650
|
+
if (method === 'daemon.hello') {
|
|
651
|
+
if (params?.protocolVersion !== PROTOCOL_VERSION) throw new RpcError(ERROR.protocol, `ALP daemon speaks protocol ${PROTOCOL_VERSION}; restart it after upgrading (alp daemon restart)`);
|
|
652
|
+
connection.helloed = true;
|
|
653
|
+
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid } });
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
if (!connection.helloed) throw new RpcError(ERROR.protocol, 'daemon.hello is required first');
|
|
657
|
+
await restored;
|
|
658
|
+
const handler = Object.hasOwn(handlers, method) ? handlers[method] : undefined;
|
|
659
|
+
if (!handler) throw new RpcError(-32601, `Unknown method '${method}'`);
|
|
660
|
+
respond({ result: await handler(connection, params ?? {}) });
|
|
661
|
+
} catch (error) {
|
|
662
|
+
const code = error instanceof RpcError ? error.code : /is not open/.test(String((error as Error)?.message)) ? ERROR.notFound : ERROR.failed;
|
|
663
|
+
const data = error instanceof RpcError && error.data !== undefined ? { data: error.data } : {};
|
|
664
|
+
respond({ error: { code, message: error instanceof Error ? error.message : String(error), ...data } });
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const methodOwners = new Map();
|
|
669
|
+
function disconnect(connection: Connection) {
|
|
670
|
+
const owned = methodOwners.get(connection);
|
|
671
|
+
if (owned) for (const method of owned) { delete handlers[method]; extensionOwners.delete(method); }
|
|
672
|
+
methodOwners.delete(connection);
|
|
673
|
+
for (const [id, waiting] of connection.pending) { clearTimeout(waiting.timer); waiting.reject(new Error('ALP daemon connection closed')); }
|
|
674
|
+
connection.pending.clear();
|
|
675
|
+
connections.delete(connection);
|
|
676
|
+
for (const root of [...connection.roots]) {
|
|
677
|
+
detach(connection, root);
|
|
678
|
+
void reap(root);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
const server = net.createServer(socket => {
|
|
683
|
+
if (closing) { socket.destroy(); return; }
|
|
684
|
+
const connection: Connection = {
|
|
685
|
+
socket,
|
|
686
|
+
helloed: false,
|
|
687
|
+
roots: new Set(),
|
|
688
|
+
send(message) { if (!socket.destroyed) socket.write(encodeFrame(message)); },
|
|
689
|
+
nextId: 0,
|
|
690
|
+
pending: new Map(),
|
|
691
|
+
};
|
|
692
|
+
connections.add(connection);
|
|
693
|
+
let buffer = '';
|
|
694
|
+
socket.setEncoding('utf8');
|
|
695
|
+
socket.on('data', chunk => {
|
|
696
|
+
buffer += chunk;
|
|
697
|
+
if (buffer.length > MAX_FRAME) { socket.destroy(); return; }
|
|
698
|
+
for (let index = buffer.indexOf('\n'); index >= 0; index = buffer.indexOf('\n')) {
|
|
699
|
+
const line = buffer.slice(0, index);
|
|
700
|
+
buffer = buffer.slice(index + 1);
|
|
701
|
+
if (!line.trim()) continue;
|
|
702
|
+
let message;
|
|
703
|
+
try { message = JSON.parse(line); } catch { connection.send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); continue; }
|
|
704
|
+
void dispatch(connection, message);
|
|
705
|
+
}
|
|
706
|
+
});
|
|
707
|
+
socket.on('error', () => {});
|
|
708
|
+
socket.on('close', () => disconnect(connection));
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
return {
|
|
712
|
+
extend(method, handler, owner = null) {
|
|
713
|
+
if (typeof method !== 'string' || !method.trim()) throw new Error('extend needs a method name');
|
|
714
|
+
if (originalMethods.has(method)) throw new Error(`${method} is a built-in method and cannot be overridden`);
|
|
715
|
+
if (Object.hasOwn(handlers, method)) throw new Error(`${method} is already registered`);
|
|
716
|
+
handlers[method] = async (_connection, params) => {
|
|
717
|
+
try {
|
|
718
|
+
const result = await handler(params ?? {});
|
|
719
|
+
return result === undefined ? {} : result;
|
|
720
|
+
} catch (error) {
|
|
721
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
722
|
+
throw new Error(message.length > 2000 ? `${message.slice(0, 2000)}...` : message);
|
|
723
|
+
}
|
|
724
|
+
};
|
|
725
|
+
if (owner) {
|
|
726
|
+
if (!methodOwners.has(owner)) methodOwners.set(owner, new Set());
|
|
727
|
+
methodOwners.get(owner).add(method);
|
|
728
|
+
}
|
|
729
|
+
},
|
|
730
|
+
|
|
731
|
+
async listen() {
|
|
732
|
+
if (process.platform !== 'win32') await unlink(socketPath).catch(() => {});
|
|
733
|
+
await new Promise<void>((resolve, reject) => {
|
|
734
|
+
server.once('error', reject);
|
|
735
|
+
server.listen(socketPath, () => { server.off('error', reject); resolve(); });
|
|
736
|
+
});
|
|
737
|
+
if (process.platform !== 'win32') await chmod(socketPath, 0o600);
|
|
738
|
+
},
|
|
739
|
+
|
|
740
|
+
local() {
|
|
741
|
+
const events = new Set<(envelope: Envelope) => void>();
|
|
742
|
+
const closes = new Set<(error: Error) => void>();
|
|
743
|
+
const pending = new Map<number, { resolve: (value: any) => void; reject: (error: Error) => void }>();
|
|
744
|
+
let sequence = 0;
|
|
745
|
+
let ended = false;
|
|
746
|
+
const connection: Connection = {
|
|
747
|
+
helloed: true,
|
|
748
|
+
roots: new Set(),
|
|
749
|
+
nextId: 0,
|
|
750
|
+
pending: new Map(),
|
|
751
|
+
send(message: any) {
|
|
752
|
+
if (message.method === 'event') {
|
|
753
|
+
for (const listener of events) listener(message.params);
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
const waiter = pending.get(message.id);
|
|
757
|
+
if (!waiter) return;
|
|
758
|
+
pending.delete(message.id);
|
|
759
|
+
if (message.error) waiter.reject(new AlpRpcError(message.error));
|
|
760
|
+
else waiter.resolve(message.result);
|
|
761
|
+
},
|
|
762
|
+
};
|
|
763
|
+
connections.add(connection);
|
|
764
|
+
return {
|
|
765
|
+
request(method, params = {}) {
|
|
766
|
+
if (ended) return Promise.reject(new Error('ALP daemon connection closed'));
|
|
767
|
+
const id = ++sequence;
|
|
768
|
+
return new Promise((resolve, reject) => {
|
|
769
|
+
pending.set(id, { resolve, reject });
|
|
770
|
+
void dispatch(connection, { jsonrpc: '2.0', id, method, params });
|
|
771
|
+
});
|
|
772
|
+
},
|
|
773
|
+
onEvent(listener) { events.add(listener); return () => events.delete(listener); },
|
|
774
|
+
onClose(listener) { closes.add(listener); return () => closes.delete(listener); },
|
|
775
|
+
close() {
|
|
776
|
+
if (ended) return;
|
|
777
|
+
ended = true;
|
|
778
|
+
disconnect(connection);
|
|
779
|
+
// Match the socket client's teardown: in-flight requests fail and close listeners fire.
|
|
780
|
+
const error = new Error('ALP daemon connection closed');
|
|
781
|
+
for (const waiter of pending.values()) waiter.reject(error);
|
|
782
|
+
pending.clear();
|
|
783
|
+
for (const listener of closes) listener(error);
|
|
784
|
+
closes.clear();
|
|
785
|
+
},
|
|
786
|
+
};
|
|
787
|
+
},
|
|
788
|
+
|
|
789
|
+
accept(send) {
|
|
790
|
+
const connection: Connection = { helloed: false, roots: new Set(), send, nextId: 0, pending: new Map() };
|
|
791
|
+
connections.add(connection);
|
|
792
|
+
let ended = false;
|
|
793
|
+
return {
|
|
794
|
+
receive(message) { if (!ended) void dispatch(connection, message); },
|
|
795
|
+
close() {
|
|
796
|
+
if (ended) return;
|
|
797
|
+
ended = true;
|
|
798
|
+
disconnect(connection);
|
|
799
|
+
},
|
|
800
|
+
};
|
|
801
|
+
},
|
|
802
|
+
|
|
803
|
+
async close() {
|
|
804
|
+
closing = true;
|
|
805
|
+
const stopped = new Promise<void>(resolve => server.close(() => resolve()));
|
|
806
|
+
for (const connection of connections) connection.socket?.destroy();
|
|
807
|
+
await stopped;
|
|
808
|
+
if (process.platform !== 'win32') await unlink(socketPath).catch(() => {});
|
|
809
|
+
await store?.flush();
|
|
810
|
+
},
|
|
811
|
+
};
|
|
812
|
+
}
|