@anhlp/alp-daemon 0.0.0-beta.1 → 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 +0 -2
- package/dist/alpd.js +1176 -3617
- package/dist/build-manifest.json +1 -28
- package/dist/lock.d.ts +0 -5
- package/dist/lock.js +17 -11
- package/dist/main.js +34 -97
- package/dist/server.d.ts +1 -8
- package/dist/server.js +91 -393
- package/dist/store.d.ts +6 -67
- package/dist/store.js +29 -191
- package/package.json +9 -16
- package/src/lock.ts +20 -17
- package/src/main.ts +24 -102
- package/src/server.ts +75 -422
- package/src/store.ts +27 -207
- package/LICENSE +0 -202
- package/NOTICE +0 -7
- package/dist/THIRD-PARTY-NOTICES.txt +0 -431
- package/dist/alp-templates.d.ts +0 -5
- package/dist/operations.d.ts +0 -23
- package/dist/operations.js +0 -272
- package/dist/rpc-error.d.ts +0 -6
- package/dist/rpc-error.js +0 -11
- package/src/alp-templates.d.ts +0 -5
- package/src/operations.ts +0 -298
- package/src/rpc-error.ts +0 -4
package/dist/server.js
CHANGED
|
@@ -1,32 +1,18 @@
|
|
|
1
1
|
// packages/daemon/src/server.ts
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
-
import { appendFile, chmod, mkdir, readFile, unlink
|
|
3
|
+
import { appendFile, chmod, mkdir, readFile, unlink } from "node:fs/promises";
|
|
4
4
|
import net from "node:net";
|
|
5
|
-
import { assertPrivateDirectory, assertPrivateSocket } from "@anhlp/alp-client/index";
|
|
6
5
|
import path from "node:path";
|
|
7
|
-
import {
|
|
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";
|
|
6
|
+
import { AlpRpcError, MAX_FRAME, PROTOCOL_VERSION, ERROR, encodeFrame } from "@anhlp/alp-protocol";
|
|
10
7
|
import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
|
|
11
8
|
import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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" });
|
|
9
|
+
var RpcError = class extends Error {
|
|
10
|
+
constructor(code, message, data) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.data = data;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
30
16
|
function digest(value) {
|
|
31
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");
|
|
32
18
|
}
|
|
@@ -34,40 +20,23 @@ var TREE_LOG_LIMIT = 2e4;
|
|
|
34
20
|
var SESSION_ID = /^[\w.:-]{1,128}$/;
|
|
35
21
|
var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
36
22
|
var RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
37
|
-
var RETENTION_SWEEP_MS = 6 * 60 * 60 * 1e3;
|
|
38
23
|
var LIVE = ["initializing", "idle", "running"];
|
|
39
|
-
function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit
|
|
24
|
+
function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit }) {
|
|
40
25
|
const connections = /* @__PURE__ */ new Set();
|
|
41
26
|
const rootOf = /* @__PURE__ */ new Map();
|
|
42
27
|
const attached = /* @__PURE__ */ new Map();
|
|
43
28
|
const logs = /* @__PURE__ */ new Map();
|
|
44
29
|
const records = /* @__PURE__ */ new Map();
|
|
45
30
|
const delivering = /* @__PURE__ */ new Map();
|
|
46
|
-
const unsaved = /* @__PURE__ */ new Map();
|
|
47
|
-
const cursors = /* @__PURE__ */ new Map();
|
|
48
31
|
let closing = false;
|
|
49
|
-
|
|
50
|
-
const recovering = /* @__PURE__ */ new Map();
|
|
32
|
+
const recovering = /* @__PURE__ */ new Set();
|
|
51
33
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
52
34
|
const restored = store ? restore() : Promise.resolve();
|
|
53
35
|
const deliver = (connection, envelope) => connection.send({ jsonrpc: "2.0", method: "event", params: envelope });
|
|
54
36
|
function save(record, changes = {}) {
|
|
55
37
|
Object.assign(record, changes, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
56
38
|
records.set(record.id, record);
|
|
57
|
-
|
|
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);
|
|
39
|
+
void store?.put(record);
|
|
71
40
|
}
|
|
72
41
|
function track(sessionId, root, event) {
|
|
73
42
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -87,9 +56,8 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
87
56
|
save(record, { title: event.item.text.replace(/\s+/g, " ").trim().slice(0, 80) });
|
|
88
57
|
}
|
|
89
58
|
}
|
|
90
|
-
runtime.onEvent((
|
|
59
|
+
runtime.onEvent((envelope) => {
|
|
91
60
|
if (closing) return;
|
|
92
|
-
let envelope = original;
|
|
93
61
|
const { sessionId, event } = envelope;
|
|
94
62
|
if (event.type === "session.opened") {
|
|
95
63
|
const parent = event.session.parentId;
|
|
@@ -97,11 +65,11 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
97
65
|
}
|
|
98
66
|
const root = rootOf.get(sessionId) ?? sessionId;
|
|
99
67
|
if (rootOf.has(sessionId)) {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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);
|
|
105
73
|
track(sessionId, root, event);
|
|
106
74
|
}
|
|
107
75
|
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
@@ -112,32 +80,33 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
112
80
|
}
|
|
113
81
|
});
|
|
114
82
|
async function restore() {
|
|
115
|
-
await store.pruneReceipts(RECEIPT_RETENTION_MS
|
|
83
|
+
await store.pruneReceipts(RECEIPT_RETENTION_MS);
|
|
116
84
|
const loaded = await store.list();
|
|
117
|
-
await reconcileReceipts(loaded);
|
|
118
85
|
const now = Date.now();
|
|
119
86
|
const ended = { code: "daemon_restarted", message: "alpd stopped while this session was working" };
|
|
120
87
|
const epoch = `restart-${startedAt}`;
|
|
121
88
|
const continuing = new Set(runtime.recoverable().map((entry) => entry.assignmentId));
|
|
122
89
|
const reopen = [];
|
|
123
|
-
const byRoot =
|
|
124
|
-
const
|
|
90
|
+
const byRoot = /* @__PURE__ */ new Map();
|
|
91
|
+
for (const record of loaded) byRoot.set(record.rootId, [...byRoot.get(record.rootId) ?? [], record]);
|
|
125
92
|
for (const [root, tree] of byRoot) {
|
|
126
93
|
const head = tree.find((record) => record.id === root);
|
|
127
|
-
if (
|
|
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
|
+
}
|
|
128
98
|
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
99
|
for (const record of tree) {
|
|
131
100
|
records.set(record.id, record);
|
|
132
101
|
if (!LIVE.includes(record.status)) continue;
|
|
133
102
|
const envelope = (event) => ({ sessionId: record.id, epoch, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event });
|
|
134
|
-
if (record.activeTurnId)
|
|
103
|
+
if (record.activeTurnId) void store.append(root, envelope({ type: "turn.ended", turnId: record.activeTurnId, state: "failed", error: { message: ended.message } }));
|
|
135
104
|
if (record.id === root) {
|
|
136
105
|
save(record, record.status === "idle" ? { status: "closed", activeTurnId: void 0 } : { status: "error", lastError: ended, activeTurnId: void 0 });
|
|
137
106
|
} else if (continuing.has(record.id) && reopen.some((entry) => entry.record.id === root)) {
|
|
138
107
|
save(record, { status: "closed", activeTurnId: void 0 });
|
|
139
108
|
} else {
|
|
140
|
-
|
|
109
|
+
void store.append(root, envelope({ type: "session.closed" }));
|
|
141
110
|
save(record, { status: "closed", lastError: ended, activeTurnId: void 0 });
|
|
142
111
|
if (runLogDir && !continuing.has(record.id)) {
|
|
143
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";
|
|
@@ -152,67 +121,8 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
152
121
|
if (!reopened.has(rootId)) await runtime.abandon(rootId, "its root session cannot be reopened").catch(() => {
|
|
153
122
|
});
|
|
154
123
|
}
|
|
155
|
-
for (const { record
|
|
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
|
-
}
|
|
124
|
+
for (const { record } of reopen) recovering.add(record.id);
|
|
125
|
+
void Promise.all(reopen.map(({ record, working }) => recoverTree(record, working)));
|
|
216
126
|
}
|
|
217
127
|
function resumable(record) {
|
|
218
128
|
return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
|
|
@@ -220,18 +130,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
220
130
|
async function recoverTree(record, working) {
|
|
221
131
|
const session = record.session;
|
|
222
132
|
try {
|
|
223
|
-
|
|
224
|
-
seen(record.id, stored);
|
|
225
|
-
logs.set(record.id, [...stored]);
|
|
133
|
+
logs.set(record.id, [...await treeLog(record.id)]);
|
|
226
134
|
await runtime.open(record.id, {
|
|
227
135
|
...record.spec,
|
|
228
136
|
persist: true,
|
|
229
137
|
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
|
|
230
138
|
}, { history: "skip", delegation: record.delegation ?? true });
|
|
231
139
|
const outcomes = await runtime.recover(record.id, { continueRoot: working });
|
|
232
|
-
|
|
140
|
+
console.log(`${(/* @__PURE__ */ new Date()).toISOString()} recovered ${record.id}: ${outcomes.map((outcome) => `${outcome.agent} ${outcome.outcome}`).join(", ") || "root"}`);
|
|
233
141
|
} catch (error) {
|
|
234
|
-
|
|
142
|
+
console.error(`${(/* @__PURE__ */ new Date()).toISOString()} could not recover ${record.id}`, error);
|
|
235
143
|
await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {
|
|
236
144
|
});
|
|
237
145
|
} finally {
|
|
@@ -241,61 +149,19 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
241
149
|
}
|
|
242
150
|
function deliverOnce(sessionId, clientMessageId, fingerprint, send) {
|
|
243
151
|
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
152
|
const attempt = async () => {
|
|
247
|
-
|
|
248
|
-
if (!existing) {
|
|
249
|
-
try {
|
|
250
|
-
existing = await store.receipt(key);
|
|
251
|
-
} catch (error) {
|
|
252
|
-
throw persistenceFailed(`message ${clientMessageId}`, error);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
153
|
+
const existing = await store.receipt(key);
|
|
255
154
|
if (existing) {
|
|
256
|
-
if (existing.state === "unreadable") throw unknown();
|
|
257
155
|
if (existing.fingerprint !== fingerprint) throw new RpcError(ERROR.conflict, `Message ${clientMessageId} was already sent with different content`, { reason: "key_conflict" });
|
|
258
|
-
if (existing.state === "
|
|
259
|
-
|
|
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" });
|
|
260
158
|
}
|
|
261
|
-
const receipt = (state
|
|
159
|
+
const receipt = (state) => ({ version: 1, sessionId, clientMessageId, fingerprint, state, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
262
160
|
live(sessionId);
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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 });
|
|
161
|
+
await store.putReceipt(key, receipt("pending"));
|
|
162
|
+
await send();
|
|
163
|
+
await store.putReceipt(key, receipt("completed"));
|
|
164
|
+
return {};
|
|
299
165
|
};
|
|
300
166
|
const previous = delivering.get(key) ?? Promise.resolve();
|
|
301
167
|
const result = previous.catch(() => {
|
|
@@ -307,10 +173,6 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
307
173
|
});
|
|
308
174
|
return result;
|
|
309
175
|
}
|
|
310
|
-
async function persisted(root) {
|
|
311
|
-
if (!store) return {};
|
|
312
|
-
return { durable: (await store.drain({ records: [root], timelines: [root] })).length === 0 };
|
|
313
|
-
}
|
|
314
176
|
function forget(root) {
|
|
315
177
|
if (runtime.snapshot(root)) return;
|
|
316
178
|
for (const [id, candidate] of rootOf) if (candidate === root) rootOf.delete(id);
|
|
@@ -363,14 +225,14 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
363
225
|
async function treeLog(root) {
|
|
364
226
|
return logs.get(root) ?? await store?.timeline(root) ?? [];
|
|
365
227
|
}
|
|
366
|
-
function replayHistory(connection, root,
|
|
228
|
+
function replayHistory(connection, root, log, { children = true } = {}) {
|
|
367
229
|
const items = /* @__PURE__ */ new Map();
|
|
368
|
-
for (const envelope of
|
|
230
|
+
for (const envelope of log) {
|
|
369
231
|
if (envelope.sessionId === root && envelope.event.type === "item") items.set(envelope.event.item.id, envelope);
|
|
370
232
|
}
|
|
371
233
|
for (const item of items.values()) deliver(connection, item);
|
|
372
234
|
if (children) {
|
|
373
|
-
for (const envelope of
|
|
235
|
+
for (const envelope of log) if (envelope.sessionId !== root && current(envelope)) deliver(connection, envelope);
|
|
374
236
|
}
|
|
375
237
|
}
|
|
376
238
|
function current(envelope) {
|
|
@@ -383,15 +245,15 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
383
245
|
}
|
|
384
246
|
}
|
|
385
247
|
function announce(connection, root, history) {
|
|
386
|
-
const
|
|
248
|
+
const log = logs.get(root) ?? [];
|
|
387
249
|
const sessions = runtime.list().filter((session) => (rootOf.get(session.id) ?? session.id) === root);
|
|
388
250
|
for (const session of sessions) {
|
|
389
|
-
const opened =
|
|
251
|
+
const opened = log.find((envelope2) => envelope2.sessionId === session.id && envelope2.event.type === "session.opened");
|
|
390
252
|
if (!opened || opened.event.type !== "session.opened") continue;
|
|
391
|
-
const seq = Math.max(...
|
|
253
|
+
const seq = Math.max(...log.filter((envelope2) => envelope2.sessionId === session.id).map((envelope2) => envelope2.seq));
|
|
392
254
|
const envelope = (event) => ({ sessionId: session.id, epoch: opened.epoch, seq, ts: (/* @__PURE__ */ new Date()).toISOString(), event });
|
|
393
255
|
deliver(connection, envelope({ ...opened.event, session }));
|
|
394
|
-
if (history === "replay" && session.id === root) replayHistory(connection, root,
|
|
256
|
+
if (history === "replay" && session.id === root) replayHistory(connection, root, log, { children: false });
|
|
395
257
|
deliver(connection, envelope({ type: "session.ready" }));
|
|
396
258
|
if (session.activeTurnId) deliver(connection, envelope({ type: "turn.started", turnId: session.activeTurnId, origin: "user" }));
|
|
397
259
|
}
|
|
@@ -404,7 +266,6 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
404
266
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
405
267
|
if (agent !== void 0 && agent !== session.agent) throw new RpcError(ERROR.failed, "Cannot resume a session as a different ALP agent");
|
|
406
268
|
const stored = await treeLog(record.id);
|
|
407
|
-
seen(record.id, stored);
|
|
408
269
|
logs.set(record.id, [...stored]);
|
|
409
270
|
attach(connection, record.id);
|
|
410
271
|
try {
|
|
@@ -422,15 +283,13 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
422
283
|
throw error;
|
|
423
284
|
}
|
|
424
285
|
}
|
|
425
|
-
const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
|
|
426
286
|
const extensionOwners = /* @__PURE__ */ new Map();
|
|
427
287
|
const handlers = {
|
|
428
288
|
"extension.register": async (connection, params) => {
|
|
429
289
|
const method = params?.method;
|
|
430
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");
|
|
431
|
-
if (method
|
|
291
|
+
if (typeof method !== "string" || !method.trim()) throw new RpcError(ERROR.protocol, "extension.register requires a method name");
|
|
432
292
|
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
293
|
extensionOwners.set(method, connection);
|
|
435
294
|
if (!methodOwners.has(connection)) methodOwners.set(connection, /* @__PURE__ */ new Set());
|
|
436
295
|
methodOwners.get(connection).add(method);
|
|
@@ -441,7 +300,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
441
300
|
extensionOwners.delete(method);
|
|
442
301
|
throw new RpcError(ERROR.notFound, `${method} is not available`);
|
|
443
302
|
}
|
|
444
|
-
return invokeExtended(owner,
|
|
303
|
+
return invokeExtended(owner, method, invokeParams ?? {});
|
|
445
304
|
};
|
|
446
305
|
return { registered: method };
|
|
447
306
|
},
|
|
@@ -457,7 +316,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
457
316
|
owned?.delete(method);
|
|
458
317
|
return { unregistered: method };
|
|
459
318
|
},
|
|
460
|
-
"daemon.status":
|
|
319
|
+
"daemon.status": () => ({ pid: process.pid, startedAt, version, protocolVersion: PROTOCOL_VERSION, sessions: runtime.list().length, questions: runtime.questions().length, ...previousExit ? { previousExit } : {} }),
|
|
461
320
|
"session.status"(_connection, { sessionId }) {
|
|
462
321
|
if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
|
|
463
322
|
const status = runtime.status(sessionId);
|
|
@@ -537,7 +396,6 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
537
396
|
if (sessionId !== void 0 && (typeof sessionId !== "string" || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, "Invalid session id");
|
|
538
397
|
if (history !== "replay" && history !== "skip") throw new RpcError(-32602, "history must be replay or skip");
|
|
539
398
|
const id = sessionId ?? `ses_${randomBytes(8).toString("hex")}`;
|
|
540
|
-
await recovering.get(id);
|
|
541
399
|
const existing = runtime.snapshot(id);
|
|
542
400
|
if (existing) {
|
|
543
401
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
@@ -548,24 +406,13 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
548
406
|
}
|
|
549
407
|
const record = records.get(id);
|
|
550
408
|
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
|
-
}
|
|
409
|
+
if (record) return { session: await resume(connection, record, spec, history, delegation), attached: false, resumed: true };
|
|
555
410
|
const { restore: _restore, ...kept } = spec;
|
|
556
411
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
557
|
-
|
|
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
|
-
}
|
|
412
|
+
save({ version: 1, id, rootId: id, spec: kept, delegation, status: "initializing", createdAt: now, updatedAt: now });
|
|
565
413
|
attach(connection, id);
|
|
566
414
|
try {
|
|
567
|
-
|
|
568
|
-
return { session, attached: false, ...await persisted(id) };
|
|
415
|
+
return { session: await runtime.open(id, spec, { history, delegation }), attached: false };
|
|
569
416
|
} catch (error) {
|
|
570
417
|
detach(connection, id);
|
|
571
418
|
records.delete(id);
|
|
@@ -578,40 +425,15 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
578
425
|
if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
|
|
579
426
|
return { preview: await runtime.preview(spec) };
|
|
580
427
|
},
|
|
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");
|
|
428
|
+
async "session.attach"(connection, { sessionId, replay = true }) {
|
|
588
429
|
const found = known(sessionId);
|
|
589
430
|
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
431
|
attach(connection, root);
|
|
602
432
|
if (replay) {
|
|
603
|
-
|
|
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
|
-
}
|
|
433
|
+
for (const envelope of await treeLog(root)) if (current(envelope)) deliver(connection, envelope);
|
|
612
434
|
}
|
|
613
435
|
announceQuestions(connection, root);
|
|
614
|
-
return { session: root === found.id ? found : summary(root)
|
|
436
|
+
return { session: root === found.id ? found : summary(root) };
|
|
615
437
|
},
|
|
616
438
|
async "session.release"(connection, { sessionId }) {
|
|
617
439
|
const root = rootOf.get(sessionId) ?? sessionId;
|
|
@@ -643,31 +465,19 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
643
465
|
return {};
|
|
644
466
|
},
|
|
645
467
|
/** The user's name for a root, in place of its first prompt (ALPD §61). */
|
|
646
|
-
|
|
647
|
-
if (typeof title !== "string" || !title.trim() ||
|
|
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");
|
|
648
470
|
const record = rootRecord(sessionId);
|
|
649
|
-
const before = record.title;
|
|
650
471
|
Object.assign(record, { title: title.replace(/\s+/g, " ").trim() });
|
|
651
|
-
|
|
652
|
-
await store?.put(record);
|
|
653
|
-
} catch (error) {
|
|
654
|
-
record.title = before;
|
|
655
|
-
throw persistenceFailed(`the name of ${record.id}`, error);
|
|
656
|
-
}
|
|
472
|
+
void store?.put(record);
|
|
657
473
|
return { session: summary(record.id) };
|
|
658
474
|
},
|
|
659
475
|
/** Sets a root aside: it closes, with its tree, and leaves the lists until unarchived (ALPD §61). */
|
|
660
476
|
async "session.archive"(_connection, { sessionId, archived = true }) {
|
|
661
477
|
const record = rootRecord(sessionId);
|
|
662
478
|
if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
|
|
663
|
-
const before = record.archived;
|
|
664
479
|
Object.assign(record, { archived: archived === true ? true : void 0 });
|
|
665
|
-
|
|
666
|
-
await store?.put(record);
|
|
667
|
-
} catch (error) {
|
|
668
|
-
record.archived = before;
|
|
669
|
-
throw persistenceFailed(`the archive state of ${record.id}`, error);
|
|
670
|
-
}
|
|
480
|
+
void store?.put(record);
|
|
671
481
|
return { session: summary(record.id) };
|
|
672
482
|
},
|
|
673
483
|
"session.get"(_connection, { sessionId }) {
|
|
@@ -679,54 +489,28 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
679
489
|
return { sessions };
|
|
680
490
|
}
|
|
681
491
|
};
|
|
682
|
-
for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
|
|
683
492
|
Object.setPrototypeOf(handlers, null);
|
|
684
|
-
const originalMethods =
|
|
685
|
-
|
|
686
|
-
async function invokeExtended(owner,
|
|
493
|
+
const originalMethods = new Set(Object.keys(handlers));
|
|
494
|
+
originalMethods.add("daemon.hello");
|
|
495
|
+
async function invokeExtended(owner, method, params) {
|
|
687
496
|
if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, "too many pending extension calls");
|
|
688
497
|
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
498
|
return new Promise((resolve, reject) => {
|
|
692
499
|
const timer = setTimeout(() => {
|
|
693
500
|
owner.pending.delete(id);
|
|
694
501
|
reject(new RpcError(ERROR.failed, `${method} timed out`));
|
|
695
502
|
}, 3e4);
|
|
696
|
-
owner.pending.set(id, { resolve, reject, timer
|
|
697
|
-
|
|
698
|
-
owner.send(invocation);
|
|
699
|
-
} catch (error) {
|
|
700
|
-
clearTimeout(timer);
|
|
701
|
-
owner.pending.delete(id);
|
|
702
|
-
reject(error);
|
|
703
|
-
}
|
|
503
|
+
owner.pending.set(id, { resolve, reject, timer });
|
|
504
|
+
owner.send({ jsonrpc: "2.0", id, method: "extension.invoke", params: { method, params } });
|
|
704
505
|
});
|
|
705
506
|
}
|
|
706
|
-
async function
|
|
707
|
-
const
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
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 }));
|
|
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
|
+
};
|
|
726
512
|
try {
|
|
727
|
-
if (Array.isArray(message)) throw new RpcError(
|
|
728
|
-
if (!single || message.jsonrpc !== "2.0") throw new RpcError(RPC_ERROR.invalidRequest, "Invalid request");
|
|
729
|
-
const oversized = (receivedBytes ?? frameBytes(message)) > MAX_FRAME;
|
|
513
|
+
if (!message || typeof message !== "object" || Array.isArray(message) || message.jsonrpc !== "2.0") throw new RpcError(-32600, "Invalid request");
|
|
730
514
|
if (!Object.prototype.hasOwnProperty.call(message, "method")) {
|
|
731
515
|
const hasResult = Object.prototype.hasOwnProperty.call(message, "result");
|
|
732
516
|
const hasError = Object.prototype.hasOwnProperty.call(message, "error");
|
|
@@ -735,43 +519,25 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
735
519
|
if (!waiter) return;
|
|
736
520
|
connection.pending.delete(id);
|
|
737
521
|
clearTimeout(waiter.timer);
|
|
738
|
-
if (oversized) {
|
|
739
|
-
waiter.reject(new RpcError(RPC_ERROR.invalidRequest, "ALP daemon frame exceeds size limit"));
|
|
740
|
-
return;
|
|
741
|
-
}
|
|
742
522
|
if (hasError) waiter.reject(new RpcError(message.error?.code ?? ERROR.failed, message.error?.message ?? "extension call failed", message.error?.data));
|
|
743
523
|
else waiter.resolve(message.result);
|
|
744
524
|
return;
|
|
745
525
|
}
|
|
746
|
-
if (
|
|
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" });
|
|
526
|
+
if (typeof method !== "string") throw new RpcError(-32600, "Invalid request");
|
|
754
527
|
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)
|
|
756
|
-
const issues2 = validateParams(method, params);
|
|
757
|
-
if (issues2.length) throw invalidParams(issues2);
|
|
528
|
+
if (params?.protocolVersion !== PROTOCOL_VERSION) throw new RpcError(ERROR.protocol, `ALP daemon speaks protocol ${PROTOCOL_VERSION}; restart it after upgrading (alp daemon restart)`);
|
|
758
529
|
connection.helloed = true;
|
|
759
|
-
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid
|
|
530
|
+
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid } });
|
|
760
531
|
return;
|
|
761
532
|
}
|
|
762
|
-
if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first"
|
|
533
|
+
if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first");
|
|
763
534
|
await restored;
|
|
764
|
-
if (!connections.has(connection)) return;
|
|
765
535
|
const handler = Object.hasOwn(handlers, method) ? handlers[method] : void 0;
|
|
766
|
-
if (!handler) throw new RpcError(
|
|
767
|
-
const issues = validateParams(method, params);
|
|
768
|
-
if (issues?.length) throw invalidParams(issues);
|
|
536
|
+
if (!handler) throw new RpcError(-32601, `Unknown method '${method}'`);
|
|
769
537
|
respond({ result: await handler(connection, params ?? {}) });
|
|
770
538
|
} catch (error) {
|
|
771
539
|
const code = error instanceof RpcError ? error.code : /is not open/.test(String(error?.message)) ? ERROR.notFound : ERROR.failed;
|
|
772
540
|
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
541
|
respond({ error: { code, message: error instanceof Error ? error.message : String(error), ...data } });
|
|
776
542
|
}
|
|
777
543
|
}
|
|
@@ -788,12 +554,6 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
788
554
|
waiting.reject(new Error("ALP daemon connection closed"));
|
|
789
555
|
}
|
|
790
556
|
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
557
|
connections.delete(connection);
|
|
798
558
|
for (const root of [...connection.roots]) {
|
|
799
559
|
detach(connection, root);
|
|
@@ -817,45 +577,29 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
817
577
|
};
|
|
818
578
|
connections.add(connection);
|
|
819
579
|
let buffer = "";
|
|
820
|
-
let bytes = 0;
|
|
821
580
|
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
581
|
socket.on("data", (chunk) => {
|
|
829
582
|
buffer += chunk;
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
if (bytes >= MAX_FRAME) tooLarge();
|
|
583
|
+
if (buffer.length > MAX_FRAME) {
|
|
584
|
+
socket.destroy();
|
|
833
585
|
return;
|
|
834
586
|
}
|
|
835
|
-
let
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
start = index + 1;
|
|
839
|
-
if (Buffer.byteLength(line, "utf8") + 1 > MAX_FRAME) {
|
|
840
|
-
tooLarge();
|
|
841
|
-
return;
|
|
842
|
-
}
|
|
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);
|
|
843
590
|
if (!line.trim()) continue;
|
|
844
591
|
let message;
|
|
845
592
|
try {
|
|
846
593
|
message = JSON.parse(line);
|
|
847
594
|
} catch {
|
|
848
|
-
|
|
849
|
-
connection.send({ jsonrpc: "2.0", id: null, error: { code: RPC_ERROR.parseError, message: "Parse error" } });
|
|
595
|
+
connection.send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
|
|
850
596
|
continue;
|
|
851
597
|
}
|
|
852
|
-
void dispatch(connection, message
|
|
598
|
+
void dispatch(connection, message);
|
|
853
599
|
}
|
|
854
|
-
buffer = buffer.slice(start);
|
|
855
|
-
bytes = Buffer.byteLength(buffer, "utf8");
|
|
856
|
-
if (bytes >= MAX_FRAME) tooLarge();
|
|
857
600
|
});
|
|
858
|
-
socket.on("error", (
|
|
601
|
+
socket.on("error", () => {
|
|
602
|
+
});
|
|
859
603
|
socket.on("close", () => disconnect(connection));
|
|
860
604
|
});
|
|
861
605
|
return {
|
|
@@ -878,55 +622,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
878
622
|
}
|
|
879
623
|
},
|
|
880
624
|
async listen() {
|
|
881
|
-
if (process.platform !== "win32") {
|
|
882
|
-
|
|
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")}`);
|
|
625
|
+
if (process.platform !== "win32") await unlink(socketPath).catch(() => {
|
|
626
|
+
});
|
|
912
627
|
await new Promise((resolve, reject) => {
|
|
913
628
|
server.once("error", reject);
|
|
914
|
-
server.listen(
|
|
629
|
+
server.listen(socketPath, () => {
|
|
915
630
|
server.off("error", reject);
|
|
916
631
|
resolve();
|
|
917
632
|
});
|
|
918
633
|
});
|
|
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
|
-
}
|
|
634
|
+
if (process.platform !== "win32") await chmod(socketPath, 384);
|
|
930
635
|
},
|
|
931
636
|
local() {
|
|
932
637
|
const events = /* @__PURE__ */ new Set();
|
|
@@ -998,18 +703,11 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
998
703
|
},
|
|
999
704
|
async close() {
|
|
1000
705
|
closing = true;
|
|
1001
|
-
if (sweeper) clearInterval(sweeper);
|
|
1002
706
|
const stopped = new Promise((resolve) => server.close(() => resolve()));
|
|
1003
707
|
for (const connection of connections) connection.socket?.destroy();
|
|
1004
708
|
await stopped;
|
|
1005
|
-
if (
|
|
1006
|
-
|
|
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
|
-
}
|
|
709
|
+
if (process.platform !== "win32") await unlink(socketPath).catch(() => {
|
|
710
|
+
});
|
|
1013
711
|
await store?.flush();
|
|
1014
712
|
}
|
|
1015
713
|
};
|