@anhlp/alp-daemon 0.0.0-stage → 0.0.1-beta.4
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/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +14 -2
- package/dist/THIRD-PARTY-NOTICES.txt +431 -0
- package/dist/alp-templates.d.ts +5 -0
- package/dist/alpd.js +49562 -0
- package/dist/attachments.d.ts +211 -0
- package/dist/attachments.js +819 -0
- package/dist/build-manifest.json +131 -0
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +672 -0
- package/dist/files.d.ts +123 -0
- package/dist/files.js +365 -0
- package/dist/git.d.ts +87 -0
- package/dist/git.js +1093 -0
- package/dist/gitignore.d.ts +62 -0
- package/dist/gitignore.js +254 -0
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +25 -0
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/lock.d.ts +21 -0
- package/dist/lock.js +42 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +277 -0
- package/dist/operations.d.ts +23 -0
- package/dist/operations.js +275 -0
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/rpc-error.d.ts +6 -0
- package/dist/rpc-error.js +11 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +290 -0
- package/dist/schedules.d.ts +69 -0
- package/dist/schedules.js +244 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +1780 -0
- package/dist/store.d.ts +176 -0
- package/dist/store.js +385 -0
- package/dist/terminals.d.ts +157 -0
- package/dist/terminals.js +487 -0
- package/dist/worktrees.d.ts +41 -0
- package/dist/worktrees.js +246 -0
- package/package.json +159 -4
- package/src/alp-templates.d.ts +5 -0
- package/src/attachments.ts +870 -0
- package/src/conversation.ts +837 -0
- package/src/files.ts +459 -0
- package/src/git.ts +1045 -0
- package/src/gitignore.ts +277 -0
- package/src/history.ts +118 -0
- package/src/index.ts +11 -0
- package/src/lifecycle.ts +283 -0
- package/src/lock.ts +53 -0
- package/src/main.ts +292 -0
- package/src/operations.ts +300 -0
- package/src/registry.ts +238 -0
- package/src/rpc-error.ts +4 -0
- package/src/scheduler.ts +422 -0
- package/src/schedules.ts +294 -0
- package/src/server.ts +2056 -0
- package/src/store.ts +448 -0
- package/src/terminals.ts +591 -0
- package/src/worktrees.ts +287 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,1780 @@
|
|
|
1
|
+
// packages/daemon/src/server.ts
|
|
2
|
+
import { realpath as fsRealpath } from "node:fs/promises";
|
|
3
|
+
import { createRegistry, RegistryError } from "./registry.js";
|
|
4
|
+
import { createWorkspaceWorktrees } from "./worktrees.js";
|
|
5
|
+
import { HistoryError } from "./history.js";
|
|
6
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
7
|
+
import { appendFile, chmod, mkdir, readFile, unlink, lstat, rename } from "node:fs/promises";
|
|
8
|
+
import net from "node:net";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import { assertPrivateDirectory, assertPrivateSocket } from "@anhlp/alp-client/index";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { createLogger } from "@anhlp/alp-core/log";
|
|
13
|
+
import { AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from "@anhlp/alp-protocol";
|
|
14
|
+
import { validateParams } from "@anhlp/alp-protocol/contract";
|
|
15
|
+
import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
|
|
16
|
+
import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
|
|
17
|
+
import { RpcError } from "./rpc-error.js";
|
|
18
|
+
import { createOperations } from "./operations.js";
|
|
19
|
+
import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from "./files.js";
|
|
20
|
+
import { createGitReader } from "./git.js";
|
|
21
|
+
import { createScheduleStore, projectKey } from "./schedules.js";
|
|
22
|
+
import { createAttachmentStore } from "./attachments.js";
|
|
23
|
+
import { clientMessageId as scheduleMessageId, createScheduler, SCHEDULE_TICK_MS } from "./scheduler.js";
|
|
24
|
+
import { createLifecycleJournal, LIFECYCLE_RETENTION_MS } from "./lifecycle.js";
|
|
25
|
+
import { createConversation } from "./conversation.js";
|
|
26
|
+
import { createTerminalService } from "./terminals.js";
|
|
27
|
+
var log = createLogger({ component: "alpd.ipc" });
|
|
28
|
+
var recoveryLog = createLogger({ component: "alpd.recovery" });
|
|
29
|
+
function validId(id) {
|
|
30
|
+
if (typeof id !== "string") return Number.isSafeInteger(id);
|
|
31
|
+
let length = 0;
|
|
32
|
+
for (const _point of id) if (++length > 128) return false;
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
var frameBytes = (message) => Buffer.byteLength(encodeFrame(message), "utf8");
|
|
36
|
+
var invalidParams = (issues) => new RpcError(RPC_ERROR.invalidParams, `Invalid params: ${issues.map((issue) => `${issue.path || "params"} ${issue.message}`).join("; ")}`, { reason: "invalid_params", issues });
|
|
37
|
+
function crashPoint(name) {
|
|
38
|
+
if (process.env.ALP_TEST_CRASH_AT !== name) return;
|
|
39
|
+
createLogger({ component: "alpd" }).error(`ALP_TEST_CRASH_AT=${name}: killing alpd`, { code: "ALP_TEST_CRASH" });
|
|
40
|
+
process.kill(process.pid, "SIGKILL");
|
|
41
|
+
}
|
|
42
|
+
var persistenceFailed = (what, error) => new RpcError(ERROR.failed, `alpd could not record ${what}: ${error instanceof Error ? error.message : String(error)}`, { reason: "persistence_failed" });
|
|
43
|
+
var scheduleFailed = (error) => {
|
|
44
|
+
if (error instanceof RpcError) return error;
|
|
45
|
+
switch (error?.code) {
|
|
46
|
+
case "SCHEDULE_NOT_FOUND":
|
|
47
|
+
return new RpcError(ERROR.notFound, error.message, { reason: "not_found" });
|
|
48
|
+
case "SCHEDULE_NOT_PENDING":
|
|
49
|
+
return new RpcError(ERROR.conflict, error.message, { reason: "task_state" });
|
|
50
|
+
case "INVALID_SCHEDULE":
|
|
51
|
+
return new RpcError(RPC_ERROR.invalidParams, error.message, { reason: "invalid_params" });
|
|
52
|
+
}
|
|
53
|
+
return error;
|
|
54
|
+
};
|
|
55
|
+
var requestedProject = (projectRoot) => {
|
|
56
|
+
if (typeof projectRoot !== "string" || !projectRoot) throw new RpcError(RPC_ERROR.invalidParams, "projectRoot is required");
|
|
57
|
+
if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute path");
|
|
58
|
+
return projectRoot;
|
|
59
|
+
};
|
|
60
|
+
function principalOf(params) {
|
|
61
|
+
return {
|
|
62
|
+
id: typeof params.principalId === "string" ? params.principalId : "owner",
|
|
63
|
+
epoch: typeof params.principalEpoch === "string" ? params.principalEpoch : "owner",
|
|
64
|
+
...Array.isArray(params.authorizedRoots) ? { roots: params.authorizedRoots.filter((root) => typeof root === "string") } : {}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function digest(value) {
|
|
68
|
+
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");
|
|
69
|
+
}
|
|
70
|
+
var TREE_LOG_LIMIT = 2e4;
|
|
71
|
+
var SESSION_ID = /^[\w.:-]{1,128}$/;
|
|
72
|
+
var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
73
|
+
var RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
74
|
+
var RETENTION_SWEEP_MS = 6 * 60 * 60 * 1e3;
|
|
75
|
+
var LIVE = ["initializing", "idle", "running"];
|
|
76
|
+
var PROMPT_TITLE_CHARS = 60;
|
|
77
|
+
function titleFromPrompt(text) {
|
|
78
|
+
const line = text.split(/\r?\n/).map((entry) => entry.replace(/\s+/g, " ").trim()).find(Boolean);
|
|
79
|
+
return line ? [...line].slice(0, PROMPT_TITLE_CHARS).join("").trim() || void 0 : void 0;
|
|
80
|
+
}
|
|
81
|
+
function fromUser(item) {
|
|
82
|
+
if (item.clientMessageId?.startsWith("alp-")) return false;
|
|
83
|
+
return item.origin !== void 0 ? item.origin === "user" : item.clientMessageId !== void 0;
|
|
84
|
+
}
|
|
85
|
+
var listCursor = {
|
|
86
|
+
key: (session) => [session.parentId ? 1 : 0, session.updatedAt ?? "", session.id],
|
|
87
|
+
compare([childA, updatedA, idA], [childB, updatedB, idB]) {
|
|
88
|
+
return childA - childB || (updatedA === updatedB ? 0 : updatedA < updatedB ? 1 : -1) || (idA === idB ? 0 : idA < idB ? -1 : 1);
|
|
89
|
+
},
|
|
90
|
+
encode: (key) => Buffer.from(JSON.stringify(key), "utf8").toString("base64url"),
|
|
91
|
+
decode(cursor) {
|
|
92
|
+
let key;
|
|
93
|
+
try {
|
|
94
|
+
key = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
95
|
+
} catch {
|
|
96
|
+
}
|
|
97
|
+
if (!Array.isArray(key) || key.length !== 3 || key[0] !== 0 && key[0] !== 1 || typeof key[1] !== "string" || typeof key[2] !== "string") {
|
|
98
|
+
throw new RpcError(RPC_ERROR.invalidParams, "cursor is not one session.list answered", { reason: "invalid_params" });
|
|
99
|
+
}
|
|
100
|
+
return key;
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions }) {
|
|
104
|
+
const connections = /* @__PURE__ */ new Set();
|
|
105
|
+
const rootOf = /* @__PURE__ */ new Map();
|
|
106
|
+
const attached = /* @__PURE__ */ new Map();
|
|
107
|
+
const logs = /* @__PURE__ */ new Map();
|
|
108
|
+
const records = /* @__PURE__ */ new Map();
|
|
109
|
+
const delivering = /* @__PURE__ */ new Map();
|
|
110
|
+
const unsaved = /* @__PURE__ */ new Map();
|
|
111
|
+
const cursors = /* @__PURE__ */ new Map();
|
|
112
|
+
let closing = false;
|
|
113
|
+
let socketIdentity;
|
|
114
|
+
const recovering = /* @__PURE__ */ new Map();
|
|
115
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
116
|
+
const clock = () => Date.now();
|
|
117
|
+
const schedules = home && store ? createScheduleStore(path.join(home, "schedules"), { now: clock }) : void 0;
|
|
118
|
+
const storeJob = async (id, projectRoot) => {
|
|
119
|
+
if (!schedules) return void 0;
|
|
120
|
+
try {
|
|
121
|
+
return await schedules.get(id, { projectRoot });
|
|
122
|
+
} catch (error) {
|
|
123
|
+
throw scheduleFailed(error);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const attachments = home && store && process.platform !== "win32" ? createAttachmentStore({
|
|
127
|
+
root: path.join(home, "state", "attachments"),
|
|
128
|
+
sessionProject: (sessionId) => runtime.snapshot(sessionId)?.projectRoot ?? records.get(sessionId)?.session?.projectRoot,
|
|
129
|
+
crashPoint,
|
|
130
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
131
|
+
// A collected object's staged copy goes with it.
|
|
132
|
+
onDiscard: (attachmentId) => runtime.dropAttachment?.(attachmentId),
|
|
133
|
+
...attachmentOptions
|
|
134
|
+
}) : void 0;
|
|
135
|
+
runtime.bindAttachments?.(attachments?.reader);
|
|
136
|
+
const holds = /* @__PURE__ */ new Map();
|
|
137
|
+
let holdRevision = 0;
|
|
138
|
+
function holdPrompts(root) {
|
|
139
|
+
holdRevision++;
|
|
140
|
+
let gate = holds.get(root);
|
|
141
|
+
if (!gate) {
|
|
142
|
+
let release;
|
|
143
|
+
const open = new Promise((resolve) => {
|
|
144
|
+
release = resolve;
|
|
145
|
+
});
|
|
146
|
+
gate = { count: 0, open, release };
|
|
147
|
+
holds.set(root, gate);
|
|
148
|
+
}
|
|
149
|
+
gate.count++;
|
|
150
|
+
const held = gate;
|
|
151
|
+
let released = false;
|
|
152
|
+
return () => {
|
|
153
|
+
if (released) return;
|
|
154
|
+
released = true;
|
|
155
|
+
if (--held.count === 0) {
|
|
156
|
+
if (holds.get(root) === held) holds.delete(root);
|
|
157
|
+
held.release();
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
const promptsInFlight = /* @__PURE__ */ new Map();
|
|
162
|
+
const rootIdOf = (sessionId) => rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
163
|
+
async function gated(sessionId, run) {
|
|
164
|
+
const root = rootIdOf(sessionId);
|
|
165
|
+
while (holds.has(root)) await holds.get(root).open;
|
|
166
|
+
refuseFenced(root);
|
|
167
|
+
promptsInFlight.set(root, (promptsInFlight.get(root) ?? 0) + 1);
|
|
168
|
+
try {
|
|
169
|
+
return await run();
|
|
170
|
+
} finally {
|
|
171
|
+
const left = (promptsInFlight.get(root) ?? 1) - 1;
|
|
172
|
+
if (left > 0) promptsInFlight.set(root, left);
|
|
173
|
+
else promptsInFlight.delete(root);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function fencedRoot(root) {
|
|
177
|
+
return conversation?.fenced(root);
|
|
178
|
+
}
|
|
179
|
+
function refuseFenced(root) {
|
|
180
|
+
const requestId = fencedRoot(root);
|
|
181
|
+
if (requestId !== void 0) throw new RpcError(ERROR.conflict, `A rewind of this session is not finished; send session.rewind again with requestId ${requestId}`, { reason: "session_busy" });
|
|
182
|
+
}
|
|
183
|
+
const journal = store ? createLifecycleJournal(path.join(store.root, "lifecycle")) : void 0;
|
|
184
|
+
const conversation = store && journal ? createConversation({
|
|
185
|
+
runtime,
|
|
186
|
+
store,
|
|
187
|
+
journal,
|
|
188
|
+
records,
|
|
189
|
+
cursors,
|
|
190
|
+
logs,
|
|
191
|
+
treeLogLimit: TREE_LOG_LIMIT,
|
|
192
|
+
summary: (id) => summary(id),
|
|
193
|
+
digest,
|
|
194
|
+
unsettled: (root) => fencedRoot(root) ? "a rewind of it is not finished; send that rewind again" : recovering.has(root) ? "it is being reopened after a restart" : openingSessions.has(root) ? "it is opening" : promptsInFlight.get(root) ? "a prompt is being delivered" : void 0,
|
|
195
|
+
holdPrompts,
|
|
196
|
+
broadcast: (root, envelope) => {
|
|
197
|
+
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
198
|
+
},
|
|
199
|
+
get registry() {
|
|
200
|
+
return registry;
|
|
201
|
+
},
|
|
202
|
+
get worktrees() {
|
|
203
|
+
return worktrees;
|
|
204
|
+
},
|
|
205
|
+
attachments,
|
|
206
|
+
crashPoint,
|
|
207
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
208
|
+
startedAt
|
|
209
|
+
}) : void 0;
|
|
210
|
+
let restored = Promise.resolve();
|
|
211
|
+
const openingSessions = /* @__PURE__ */ new Map();
|
|
212
|
+
const recoveryErrors = /* @__PURE__ */ new Map();
|
|
213
|
+
const markOpening = (sessionId) => openingSessions.set(sessionId, (openingSessions.get(sessionId) ?? 0) + 1);
|
|
214
|
+
const clearOpening = (sessionId) => {
|
|
215
|
+
const count = (openingSessions.get(sessionId) ?? 0) - 1;
|
|
216
|
+
if (count > 0) openingSessions.set(sessionId, count);
|
|
217
|
+
else openingSessions.delete(sessionId);
|
|
218
|
+
};
|
|
219
|
+
function keepRecoveryError(sessionId, message) {
|
|
220
|
+
if (scheduler?.holds(sessionId)) recoveryErrors.set(sessionId, message);
|
|
221
|
+
}
|
|
222
|
+
function dropRecoveryError(sessionId) {
|
|
223
|
+
if (!scheduler?.holds(sessionId)) recoveryErrors.delete(sessionId);
|
|
224
|
+
}
|
|
225
|
+
const scheduler = schedules ? createScheduler({
|
|
226
|
+
store: schedules,
|
|
227
|
+
runtime,
|
|
228
|
+
deliver: deliverJob,
|
|
229
|
+
ready: () => restored,
|
|
230
|
+
session: (sessionId) => openingSessions.has(sessionId) ? { opening: true } : recoveryErrors.has(sessionId) ? { error: { message: `The session this job continues could not be opened again: ${recoveryErrors.get(sessionId)}`, code: "session_open_failed" } } : void 0,
|
|
231
|
+
settled: (sessionId) => dropRecoveryError(sessionId),
|
|
232
|
+
stopping: () => closing,
|
|
233
|
+
now: clock,
|
|
234
|
+
...scheduleDeliveryTimeoutMs === void 0 ? {} : { deliveryTimeoutMs: scheduleDeliveryTimeoutMs }
|
|
235
|
+
}) : void 0;
|
|
236
|
+
restored = store ? restore() : Promise.resolve();
|
|
237
|
+
const deliver = (connection, envelope) => {
|
|
238
|
+
const message = { jsonrpc: "2.0", method: "event", params: envelope };
|
|
239
|
+
const bytes = frameBytes(message);
|
|
240
|
+
if (bytes > 512 * 1024 && envelope.cursor !== void 0) message.params = {
|
|
241
|
+
...envelope,
|
|
242
|
+
event: { type: "item", item: { kind: "notice", id: `oversized:${envelope.cursor}`, level: "warning", text: `History event ${envelope.cursor} is too large to display (${bytes} bytes).` } }
|
|
243
|
+
};
|
|
244
|
+
connection.send(message);
|
|
245
|
+
};
|
|
246
|
+
const watchers = /* @__PURE__ */ new Map();
|
|
247
|
+
function projectOf(root) {
|
|
248
|
+
return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
|
|
249
|
+
}
|
|
250
|
+
function tellWatchers(root, envelope, turn = false) {
|
|
251
|
+
if (!watchers.size) return;
|
|
252
|
+
const { cursor: _cursor, ...announced } = envelope;
|
|
253
|
+
const project = projectOf(root);
|
|
254
|
+
for (const [connection, { projectRoot, turns }] of watchers) {
|
|
255
|
+
if (turn && !turns) continue;
|
|
256
|
+
if (attached.get(root)?.has(connection)) continue;
|
|
257
|
+
if (projectRoot !== void 0 && project !== projectRoot) continue;
|
|
258
|
+
deliver(connection, announced);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function tellAttention(root, attention) {
|
|
262
|
+
if (!watchers.size) return;
|
|
263
|
+
const project = projectOf(root);
|
|
264
|
+
const envelope = { sessionId: root, epoch: `attention-${startedAt}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "attention", ...attention ? { attention } : {} } };
|
|
265
|
+
for (const [connection, watch] of watchers) {
|
|
266
|
+
if (!watch.attention) continue;
|
|
267
|
+
if (watch.projectRoot !== void 0 && project !== watch.projectRoot) continue;
|
|
268
|
+
deliver(connection, envelope);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const pendingAcks = /* @__PURE__ */ new Map();
|
|
272
|
+
function attentionOf(projectRoot) {
|
|
273
|
+
const found = [];
|
|
274
|
+
for (const record of records.values()) {
|
|
275
|
+
if (record.id !== record.rootId || !record.attention || record.archived) continue;
|
|
276
|
+
if (projectRoot !== void 0 && projectOf(record.id) !== projectRoot) continue;
|
|
277
|
+
found.push({ sessionId: record.id, attention: record.attention });
|
|
278
|
+
}
|
|
279
|
+
return found;
|
|
280
|
+
}
|
|
281
|
+
function save(record, changes = {}) {
|
|
282
|
+
Object.assign(record, changes, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
283
|
+
records.set(record.id, record);
|
|
284
|
+
return store?.put(record).catch(() => {
|
|
285
|
+
}) ?? Promise.resolve();
|
|
286
|
+
}
|
|
287
|
+
function keep(root, envelope) {
|
|
288
|
+
const cursor = (cursors.get(root) ?? 0) + 1;
|
|
289
|
+
cursors.set(root, cursor);
|
|
290
|
+
const kept = { ...envelope, cursor };
|
|
291
|
+
void store?.append(root, kept).catch(() => {
|
|
292
|
+
});
|
|
293
|
+
return kept;
|
|
294
|
+
}
|
|
295
|
+
function seen(root, log2) {
|
|
296
|
+
const last = log2.at(-1)?.cursor ?? 0;
|
|
297
|
+
if (last > (cursors.get(root) ?? 0)) cursors.set(root, last);
|
|
298
|
+
}
|
|
299
|
+
function track(sessionId, root, event) {
|
|
300
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
301
|
+
let record = records.get(sessionId);
|
|
302
|
+
if (event.type === "session.opened") {
|
|
303
|
+
record ??= { version: 1, id: sessionId, rootId: root, status: "initializing", createdAt: now, updatedAt: now };
|
|
304
|
+
const usage = event.session.usage ?? record.session?.usage;
|
|
305
|
+
const parked = recovering.has(root) ? record.session?.parked : event.session.parked;
|
|
306
|
+
save(record, { rootId: root, session: { ...event.session, ...usage ? { usage } : {}, ...parked ? { parked } : {} }, status: "idle", lastError: void 0, activeTurnId: void 0 });
|
|
307
|
+
return false;
|
|
308
|
+
}
|
|
309
|
+
if (!record) return false;
|
|
310
|
+
if (event.type === "session.updated") save(record, { session: { ...record.session, ...event.session, ...event.session.parked ? {} : { parked: void 0 } } });
|
|
311
|
+
else if (event.type === "turn.started") save(record, { status: "running", activeTurnId: event.turnId, archived: void 0, ...sessionId === root ? { attention: void 0 } : {} });
|
|
312
|
+
else if (event.type === "turn.ended") save(record, {
|
|
313
|
+
status: "idle",
|
|
314
|
+
activeTurnId: void 0,
|
|
315
|
+
// A root's turn that completed or failed asks every client for a look until one acknowledges it (Paseo's checkAndSetAttention).
|
|
316
|
+
...sessionId === root ? { attention: turnAttention(event) } : {},
|
|
317
|
+
...record.session ? { session: { ...record.session, parked: event.state === "failed" ? runtime.snapshot(sessionId)?.parked : void 0 } } : {},
|
|
318
|
+
...event.state === "failed" ? { lastError: { message: event.error?.message ?? "Turn failed" } } : {}
|
|
319
|
+
});
|
|
320
|
+
else if (event.type === "usage" && record.session) record.session = { ...record.session, usage: event.usage };
|
|
321
|
+
else if (event.type === "session.failed") save(record, { status: "error", lastError: event.error });
|
|
322
|
+
else if (event.type === "session.closed") save(record, { status: record.status === "error" ? "error" : "closed", activeTurnId: void 0 });
|
|
323
|
+
else if (event.type === "item" && sessionId === root && !record.title && event.item.kind === "user_message" && fromUser(event.item)) {
|
|
324
|
+
const title = titleFromPrompt(event.item.text);
|
|
325
|
+
if (title) {
|
|
326
|
+
save(record, { title });
|
|
327
|
+
return true;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
function turnAttention(event) {
|
|
333
|
+
if (event.state === "canceled") return void 0;
|
|
334
|
+
const message = event.error?.message?.trim();
|
|
335
|
+
return { reason: event.state === "completed" ? "finished" : "error", at: (/* @__PURE__ */ new Date()).toISOString(), turnId: event.turnId, ...event.state === "failed" && message ? { message: event.error.message } : {} };
|
|
336
|
+
}
|
|
337
|
+
function announceTitle(root, title) {
|
|
338
|
+
const session = runtime.snapshot(root);
|
|
339
|
+
if (!session || rootOf.get(root) !== root) return;
|
|
340
|
+
const envelope = keep(root, { sessionId: root, epoch: `title-${startedAt}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "session.updated", session: { ...session, title } } });
|
|
341
|
+
const log2 = logs.get(root) ?? [];
|
|
342
|
+
log2.push(envelope);
|
|
343
|
+
if (log2.length > TREE_LOG_LIMIT) log2.splice(0, log2.length - TREE_LOG_LIMIT);
|
|
344
|
+
logs.set(root, log2);
|
|
345
|
+
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
346
|
+
}
|
|
347
|
+
runtime.onEvent((original) => {
|
|
348
|
+
if (closing) return;
|
|
349
|
+
let envelope = original;
|
|
350
|
+
const { sessionId, event } = envelope;
|
|
351
|
+
if (event.type === "session.opened") {
|
|
352
|
+
const parent = event.session.parentId;
|
|
353
|
+
rootOf.set(sessionId, parent ? rootOf.get(parent) ?? parent : sessionId);
|
|
354
|
+
}
|
|
355
|
+
const root = rootOf.get(sessionId) ?? sessionId;
|
|
356
|
+
let named = false;
|
|
357
|
+
if (rootOf.has(sessionId)) {
|
|
358
|
+
envelope = keep(root, envelope);
|
|
359
|
+
const log2 = logs.get(root) ?? [];
|
|
360
|
+
log2.push(envelope);
|
|
361
|
+
if (log2.length > TREE_LOG_LIMIT) log2.splice(0, log2.length - TREE_LOG_LIMIT);
|
|
362
|
+
logs.set(root, log2);
|
|
363
|
+
const before = records.get(root)?.attention;
|
|
364
|
+
named = track(sessionId, root, event);
|
|
365
|
+
const after = records.get(root)?.attention;
|
|
366
|
+
if (sessionId === root && (event.type === "turn.started" || event.type === "turn.ended")) pendingAcks.delete(root);
|
|
367
|
+
if (after !== before) tellAttention(root, after);
|
|
368
|
+
}
|
|
369
|
+
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
370
|
+
if (event.type === "question" || event.type === "question.resolved") tellWatchers(root, envelope);
|
|
371
|
+
else if (event.type === "turn.ended" && sessionId === root) tellWatchers(root, envelope, true);
|
|
372
|
+
if (named) announceTitle(root, records.get(root).title);
|
|
373
|
+
if (event.type === "session.closed" && sessionId === root) {
|
|
374
|
+
setImmediate(() => forget(root));
|
|
375
|
+
} else {
|
|
376
|
+
setImmediate(() => void reap(root));
|
|
377
|
+
}
|
|
378
|
+
});
|
|
379
|
+
async function restore() {
|
|
380
|
+
await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: true });
|
|
381
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS, { temporaries: true }).catch((error) => recoveryLog.warn("could not prune the lifecycle journal", { code: "ALPD_LIFECYCLE_PRUNE_FAILED", error }));
|
|
382
|
+
const loaded = await store.list();
|
|
383
|
+
await reconcileReceipts(loaded);
|
|
384
|
+
const now = Date.now();
|
|
385
|
+
const ended = { code: "daemon_restarted", message: "alpd stopped while this session was working" };
|
|
386
|
+
const epoch = `restart-${startedAt}`;
|
|
387
|
+
const continuing = new Set(runtime.recoverable().map((entry) => entry.assignmentId));
|
|
388
|
+
const pending = await schedules?.all({ status: "pending" }) ?? [];
|
|
389
|
+
for (const job of pending) scheduler?.hold(job);
|
|
390
|
+
const scheduled = new Set(pending.map((job) => job.sessionId));
|
|
391
|
+
const reopen = [];
|
|
392
|
+
const byRoot = trees(loaded);
|
|
393
|
+
const removed = await expire(byRoot, now);
|
|
394
|
+
for (const [root, tree] of byRoot) {
|
|
395
|
+
const head = tree.find((record) => record.id === root);
|
|
396
|
+
if (removed.has(root)) continue;
|
|
397
|
+
if (head && resumable(head) && (head.status === "running" || head.status === "idle" && head.session?.parked || tree.some((record) => continuing.has(record.id)) || scheduled.has(head.id) && head.status !== "closed")) reopen.push({ record: head, working: head.status === "running" });
|
|
398
|
+
if (tree.some((record) => LIVE.includes(record.status))) seen(root, await store.timeline(root));
|
|
399
|
+
for (const record of tree) {
|
|
400
|
+
records.set(record.id, record);
|
|
401
|
+
if (!LIVE.includes(record.status)) continue;
|
|
402
|
+
const envelope = (event) => ({ sessionId: record.id, epoch, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event });
|
|
403
|
+
if (record.activeTurnId) keep(root, envelope({ type: "turn.ended", turnId: record.activeTurnId, state: "failed", error: { message: ended.message, code: ended.code } }));
|
|
404
|
+
if (record.id === root) {
|
|
405
|
+
if (!(record.status === "idle" && record.session?.parked)) save(record, record.status === "idle" ? { status: "closed", activeTurnId: void 0 } : { status: "error", lastError: ended, activeTurnId: void 0 });
|
|
406
|
+
} else if (continuing.has(record.id) && reopen.some((entry) => entry.record.id === root)) {
|
|
407
|
+
save(record, { status: "closed", activeTurnId: void 0 });
|
|
408
|
+
} else {
|
|
409
|
+
keep(root, envelope({ type: "session.closed" }));
|
|
410
|
+
save(record, { status: "closed", lastError: ended, activeTurnId: void 0 });
|
|
411
|
+
if (runLogDir && !continuing.has(record.id)) {
|
|
412
|
+
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";
|
|
413
|
+
await mkdir(runLogDir, { recursive: true }).then(() => appendFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`), line)).catch(() => {
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
if (conversation) await conversation.recover().catch((error) => recoveryLog.error("could not recover lifecycle operations", { code: "ALPD_LIFECYCLE_RECOVERY_FAILED", error }));
|
|
420
|
+
const reopened = new Set(reopen.map((entry) => entry.record.id));
|
|
421
|
+
for (const rootId of new Set(runtime.recoverable().map((entry) => entry.rootId))) {
|
|
422
|
+
if (!reopened.has(rootId)) await runtime.abandon(rootId, "its root session cannot be reopened").catch(() => {
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
for (const { record, working } of reopen) {
|
|
426
|
+
if (fencedRoot(record.id)) {
|
|
427
|
+
recoveryLog.warn(`${record.id} is not reopened: a rewind of it is not finished`, { code: "ALPD_REWIND_FENCED", sessionId: record.id });
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
markOpening(record.id);
|
|
431
|
+
recovering.set(record.id, recoverTree(record, working, () => {
|
|
432
|
+
clearOpening(record.id);
|
|
433
|
+
}));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
function trees(list) {
|
|
437
|
+
const byRoot = /* @__PURE__ */ new Map();
|
|
438
|
+
for (const record of list) byRoot.set(record.rootId, [...byRoot.get(record.rootId) ?? [], record]);
|
|
439
|
+
return byRoot;
|
|
440
|
+
}
|
|
441
|
+
async function expire(byRoot, now = Date.now()) {
|
|
442
|
+
const removed = /* @__PURE__ */ new Set();
|
|
443
|
+
const receiptWritten = /* @__PURE__ */ new Map();
|
|
444
|
+
for (const { receipt, writtenAt } of await store.receipts()) {
|
|
445
|
+
const at = Date.parse(receipt.updatedAt);
|
|
446
|
+
receiptWritten.set(receipt.sessionId, Math.max(receiptWritten.get(receipt.sessionId) ?? 0, Number.isNaN(at) ? now : at, writtenAt));
|
|
447
|
+
}
|
|
448
|
+
const continuing = new Set(runtime.recoverable().map((entry) => entry.rootId));
|
|
449
|
+
for (const [root, tree] of byRoot) {
|
|
450
|
+
const remove = async () => {
|
|
451
|
+
if (!tree.some((record) => record.id === root)) return;
|
|
452
|
+
if (tree.some((record) => LIVE.includes(record.status))) return;
|
|
453
|
+
if (now - Math.max(...tree.map((record) => Date.parse(record.updatedAt) || now)) <= RETENTION_MS) return;
|
|
454
|
+
if (tree.some((record) => now - (receiptWritten.get(record.id) ?? 0) <= RECEIPT_RETENTION_MS)) return;
|
|
455
|
+
if (continuing.has(root) || rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
456
|
+
if (scheduler?.holds(root)) return;
|
|
457
|
+
const ids = tree.map((record) => record.id);
|
|
458
|
+
if (now - await store.writtenAt(ids) <= RETENTION_MS) return;
|
|
459
|
+
if (rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
460
|
+
if (await conversation?.retainsFork(root)) return;
|
|
461
|
+
for (const id of ids) records.delete(id);
|
|
462
|
+
cursors.delete(root);
|
|
463
|
+
await store.remove(root, ids);
|
|
464
|
+
await attachments?.releaseSessions(ids).catch((error) => recoveryLog.warn("could not release the attachments of removed sessions", { code: "ALPD_ATTACHMENT_RELEASE_FAILED", error }));
|
|
465
|
+
if (runLogDir) await unlink(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`)).catch(() => {
|
|
466
|
+
});
|
|
467
|
+
removed.add(root);
|
|
468
|
+
};
|
|
469
|
+
if (conversation) await conversation.lifecycle.serial(root, remove);
|
|
470
|
+
else await remove();
|
|
471
|
+
}
|
|
472
|
+
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 });
|
|
473
|
+
return removed;
|
|
474
|
+
}
|
|
475
|
+
async function sweep() {
|
|
476
|
+
if (closing || !store) return;
|
|
477
|
+
try {
|
|
478
|
+
await restored;
|
|
479
|
+
await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
|
|
480
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS);
|
|
481
|
+
await expire(trees(records.values()));
|
|
482
|
+
} catch (error) {
|
|
483
|
+
recoveryLog.warn("retention sweep failed", { code: "ALP_RETENTION_FAILED", error });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : void 0;
|
|
487
|
+
sweeper?.unref();
|
|
488
|
+
scheduler?.start(scheduleTickMs);
|
|
489
|
+
async function reconcileReceipts(loaded) {
|
|
490
|
+
const rootOfRecord = new Map(loaded.map((record) => [record.id, record.rootId]));
|
|
491
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
492
|
+
for (const { key, receipt } of await store.receipts()) {
|
|
493
|
+
if (receipt.state !== "pending") continue;
|
|
494
|
+
const root = rootOfRecord.get(receipt.sessionId);
|
|
495
|
+
if (!root) continue;
|
|
496
|
+
if (!timelines.has(root)) timelines.set(root, await store.timeline(root).catch(() => []));
|
|
497
|
+
const answer = timelines.get(root).find(({ sessionId, event: event2 }) => sessionId === receipt.sessionId && (event2.type === "prompt.accepted" || event2.type === "prompt.failed") && event2.clientMessageId === receipt.clientMessageId);
|
|
498
|
+
if (!answer) continue;
|
|
499
|
+
const event = answer.event;
|
|
500
|
+
const outcome = event.type === "prompt.accepted" ? "accepted" : event.error.code === "outcome_unknown" ? "unknown" : "failed";
|
|
501
|
+
await store.putReceipt(key, { ...receipt, state: "completed", outcome, ...event.type === "prompt.failed" ? { error: event.error } : {}, reconciled: true, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).catch(() => {
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
function resumable(record) {
|
|
506
|
+
return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
|
|
507
|
+
}
|
|
508
|
+
async function recoverTree(record, working, opened) {
|
|
509
|
+
const session = record.session;
|
|
510
|
+
let openedOnce = false;
|
|
511
|
+
const open = () => {
|
|
512
|
+
if (openedOnce) return;
|
|
513
|
+
openedOnce = true;
|
|
514
|
+
opened?.();
|
|
515
|
+
};
|
|
516
|
+
try {
|
|
517
|
+
if (worktrees && record.spec?.cwd) await worktrees.assertAvailable(record.spec.cwd);
|
|
518
|
+
const stored = await treeLog(record.id);
|
|
519
|
+
seen(record.id, stored);
|
|
520
|
+
logs.set(record.id, [...stored]);
|
|
521
|
+
await runtime.open(record.id, {
|
|
522
|
+
...record.spec,
|
|
523
|
+
persist: true,
|
|
524
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...record.base ? { base: record.base } : {} }
|
|
525
|
+
}, { history: "skip", delegation: record.delegation ?? true });
|
|
526
|
+
open();
|
|
527
|
+
const outcomes = await runtime.recover(record.id, { continueRoot: working, parkedRoot: session.parked });
|
|
528
|
+
recoveryLog.info(`recovered ${record.id}: ${outcomes.map((outcome) => `${outcome.agent} ${outcome.outcome}`).join(", ") || "root"}`, { event: "recovered", sessionId: record.id, rootId: record.rootId });
|
|
529
|
+
} catch (error) {
|
|
530
|
+
open();
|
|
531
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
532
|
+
recoveryLog.error(`could not recover ${record.id}`, { code: "ALP_RECOVERY_FAILED", sessionId: record.id, rootId: record.rootId, error });
|
|
533
|
+
await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {
|
|
534
|
+
});
|
|
535
|
+
} finally {
|
|
536
|
+
recovering.delete(record.id);
|
|
537
|
+
setImmediate(() => void reap(record.id));
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
function deliverOnce(sessionId, clientMessageId, fingerprint, send, { requireReceipt = false, prepare, abandon } = {}) {
|
|
541
|
+
const key = digest(["prompt", sessionId, clientMessageId]);
|
|
542
|
+
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" });
|
|
543
|
+
const answer = (receipt, extra = {}) => ({ outcome: receipt.outcome ?? "accepted", ...receipt.error ? { error: receipt.error } : {}, ...extra });
|
|
544
|
+
const attempt = async () => {
|
|
545
|
+
let existing = unsaved.get(key);
|
|
546
|
+
if (!existing) {
|
|
547
|
+
try {
|
|
548
|
+
existing = await store.receipt(key);
|
|
549
|
+
} catch (error) {
|
|
550
|
+
throw persistenceFailed(`message ${clientMessageId}`, error);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
if (existing) {
|
|
554
|
+
if (existing.state === "unreadable") throw unknown();
|
|
555
|
+
if (existing.fingerprint !== fingerprint) throw new RpcError(ERROR.conflict, `Message ${clientMessageId} was already sent with different content`, { reason: "key_conflict" });
|
|
556
|
+
if (existing.state === "pending" || existing.outcome === "unknown") throw unknown();
|
|
557
|
+
return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
|
|
558
|
+
}
|
|
559
|
+
if (requireReceipt) throw unknown();
|
|
560
|
+
const receipt = (state, changes = {}) => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
561
|
+
live(sessionId);
|
|
562
|
+
await prepare?.(key);
|
|
563
|
+
crashPoint("prompt.before-receipt");
|
|
564
|
+
try {
|
|
565
|
+
await store.putReceipt(key, receipt("pending"));
|
|
566
|
+
} catch (error) {
|
|
567
|
+
await abandon?.(key).catch(() => {
|
|
568
|
+
});
|
|
569
|
+
throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error);
|
|
570
|
+
}
|
|
571
|
+
crashPoint("prompt.after-receipt");
|
|
572
|
+
let reply = { outcome: "accepted" };
|
|
573
|
+
const stop = runtime.onEvent(({ sessionId: from, event }) => {
|
|
574
|
+
if (from !== sessionId) return;
|
|
575
|
+
if (event.type === "prompt.accepted" && event.clientMessageId === clientMessageId) reply = { outcome: "accepted" };
|
|
576
|
+
if (event.type === "prompt.failed" && event.clientMessageId === clientMessageId) reply = { outcome: event.error.code === "outcome_unknown" ? "unknown" : "failed", error: event.error };
|
|
577
|
+
});
|
|
578
|
+
try {
|
|
579
|
+
await send();
|
|
580
|
+
} catch (error) {
|
|
581
|
+
await store.removeReceipt(key).catch(() => {
|
|
582
|
+
});
|
|
583
|
+
await abandon?.(key).catch(() => {
|
|
584
|
+
});
|
|
585
|
+
throw error;
|
|
586
|
+
} finally {
|
|
587
|
+
stop();
|
|
588
|
+
}
|
|
589
|
+
const root = rootOf.get(sessionId) ?? sessionId;
|
|
590
|
+
const lost = await store.drain({ records: [sessionId], timelines: [root] });
|
|
591
|
+
crashPoint("prompt.after-send");
|
|
592
|
+
const done = receipt("completed", reply);
|
|
593
|
+
let durable = lost.length === 0;
|
|
594
|
+
try {
|
|
595
|
+
await store.putReceipt(key, done);
|
|
596
|
+
} catch {
|
|
597
|
+
unsaved.set(key, done);
|
|
598
|
+
durable = false;
|
|
599
|
+
}
|
|
600
|
+
crashPoint("prompt.after-completed");
|
|
601
|
+
if (reply.outcome === "unknown") throw unknown();
|
|
602
|
+
return answer(done, { durable });
|
|
603
|
+
};
|
|
604
|
+
const previous = delivering.get(key) ?? Promise.resolve();
|
|
605
|
+
const result = previous.catch(() => {
|
|
606
|
+
}).then(() => gated(sessionId, attempt));
|
|
607
|
+
delivering.set(key, result);
|
|
608
|
+
void result.finally(() => {
|
|
609
|
+
if (delivering.get(key) === result) delivering.delete(key);
|
|
610
|
+
}).catch(() => {
|
|
611
|
+
});
|
|
612
|
+
return result;
|
|
613
|
+
}
|
|
614
|
+
async function deliverJob(job, content, messageId, send = (id, input) => runtime.prompt(id, input)) {
|
|
615
|
+
const clientMessageId = messageId || scheduleMessageId(job);
|
|
616
|
+
return deliverOnce(job.sessionId, clientMessageId, digest({ delivery: "auto", content }), async () => {
|
|
617
|
+
live(job.sessionId);
|
|
618
|
+
await send(job.sessionId, { clientMessageId, delivery: "auto", content });
|
|
619
|
+
}, { requireReceipt: job.attempts > 1 });
|
|
620
|
+
}
|
|
621
|
+
async function persisted(root) {
|
|
622
|
+
if (!store) return {};
|
|
623
|
+
return { durable: (await store.drain({ records: [root], timelines: [root] })).length === 0 };
|
|
624
|
+
}
|
|
625
|
+
function forget(root) {
|
|
626
|
+
if (runtime.snapshot(root)) return;
|
|
627
|
+
for (const [id, candidate] of rootOf) if (candidate === root) {
|
|
628
|
+
rootOf.delete(id);
|
|
629
|
+
recoveryErrors.delete(id);
|
|
630
|
+
}
|
|
631
|
+
recoveryErrors.delete(root);
|
|
632
|
+
logs.delete(root);
|
|
633
|
+
}
|
|
634
|
+
async function reap(root) {
|
|
635
|
+
if (closing || attached.get(root)?.size || recovering.has(root)) return false;
|
|
636
|
+
if (scheduler?.holds(root)) return false;
|
|
637
|
+
const session = runtime.snapshot(root);
|
|
638
|
+
if (!session || session.busy) return false;
|
|
639
|
+
await runtime.close(root).catch(() => {
|
|
640
|
+
});
|
|
641
|
+
return true;
|
|
642
|
+
}
|
|
643
|
+
function attach(connection, root) {
|
|
644
|
+
const set = attached.get(root) ?? /* @__PURE__ */ new Set();
|
|
645
|
+
set.add(connection);
|
|
646
|
+
attached.set(root, set);
|
|
647
|
+
connection.roots.add(root);
|
|
648
|
+
}
|
|
649
|
+
function detach(connection, root) {
|
|
650
|
+
attached.get(root)?.delete(connection);
|
|
651
|
+
if (!attached.get(root)?.size) attached.delete(root);
|
|
652
|
+
connection.roots.delete(root);
|
|
653
|
+
}
|
|
654
|
+
function summary(id) {
|
|
655
|
+
const record = records.get(id);
|
|
656
|
+
const live2 = runtime.snapshot(id);
|
|
657
|
+
const session = live2 ?? record?.session;
|
|
658
|
+
if (!session) return void 0;
|
|
659
|
+
const status = live2 ? live2.activeTurnId ? "running" : "idle" : record?.status === "error" ? "error" : "closed";
|
|
660
|
+
return { ...session, ...live2 ? {} : { busy: false, activeTurnId: void 0 }, status, title: record?.title, ...record?.archived ? { archived: true } : {}, ...record?.attention && !record.archived ? { attention: record.attention } : {}, lastError: record?.lastError, createdAt: record?.createdAt, updatedAt: record?.updatedAt, ...record && conversation ? conversation.fields(record, session) : {} };
|
|
661
|
+
}
|
|
662
|
+
function rootRecord(sessionId) {
|
|
663
|
+
if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
|
|
664
|
+
const record = records.get(sessionId);
|
|
665
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
|
|
666
|
+
if (record.rootId !== record.id) throw new RpcError(-32602, "Only a root session can be renamed or archived");
|
|
667
|
+
return record;
|
|
668
|
+
}
|
|
669
|
+
function known(sessionId) {
|
|
670
|
+
const found = summary(sessionId);
|
|
671
|
+
if (!found) throw new RpcError(ERROR.notFound, "Session is not open");
|
|
672
|
+
return found;
|
|
673
|
+
}
|
|
674
|
+
function live(sessionId) {
|
|
675
|
+
const session = runtime.snapshot(sessionId);
|
|
676
|
+
if (!session) throw new RpcError(ERROR.notFound, "Session is not open");
|
|
677
|
+
return session;
|
|
678
|
+
}
|
|
679
|
+
async function treeLog(root) {
|
|
680
|
+
return logs.get(root) ?? await store?.timeline(root) ?? [];
|
|
681
|
+
}
|
|
682
|
+
function replayHistory(connection, root, log2, { children = true } = {}) {
|
|
683
|
+
const items = /* @__PURE__ */ new Map();
|
|
684
|
+
for (const envelope of log2) {
|
|
685
|
+
if (envelope.sessionId === root && envelope.event.type === "item") items.set(envelope.event.item.id, envelope);
|
|
686
|
+
}
|
|
687
|
+
for (const item of items.values()) deliver(connection, item);
|
|
688
|
+
if (children) {
|
|
689
|
+
for (const envelope of log2) if (envelope.sessionId !== root && current(envelope)) deliver(connection, envelope);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
function current(envelope) {
|
|
693
|
+
return envelope.event.type !== "question" && envelope.event.type !== "question.resolved";
|
|
694
|
+
}
|
|
695
|
+
function announceQuestions(connection, root) {
|
|
696
|
+
for (const question of runtime.questions()) {
|
|
697
|
+
if (question.rootId !== root) continue;
|
|
698
|
+
deliver(connection, { sessionId: question.sessionId, epoch: `announce-${startedAt}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "question", question } });
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
function announce(connection, root, history) {
|
|
702
|
+
const log2 = logs.get(root) ?? [];
|
|
703
|
+
const sessions = runtime.list().filter((session) => (rootOf.get(session.id) ?? session.id) === root);
|
|
704
|
+
for (const session of sessions) {
|
|
705
|
+
const opened = log2.find((envelope2) => envelope2.sessionId === session.id && envelope2.event.type === "session.opened");
|
|
706
|
+
if (!opened || opened.event.type !== "session.opened") continue;
|
|
707
|
+
const seq = Math.max(...log2.filter((envelope2) => envelope2.sessionId === session.id).map((envelope2) => envelope2.seq));
|
|
708
|
+
const envelope = (event) => ({ sessionId: session.id, epoch: opened.epoch, seq, ts: (/* @__PURE__ */ new Date()).toISOString(), event });
|
|
709
|
+
deliver(connection, envelope({ ...opened.event, session }));
|
|
710
|
+
if (history === "replay" && session.id === root) replayHistory(connection, root, log2, { children: false });
|
|
711
|
+
deliver(connection, envelope({ type: "session.ready" }));
|
|
712
|
+
if (session.activeTurnId) deliver(connection, envelope({ type: "turn.started", turnId: session.activeTurnId, origin: "user" }));
|
|
713
|
+
}
|
|
714
|
+
announceQuestions(connection, root);
|
|
715
|
+
}
|
|
716
|
+
async function resume(connection, record, spec, history, delegation) {
|
|
717
|
+
const session = record.session;
|
|
718
|
+
if (record.rootId !== record.id) throw new RpcError(ERROR.failed, "Only root sessions can be resumed");
|
|
719
|
+
if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, "This session cannot be resumed");
|
|
720
|
+
const agent = spec.agent ?? spec.restore?.agent;
|
|
721
|
+
if (agent !== void 0 && agent !== session.agent) throw new RpcError(ERROR.failed, "Cannot resume a session as a different ALP agent");
|
|
722
|
+
markOpening(record.id);
|
|
723
|
+
recoveryErrors.delete(record.id);
|
|
724
|
+
let applied = false;
|
|
725
|
+
try {
|
|
726
|
+
if (worktrees) await worktrees.assertAvailable(record.spec.cwd);
|
|
727
|
+
const stored = await treeLog(record.id);
|
|
728
|
+
seen(record.id, stored);
|
|
729
|
+
logs.set(record.id, [...stored]);
|
|
730
|
+
attach(connection, record.id);
|
|
731
|
+
const opened = await runtime.open(record.id, {
|
|
732
|
+
...record.spec,
|
|
733
|
+
...spec.mode !== void 0 ? { mode: spec.mode } : {},
|
|
734
|
+
...spec.thinking !== void 0 ? { thinking: spec.thinking } : {},
|
|
735
|
+
persist: true,
|
|
736
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...record.base ? { base: record.base } : {} }
|
|
737
|
+
}, { history: stored.length ? "skip" : history, delegation: record.delegation ?? delegation });
|
|
738
|
+
applied = true;
|
|
739
|
+
await persistAcceptedSpec(record.id, opened, { mode: spec.mode !== void 0, thinking: spec.thinking !== void 0 });
|
|
740
|
+
if (history === "replay") replayHistory(connection, record.id, stored);
|
|
741
|
+
return opened;
|
|
742
|
+
} catch (error) {
|
|
743
|
+
if (applied) throw error;
|
|
744
|
+
detach(connection, record.id);
|
|
745
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
746
|
+
throw error;
|
|
747
|
+
} finally {
|
|
748
|
+
clearOpening(record.id);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
async function persistAcceptedSpec(id, accepted, fields) {
|
|
752
|
+
const record = records.get(id);
|
|
753
|
+
if (!record?.spec || !fields.mode && !fields.thinking) return;
|
|
754
|
+
record.spec = {
|
|
755
|
+
...record.spec,
|
|
756
|
+
...fields.mode ? { mode: accepted.mode } : {},
|
|
757
|
+
...fields.thinking ? { thinking: accepted.thinking } : {}
|
|
758
|
+
};
|
|
759
|
+
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
760
|
+
try {
|
|
761
|
+
await store?.put(record);
|
|
762
|
+
} catch (error) {
|
|
763
|
+
throw persistenceFailed(`the configuration of ${id}; the runtime already applied it`, error);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
const registry = home ? createRegistry(home) : void 0;
|
|
767
|
+
const worktrees = home && registry && process.platform !== "win32" ? createWorkspaceWorktrees(home, registry, async (directory, run) => {
|
|
768
|
+
if (!runtime.withWorkspaceMutation) throw new RegistryError(1005, "Runtime cannot prove safe worktree removal", { reason: "guard_unavailable" });
|
|
769
|
+
try {
|
|
770
|
+
return await runtime.withWorkspaceMutation(directory, run);
|
|
771
|
+
} catch (error) {
|
|
772
|
+
if (error?.data?.reason) throw new RegistryError(1004, "Workspace is in use or has retained assignment results", error.data);
|
|
773
|
+
throw error;
|
|
774
|
+
}
|
|
775
|
+
}, async (directory) => {
|
|
776
|
+
if (!runtime.registerWorkspace) throw new RegistryError(1005, "Runtime cannot register safe workspace ownership", { reason: "guard_unavailable" });
|
|
777
|
+
await runtime.registerWorkspace(directory);
|
|
778
|
+
}) : void 0;
|
|
779
|
+
const workspaceDescriptor = async (w) => worktrees ? worktrees.describe(w) : w;
|
|
780
|
+
const gitReader = registry ? createGitReader({ registry, log: (message, fields) => log.warn(message, { code: "ALPD_GIT_READ_FAILED", ...fields }) }) : void 0;
|
|
781
|
+
const terminals = home && registry ? createTerminalService({
|
|
782
|
+
home,
|
|
783
|
+
resolveWorkspace: (workspaceId) => registry.resolve(workspaceId),
|
|
784
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
785
|
+
...terminalOptions
|
|
786
|
+
}) : void 0;
|
|
787
|
+
const terminalCall = (run) => {
|
|
788
|
+
if (!terminals) throw new RpcError(ERROR.unavailable, "This alpd has no home: it serves no terminals", { reason: "terminal_unsupported" });
|
|
789
|
+
return run(terminals);
|
|
790
|
+
};
|
|
791
|
+
const attachmentCall = (run) => {
|
|
792
|
+
if (!attachments) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not store attachments (capability attachments is not listed)");
|
|
793
|
+
return run(attachments);
|
|
794
|
+
};
|
|
795
|
+
const gitCall = (run) => {
|
|
796
|
+
if (!gitReader) throw new RpcError(ERROR.unavailable, "Registry needs ALP_HOME");
|
|
797
|
+
return run(gitReader);
|
|
798
|
+
};
|
|
799
|
+
const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
|
|
800
|
+
const extensionOwners = /* @__PURE__ */ new Map();
|
|
801
|
+
const handlers = {
|
|
802
|
+
"extension.register": async (connection, params) => {
|
|
803
|
+
const method = params?.method;
|
|
804
|
+
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");
|
|
805
|
+
if (method.length > 128 || reservedNamespaces.has(method.split(".")[0]) && !originalMethods.has(method)) throw new RpcError(ERROR.protocol, "extension.register requires an extension namespace and a name of at most 128 characters");
|
|
806
|
+
if (originalMethods.has(method) || extensionOwners.has(method) || Object.hasOwn(handlers, method)) throw new RpcError(ERROR.conflict, `${method} is already registered`);
|
|
807
|
+
if ((methodOwners.get(connection)?.size ?? 0) >= 128 || extensionOwners.size >= 1024) throw new RpcError(ERROR.conflict, "too many registered extension methods");
|
|
808
|
+
extensionOwners.set(method, connection);
|
|
809
|
+
if (!methodOwners.has(connection)) methodOwners.set(connection, /* @__PURE__ */ new Set());
|
|
810
|
+
methodOwners.get(connection).add(method);
|
|
811
|
+
handlers[method] = async (_connection, invokeParams) => {
|
|
812
|
+
const owner = extensionOwners.get(method);
|
|
813
|
+
if (!owner || !connections.has(owner)) {
|
|
814
|
+
delete handlers[method];
|
|
815
|
+
extensionOwners.delete(method);
|
|
816
|
+
throw new RpcError(ERROR.notFound, `${method} is not available`);
|
|
817
|
+
}
|
|
818
|
+
return invokeExtended(owner, _connection, method, invokeParams ?? {});
|
|
819
|
+
};
|
|
820
|
+
return { registered: method };
|
|
821
|
+
},
|
|
822
|
+
"extension.unregister": async (connection, params) => {
|
|
823
|
+
const method = params?.method;
|
|
824
|
+
if (typeof method !== "string" || !method.trim()) throw new RpcError(ERROR.protocol, "extension.unregister requires a method name");
|
|
825
|
+
const owner = extensionOwners.get(method);
|
|
826
|
+
if (!owner) throw new RpcError(ERROR.notFound, `${method} is not registered`);
|
|
827
|
+
if (owner !== connection) throw new RpcError(ERROR.conflict, `${method} is owned by another connection`);
|
|
828
|
+
delete handlers[method];
|
|
829
|
+
extensionOwners.delete(method);
|
|
830
|
+
const owned = methodOwners.get(connection);
|
|
831
|
+
owned?.delete(method);
|
|
832
|
+
return { unregistered: method };
|
|
833
|
+
},
|
|
834
|
+
"daemon.status": async () => ({ pid: process.pid, startedAt, version, protocolVersion: PROTOCOL_VERSION, sessions: runtime.list().length, questions: runtime.questions().length, ...previousExit ? { previousExit } : {}, ...store ? { persistence: store.health() } : {}, health: await health() }),
|
|
835
|
+
"session.status"(_connection, { sessionId }) {
|
|
836
|
+
if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
|
|
837
|
+
const status = runtime.status(sessionId);
|
|
838
|
+
if (!status) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not live`);
|
|
839
|
+
return { status };
|
|
840
|
+
},
|
|
841
|
+
"session.message"(_connection, { sessionId, text }) {
|
|
842
|
+
runtime.message(sessionId, text);
|
|
843
|
+
return {};
|
|
844
|
+
},
|
|
845
|
+
/** The assignment log of a session's tree, from the run log. */
|
|
846
|
+
async "session.log"(_connection, { sessionId }) {
|
|
847
|
+
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
848
|
+
if (!runLogDir) return { rootId: root, entries: [] };
|
|
849
|
+
const text = await readFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`), "utf8").catch(() => "");
|
|
850
|
+
const entries = text.split("\n").filter(Boolean).flatMap((line) => {
|
|
851
|
+
try {
|
|
852
|
+
return [JSON.parse(line)];
|
|
853
|
+
} catch {
|
|
854
|
+
return [];
|
|
855
|
+
}
|
|
856
|
+
});
|
|
857
|
+
return { rootId: root, entries };
|
|
858
|
+
},
|
|
859
|
+
"question.list"(_connection, { projectRoot } = {}) {
|
|
860
|
+
return { questions: runtime.questions().filter((question) => projectRoot === void 0 || projectOf(question.rootId) === projectRoot) };
|
|
861
|
+
},
|
|
862
|
+
/**
|
|
863
|
+
* The questions waiting now; from then on this connection is told of `question` and
|
|
864
|
+
* `question.resolved` in every tree, or those of `projectRoot`, attached or not. Calling it
|
|
865
|
+
* again replaces the filter; it lasts as long as the connection (ALPD §15). With `turns`, also
|
|
866
|
+
* of `turn.ended` of every root; with `attention`, also of each root's attention, now and as it
|
|
867
|
+
* changes (docs/protocol/alp-json-rpc-v1.md §12.2).
|
|
868
|
+
*/
|
|
869
|
+
"question.watch"(connection, { projectRoot, turns, attention } = {}) {
|
|
870
|
+
watchers.set(connection, { projectRoot, turns: turns === true, attention: attention === true });
|
|
871
|
+
return {
|
|
872
|
+
questions: runtime.questions().filter((question) => projectRoot === void 0 || projectOf(question.rootId) === projectRoot),
|
|
873
|
+
...attention === true ? { attention: attentionOf(projectRoot) } : {}
|
|
874
|
+
};
|
|
875
|
+
},
|
|
876
|
+
/**
|
|
877
|
+
* Acknowledges a root's attention for every client, as Paseo's clear_agent_attention; with `at`,
|
|
878
|
+
* only the attention set then, so a look at an older turn end never hides a newer one (§12.2).
|
|
879
|
+
*/
|
|
880
|
+
async "session.attention.clear"(_connection, { sessionId, at }) {
|
|
881
|
+
if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
|
|
882
|
+
if (at !== void 0 && typeof at !== "string") throw new RpcError(-32602, "at must be a string");
|
|
883
|
+
const record = records.get(sessionId);
|
|
884
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
|
|
885
|
+
const attention = record.attention;
|
|
886
|
+
if (!attention || at !== void 0 && attention.at !== at) return { cleared: false };
|
|
887
|
+
const ack = {};
|
|
888
|
+
pendingAcks.set(record.id, ack);
|
|
889
|
+
record.attention = void 0;
|
|
890
|
+
try {
|
|
891
|
+
await store?.put(record);
|
|
892
|
+
} catch (error) {
|
|
893
|
+
if (pendingAcks.get(record.id) === ack && !record.attention) record.attention = attention;
|
|
894
|
+
throw persistenceFailed(`the attention of ${record.id}`, error);
|
|
895
|
+
} finally {
|
|
896
|
+
if (pendingAcks.get(record.id) === ack) pendingAcks.delete(record.id);
|
|
897
|
+
}
|
|
898
|
+
tellAttention(record.id, record.attention);
|
|
899
|
+
return { cleared: true };
|
|
900
|
+
},
|
|
901
|
+
/**
|
|
902
|
+
* The files of a directory whose path matches a query, read-only and confined to it: no link
|
|
903
|
+
* is followed, only names are read (docs/protocol/alp-json-rpc-v1.md §12.3, ALPD §15).
|
|
904
|
+
*/
|
|
905
|
+
async "workspace.files.search"(_connection, { projectRoot, query, limit } = {}) {
|
|
906
|
+
if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot) || path.resolve(projectRoot) !== projectRoot) {
|
|
907
|
+
throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute, normalized path", { reason: "invalid_path" });
|
|
908
|
+
}
|
|
909
|
+
try {
|
|
910
|
+
return await searchWorkspaceFiles(projectRoot, { query, limit });
|
|
911
|
+
} catch (error) {
|
|
912
|
+
if (error instanceof FilesError) throw new RpcError(ERROR.notFound, error.message, { reason: "not_directory" });
|
|
913
|
+
throw error;
|
|
914
|
+
}
|
|
915
|
+
},
|
|
916
|
+
/**
|
|
917
|
+
* The entries of a directory under projectRoot, and the content of a text file there:
|
|
918
|
+
* read-only, confined to it, no link followed, blocked paths always refused, .gitignore'd ones
|
|
919
|
+
* unless includeIgnored (docs/protocol/alp-json-rpc-v1.md §12.4, ALPD §15).
|
|
920
|
+
*/
|
|
921
|
+
async "workspace.files.list"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
922
|
+
return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
923
|
+
},
|
|
924
|
+
async "workspace.files.read"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
925
|
+
return filesCall(projectRoot, () => readWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
926
|
+
},
|
|
927
|
+
/** The project board: live claims, decisions and findings (ALPD §18). */
|
|
928
|
+
async "board.list"(_connection, { projectRoot } = {}) {
|
|
929
|
+
if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, "An absolute projectRoot is required");
|
|
930
|
+
return { pins: await runtime.board(projectRoot) };
|
|
931
|
+
},
|
|
932
|
+
/** Pauses delegation and wakes on a runtime, or everywhere (ALPD §29). */
|
|
933
|
+
"daemon.pause"(_connection, { runtime: kind, now = false, reason } = {}) {
|
|
934
|
+
try {
|
|
935
|
+
return runtime.pause({ ...kind === void 0 ? {} : { runtime: kind }, now: now === true, ...reason === void 0 ? {} : { reason } });
|
|
936
|
+
} catch (error) {
|
|
937
|
+
throw new RpcError(-32602, error?.message ?? String(error));
|
|
938
|
+
}
|
|
939
|
+
},
|
|
940
|
+
"daemon.resume"(_connection, { runtime: kind } = {}) {
|
|
941
|
+
try {
|
|
942
|
+
return runtime.resume(kind === void 0 ? {} : { runtime: kind });
|
|
943
|
+
} catch (error) {
|
|
944
|
+
throw new RpcError(-32602, error?.message ?? String(error));
|
|
945
|
+
}
|
|
946
|
+
},
|
|
947
|
+
"daemon.pauses"() {
|
|
948
|
+
return runtime.pauses();
|
|
949
|
+
},
|
|
950
|
+
"daemon.usage": (_connection, { refresh = false } = {}) => runtime.usage(refresh === true),
|
|
951
|
+
/** Asks a finished assignment, or the last one on a task, about its work (ALPD §27). */
|
|
952
|
+
async "assignment.recall"(_connection, { assignmentId, taskId, projectRoot, question } = {}) {
|
|
953
|
+
if (projectRoot !== void 0 && (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot))) throw new RpcError(-32602, "projectRoot must be absolute");
|
|
954
|
+
try {
|
|
955
|
+
return await runtime.recall({ assignmentId, taskId, projectRoot }, question);
|
|
956
|
+
} catch (error) {
|
|
957
|
+
throw new RpcError(ERROR.failed, error?.message ?? String(error));
|
|
958
|
+
}
|
|
959
|
+
},
|
|
960
|
+
"question.answer"(_connection, { questionId, text, dismiss = false, reason }) {
|
|
961
|
+
if (typeof questionId !== "string") throw new RpcError(-32602, "questionId is required");
|
|
962
|
+
if (dismiss !== true && typeof text !== "string") throw new RpcError(-32602, "text or dismiss is required");
|
|
963
|
+
const matches = runtime.questions().filter((question) => question.id === questionId || question.id.startsWith(questionId));
|
|
964
|
+
if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
|
|
965
|
+
runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason } : { text });
|
|
966
|
+
return { questionId: matches[0].id };
|
|
967
|
+
},
|
|
968
|
+
"daemon.shutdown": () => {
|
|
969
|
+
setImmediate(() => onShutdown?.());
|
|
970
|
+
return {};
|
|
971
|
+
},
|
|
972
|
+
"registry.owner": (_c, params) => registryCall(async () => {
|
|
973
|
+
const result = params.operation ? await registry.mutate(params.operation, params.args ?? {}, { requestId: params.requestId, ifRevision: params.ifRevision }) : void 0;
|
|
974
|
+
const { receipts: _receipts, ...metadata } = await registry.snapshot();
|
|
975
|
+
return { ...result ? { result } : {}, registry: metadata };
|
|
976
|
+
}),
|
|
977
|
+
"registry.worktree": (_c, p) => registryCall(() => worktrees.grants(p)),
|
|
978
|
+
"workspace.worktree.options": (_c, p) => registryCall(async () => {
|
|
979
|
+
const w = (await registry.snapshot()).workspaces.find((w2) => w2.id === p.workspaceId);
|
|
980
|
+
if (!w) throw new RegistryError(1001, "No workspace", { reason: "not_found" });
|
|
981
|
+
const grants = await worktrees.grants(p);
|
|
982
|
+
return { mappingIds: grants.mappings.filter((m) => m.source === (w.canonical ?? w.directory)).map((m) => m.id) };
|
|
983
|
+
}),
|
|
984
|
+
"workspace.worktree.create": (_c, p) => registryCall(async () => {
|
|
985
|
+
const result = await worktrees.mutate("create", p, p);
|
|
986
|
+
return { ...result, workspace: await workspaceDescriptor(result.workspace) };
|
|
987
|
+
}),
|
|
988
|
+
"workspace.worktree.remove": (_c, p) => registryCall(async () => {
|
|
989
|
+
const result = await worktrees.mutate("remove", p, p);
|
|
990
|
+
return { ...result, workspace: await workspaceDescriptor(result.workspace) };
|
|
991
|
+
}),
|
|
992
|
+
"workspace.git.status": (_c, p) => gitCall((reader) => reader.status(p.workspaceId)),
|
|
993
|
+
"workspace.git.diff": (_c, p) => gitCall((reader) => reader.diff({ workspaceId: p.workspaceId, compare: p.compare, path: p.path, cursor: p.cursor })),
|
|
994
|
+
"project.list": (_c, p) => registryList("projects", p),
|
|
995
|
+
"workspace.list": (_c, p) => registryList("workspaces", p),
|
|
996
|
+
"workspace.get": (_c, p) => registryCall(async () => {
|
|
997
|
+
await registry.resolve(p.workspaceId, void 0, true);
|
|
998
|
+
const r = await registry.snapshot();
|
|
999
|
+
return { workspace: { ...await workspaceDescriptor(r.workspaces.find((w) => w.id === p.workspaceId)), revision: r.revision }, revision: r.revision };
|
|
1000
|
+
}),
|
|
1001
|
+
"project.register": (_c, p) => registryMutation("project.register", p),
|
|
1002
|
+
"project.remove": (_c, p) => registryMutation("project.remove", p),
|
|
1003
|
+
"workspace.update": (_c, p) => registryMutation("workspace.update", p),
|
|
1004
|
+
"catalog.get": () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
|
|
1005
|
+
// attachment.* (§12.6): each call acts for its principal context; without the store (no home or
|
|
1006
|
+
// store, or Windows) alpd does not serve them, as for any method it does not know.
|
|
1007
|
+
// terminal.* (§12.10): each call acts for its principal context; input, resize and the stream
|
|
1008
|
+
// belong to the connection that attached the terminal.
|
|
1009
|
+
"terminal.create": (_c, p) => terminalCall((service) => service.create(principalOf(p), p)),
|
|
1010
|
+
"terminal.list": (_c, p) => terminalCall((service) => service.list(principalOf(p), p)),
|
|
1011
|
+
"terminal.attach": (c, p) => terminalCall((service) => service.attach(principalOf(p), c, p)),
|
|
1012
|
+
"terminal.input": (c, p) => terminalCall((service) => service.input(principalOf(p), c, p)),
|
|
1013
|
+
"terminal.resize": (c, p) => terminalCall((service) => service.resize(principalOf(p), c, p)),
|
|
1014
|
+
"terminal.close": (_c, p) => terminalCall((service) => service.close(principalOf(p), p)),
|
|
1015
|
+
"terminal.revoke": (_c, p) => terminalCall((service) => service.revoke(p.principalId)),
|
|
1016
|
+
"attachment.begin": (_c, p) => attachmentCall((store2) => store2.begin(principalOf(p), p)),
|
|
1017
|
+
"attachment.chunk": (_c, p) => attachmentCall((store2) => store2.chunk(principalOf(p), p)),
|
|
1018
|
+
"attachment.commit": (_c, p) => attachmentCall((store2) => store2.commit(principalOf(p), p)),
|
|
1019
|
+
"attachment.abort": (_c, p) => attachmentCall((store2) => store2.abort(principalOf(p), p)),
|
|
1020
|
+
"attachment.get": (_c, p) => attachmentCall((store2) => store2.get(principalOf(p), p)),
|
|
1021
|
+
"attachment.delete": (_c, p) => attachmentCall((store2) => store2.remove(principalOf(p), p)),
|
|
1022
|
+
async "session.create"(connection, { sessionId, workspaceId, spec, history = "skip", delegation = true, resume: resuming = false }) {
|
|
1023
|
+
if (workspaceId !== void 0) {
|
|
1024
|
+
if (!registry || typeof workspaceId !== "string") throw new RpcError(-32602, "Invalid workspaceId");
|
|
1025
|
+
try {
|
|
1026
|
+
spec = { ...spec, cwd: await registry.resolve(workspaceId, spec?.cwd) };
|
|
1027
|
+
} catch (e) {
|
|
1028
|
+
if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data);
|
|
1029
|
+
throw e;
|
|
1030
|
+
}
|
|
1031
|
+
const placements = (await registryCall(() => registry.snapshot())).sessions;
|
|
1032
|
+
const prior = Object.hasOwn(placements, sessionId) ? placements[sessionId] : void 0;
|
|
1033
|
+
if (prior && prior !== workspaceId) throw new RpcError(ERROR.conflict, "Session belongs to another workspace", { reason: "workspace_mismatch" });
|
|
1034
|
+
}
|
|
1035
|
+
if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
|
|
1036
|
+
if (worktrees) await registryCall(() => worktrees.assertAvailable(spec.cwd));
|
|
1037
|
+
if (sessionId !== void 0 && (typeof sessionId !== "string" || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, "Invalid session id");
|
|
1038
|
+
if (history !== "replay" && history !== "skip") throw new RpcError(-32602, "history must be replay or skip");
|
|
1039
|
+
const id = sessionId ?? `ses_${randomBytes(8).toString("hex")}`;
|
|
1040
|
+
await recovering.get(id);
|
|
1041
|
+
while (holds.has(id)) await holds.get(id).open;
|
|
1042
|
+
refuseFenced(id);
|
|
1043
|
+
let reservedWorkspaceId;
|
|
1044
|
+
const reserve = async () => {
|
|
1045
|
+
if (!registry) return;
|
|
1046
|
+
const directory = runtime.snapshot(id)?.projectRoot ?? records.get(id)?.session?.projectRoot ?? records.get(id)?.spec?.cwd ?? spec.cwd;
|
|
1047
|
+
if (workspaceId) await registryCall(() => registry.resolve(workspaceId, directory));
|
|
1048
|
+
if (Object.hasOwn((await registry.snapshot()).sessions, id)) return;
|
|
1049
|
+
if (workspaceId) await registryCall(() => registry.mutate("placement.assign", { sessionId: id, workspaceId }, { requestId: `reserve:${randomBytes(12).toString("hex")}` }));
|
|
1050
|
+
else await registryCall(() => registry.mutate("placement.prepare", { sessions: [{ id, projectRoot: directory }] }, { requestId: `prepare:${randomBytes(12).toString("hex")}` }));
|
|
1051
|
+
reservedWorkspaceId = (await registry.snapshot()).sessions[id];
|
|
1052
|
+
};
|
|
1053
|
+
const rollback = async () => {
|
|
1054
|
+
if (!registry || !reservedWorkspaceId) return;
|
|
1055
|
+
await registryCall(() => registry.mutate("placement.remove", { sessionId: id, workspaceId: reservedWorkspaceId }, { requestId: `rollback:${randomBytes(12).toString("hex")}` }));
|
|
1056
|
+
};
|
|
1057
|
+
const existing = runtime.snapshot(id);
|
|
1058
|
+
if (existing) {
|
|
1059
|
+
const agent = spec.agent ?? spec.restore?.agent;
|
|
1060
|
+
if (existing.parentId || agent !== void 0 && agent !== existing.agent) throw new RpcError(ERROR.failed, "Session is already open");
|
|
1061
|
+
await reserve();
|
|
1062
|
+
attach(connection, id);
|
|
1063
|
+
announce(connection, id, history);
|
|
1064
|
+
return { session: existing, attached: true };
|
|
1065
|
+
}
|
|
1066
|
+
const record = records.get(id);
|
|
1067
|
+
if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
|
|
1068
|
+
if (record) {
|
|
1069
|
+
await reserve();
|
|
1070
|
+
try {
|
|
1071
|
+
const session = await resume(connection, record, spec, history, delegation);
|
|
1072
|
+
return { session, attached: false, resumed: true, ...await persisted(id) };
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
if (!runtime.snapshot(id)) await rollback();
|
|
1075
|
+
throw error;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
const { restore: _restore, ...kept } = spec;
|
|
1079
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1080
|
+
const created = { version: 1, id, rootId: id, spec: kept, delegation, status: "initializing", createdAt: now, updatedAt: now };
|
|
1081
|
+
records.set(id, created);
|
|
1082
|
+
try {
|
|
1083
|
+
await store?.put(created);
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
if (records.get(id) === created) records.delete(id);
|
|
1086
|
+
throw persistenceFailed(`session ${id}; it was not started`, error);
|
|
1087
|
+
}
|
|
1088
|
+
try {
|
|
1089
|
+
await reserve();
|
|
1090
|
+
attach(connection, id);
|
|
1091
|
+
const session = await runtime.open(id, spec, { history, delegation });
|
|
1092
|
+
return { session, attached: false, ...await persisted(id) };
|
|
1093
|
+
} catch (error) {
|
|
1094
|
+
detach(connection, id);
|
|
1095
|
+
records.delete(id);
|
|
1096
|
+
await store?.remove(id, [id]);
|
|
1097
|
+
await rollback();
|
|
1098
|
+
throw error;
|
|
1099
|
+
}
|
|
1100
|
+
},
|
|
1101
|
+
/** The team and main a new root would run with, and the teams it may choose (ALPD §60). */
|
|
1102
|
+
async "session.preview"(_connection, { spec }) {
|
|
1103
|
+
if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
|
|
1104
|
+
return { preview: await runtime.preview(spec) };
|
|
1105
|
+
},
|
|
1106
|
+
/**
|
|
1107
|
+
* Watches a tree. With `after`, the cursor of the last event a client has, only later
|
|
1108
|
+
* events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
|
|
1109
|
+
* with the whole timeline. The replay and the live events that follow are in cursor order.
|
|
1110
|
+
*/
|
|
1111
|
+
async "session.history"(_connection, { sessionId, before, limit, maxBytes }) {
|
|
1112
|
+
known(sessionId);
|
|
1113
|
+
if (!store) throw new RpcError(1005, "Durable history unavailable");
|
|
1114
|
+
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
1115
|
+
try {
|
|
1116
|
+
return await store.history(root, sessionId, { before, limit, maxBytes });
|
|
1117
|
+
} catch (error) {
|
|
1118
|
+
if (error instanceof HistoryError) throw new RpcError(error.reason === "stale_cursor" ? 1004 : -32602, error.message, { reason: error.reason });
|
|
1119
|
+
throw error;
|
|
1120
|
+
}
|
|
1121
|
+
},
|
|
1122
|
+
async "session.attach"(connection, { sessionId, replay = true, after, generation }) {
|
|
1123
|
+
if (after !== void 0 && (!Number.isSafeInteger(after) || after < 0)) throw new RpcError(-32602, "after must be a cursor");
|
|
1124
|
+
known(sessionId);
|
|
1125
|
+
const root = rootIdOf(sessionId);
|
|
1126
|
+
for (; ; ) {
|
|
1127
|
+
while (holds.has(root)) await holds.get(root).open;
|
|
1128
|
+
refuseFenced(root);
|
|
1129
|
+
const revision = holdRevision;
|
|
1130
|
+
const found = known(sessionId);
|
|
1131
|
+
let stored = [];
|
|
1132
|
+
if (replay || store && !cursors.has(root)) {
|
|
1133
|
+
const memory = logs.get(root);
|
|
1134
|
+
const covered = !!memory?.length && (memory[0].cursor ?? 1) <= (after ?? 0) + 1;
|
|
1135
|
+
if (!covered) stored = store ? await store.timeline(root) : memory ?? [];
|
|
1136
|
+
}
|
|
1137
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1138
|
+
if (generation !== void 0) {
|
|
1139
|
+
const checkpoint = await store?.history(root, sessionId, { limit: 1 });
|
|
1140
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1141
|
+
if (checkpoint?.generation !== generation) throw new RpcError(1004, "History generation changed", { reason: "stale_cursor" });
|
|
1142
|
+
}
|
|
1143
|
+
const live2 = logs.get(root) ?? [];
|
|
1144
|
+
const tip = Math.max(cursors.get(root) ?? 0, stored.at(-1)?.cursor ?? 0, live2.at(-1)?.cursor ?? 0);
|
|
1145
|
+
if (generation !== void 0 && replay) {
|
|
1146
|
+
const covered = Math.max(after ?? 0, stored.at(-1)?.cursor ?? 0);
|
|
1147
|
+
const next = live2.find((envelope) => (envelope.cursor ?? 0) > covered)?.cursor;
|
|
1148
|
+
if (next !== void 0 && next > covered + 1 || next === void 0 && tip > covered) {
|
|
1149
|
+
throw new RpcError(1005, "History advanced beyond replay coverage; retry attach", { reason: "history_gap" });
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
const first = replay ? [...stored, ...live2].find((envelope) => envelope.cursor !== void 0)?.cursor : void 0;
|
|
1153
|
+
const reset = after !== void 0 && (after > tip || replay && after < tip && (first === void 0 || first > after + 1) || !!conversation?.discarded(records.get(root), after));
|
|
1154
|
+
const from = reset ? 0 : after ?? 0;
|
|
1155
|
+
attach(connection, root);
|
|
1156
|
+
if (replay) {
|
|
1157
|
+
let last = from;
|
|
1158
|
+
for (const envelope of stored) if ((envelope.cursor ?? 0) > last) {
|
|
1159
|
+
if (current(envelope)) deliver(connection, envelope);
|
|
1160
|
+
last = envelope.cursor ?? last;
|
|
1161
|
+
}
|
|
1162
|
+
for (const envelope of live2) if ((envelope.cursor ?? 0) > last) {
|
|
1163
|
+
if (current(envelope)) deliver(connection, envelope);
|
|
1164
|
+
last = envelope.cursor ?? last;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
announceQuestions(connection, root);
|
|
1168
|
+
return { session: root === found.id ? found : summary(root), cursor: tip, ...reset ? { reset: true } : {} };
|
|
1169
|
+
}
|
|
1170
|
+
},
|
|
1171
|
+
async "session.release"(connection, { sessionId }) {
|
|
1172
|
+
const root = rootOf.get(sessionId) ?? sessionId;
|
|
1173
|
+
detach(connection, root);
|
|
1174
|
+
return { closed: await reap(root) };
|
|
1175
|
+
},
|
|
1176
|
+
async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content, ...context }) {
|
|
1177
|
+
if (typeof clientMessageId !== "string" || !Array.isArray(content)) throw new RpcError(-32602, "clientMessageId and content are required");
|
|
1178
|
+
if (delivery !== "auto" && delivery !== "steer") throw new RpcError(-32602, "delivery must be auto or steer");
|
|
1179
|
+
const images = content.filter((part) => part?.type === "image");
|
|
1180
|
+
if (images.length > PROMPT_IMAGES.maxCount) throw new RpcError(-32602, `A prompt takes at most ${PROMPT_IMAGES.maxCount} images`);
|
|
1181
|
+
let total = 0;
|
|
1182
|
+
for (const image of images) {
|
|
1183
|
+
const bytes = base64Bytes(image.data);
|
|
1184
|
+
total += bytes;
|
|
1185
|
+
if (bytes > PROMPT_IMAGES.maxBytes) throw new RpcError(-32602, `An image in a prompt is at most ${PROMPT_IMAGES.maxBytes} bytes`);
|
|
1186
|
+
if (total > PROMPT_IMAGES.maxTotalBytes) throw new RpcError(-32602, `The images of a prompt are at most ${PROMPT_IMAGES.maxTotalBytes} bytes together`);
|
|
1187
|
+
}
|
|
1188
|
+
const attached2 = content.filter((part) => part?.type === "attachment");
|
|
1189
|
+
let resolved = [];
|
|
1190
|
+
if (attached2.length) {
|
|
1191
|
+
if (!attachments || !store) throw new RpcError(ERROR.unavailable, "This alpd does not store attachments", { reason: "attachment_unsupported" });
|
|
1192
|
+
resolved = await attachments.resolve(principalOf(context), sessionId, attached2.map((part) => part.attachmentId));
|
|
1193
|
+
}
|
|
1194
|
+
let index = 0;
|
|
1195
|
+
const delivered = attached2.length ? content.map((part) => part?.type === "attachment" ? resolved[index++] : part) : content;
|
|
1196
|
+
const fingerprinted = attached2.length ? content.map((part) => part?.type === "attachment" ? { type: "attachment", attachmentId: part.attachmentId, sha256: resolved.find((entry) => entry.attachmentId === part.attachmentId).sha256 } : part) : content;
|
|
1197
|
+
const send = async () => {
|
|
1198
|
+
live(sessionId);
|
|
1199
|
+
await runtime.prompt(sessionId, { clientMessageId, delivery, content: delivered });
|
|
1200
|
+
};
|
|
1201
|
+
if (!store) {
|
|
1202
|
+
await gated(sessionId, send);
|
|
1203
|
+
return {};
|
|
1204
|
+
}
|
|
1205
|
+
if (!attached2.length) return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
1206
|
+
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content: fingerprinted }), send, {
|
|
1207
|
+
prepare: async (key) => {
|
|
1208
|
+
if (!runtime.takesAttachments?.(sessionId)) throw new RpcError(ERROR.unavailable, "This session's runtime cannot read attachments yet; they stay stored and the prompt was not sent", { reason: "attachment_unsupported" });
|
|
1209
|
+
await attachments.pin(`prompt:${key}`, sessionId, resolved.map((entry) => entry.attachmentId));
|
|
1210
|
+
},
|
|
1211
|
+
abandon: (key) => attachments.release(`prompt:${key}`)
|
|
1212
|
+
});
|
|
1213
|
+
},
|
|
1214
|
+
/** A new root from a root's conversation cut at a turn, or from a branch a rewind set aside (§12.7). */
|
|
1215
|
+
async "session.fork"(_connection, params) {
|
|
1216
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not fork conversations (capability session.fork is not listed)");
|
|
1217
|
+
return conversation.fork({ ...params, principal: principalOf(params) });
|
|
1218
|
+
},
|
|
1219
|
+
/** The root's conversation from before a turn on, same id; the later turns stay a recoverable branch, files untouched (§12.7). */
|
|
1220
|
+
async "session.rewind"(_connection, params) {
|
|
1221
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not rewind conversations (capability session.rewind is not listed)");
|
|
1222
|
+
return conversation.rewind(params);
|
|
1223
|
+
},
|
|
1224
|
+
/** Restarts a live root's native process on its own conversation at the idle barrier (§12.8). */
|
|
1225
|
+
async "session.reload"(_connection, params) {
|
|
1226
|
+
if (!conversation?.reloads) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not reload sessions (capability session.reload is not listed)");
|
|
1227
|
+
return conversation.reload(params);
|
|
1228
|
+
},
|
|
1229
|
+
/** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
|
|
1230
|
+
async "session.resumeCommand"(_connection, { sessionId }) {
|
|
1231
|
+
if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd has no resume command (capability session.resumeCommand is not listed)");
|
|
1232
|
+
return conversation.resumeCommand(sessionId);
|
|
1233
|
+
},
|
|
1234
|
+
async "session.interrupt"(_connection, { sessionId, turnId }) {
|
|
1235
|
+
if (turnId !== void 0) {
|
|
1236
|
+
if (typeof turnId !== "string" || !turnId) throw new RpcError(-32602, "turnId must be a nonempty string");
|
|
1237
|
+
if (!runtime.interruptTurn) throw new RpcError(ERROR.unavailable, "This runtime cannot interrupt a specific turn");
|
|
1238
|
+
return { interrupted: await runtime.interruptTurn(sessionId, turnId) };
|
|
1239
|
+
}
|
|
1240
|
+
await runtime.interrupt(sessionId);
|
|
1241
|
+
return {};
|
|
1242
|
+
},
|
|
1243
|
+
/**
|
|
1244
|
+
* A session's permissions mode while idle; with model, thinking or team, a live root's configuration
|
|
1245
|
+
* at the idle barrier through a restart on the same conversation (§12.9, capability session.configure.live).
|
|
1246
|
+
*/
|
|
1247
|
+
async "session.configure"(_connection, params) {
|
|
1248
|
+
const { sessionId, mode } = params;
|
|
1249
|
+
if (params.model !== void 0 || params.thinking !== void 0 || params.team !== void 0) {
|
|
1250
|
+
if (!conversation?.configures) throw new RpcError(RPC_ERROR.invalidParams, "This alpd changes only the mode of a session (capability session.configure.live is not listed)", { reason: "invalid_params" });
|
|
1251
|
+
return conversation.configure(params);
|
|
1252
|
+
}
|
|
1253
|
+
return { session: await runtime.configure(sessionId, { mode }, {
|
|
1254
|
+
onApplied: (accepted) => persistAcceptedSpec(sessionId, accepted, { mode: true })
|
|
1255
|
+
}) };
|
|
1256
|
+
},
|
|
1257
|
+
/** What a change of model, thinking, team or mode would run a live root with (§12.9). */
|
|
1258
|
+
async "session.configure.preview"(_connection, params) {
|
|
1259
|
+
if (!conversation?.configures) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not preview configurations (capability session.configure.live is not listed)");
|
|
1260
|
+
return { preview: await conversation.configurePreview(params) };
|
|
1261
|
+
},
|
|
1262
|
+
async "session.close"(_connection, { sessionId }) {
|
|
1263
|
+
await runtime.close(sessionId);
|
|
1264
|
+
return {};
|
|
1265
|
+
},
|
|
1266
|
+
/** The user's name for a root, in place of its first prompt (ALPD §61). */
|
|
1267
|
+
async "session.rename"(_connection, { sessionId, title }) {
|
|
1268
|
+
if (typeof title !== "string" || !title.trim() || [...title].length > 200) throw new RpcError(-32602, "title must be 1 to 200 characters");
|
|
1269
|
+
const record = rootRecord(sessionId);
|
|
1270
|
+
const before = record.title;
|
|
1271
|
+
Object.assign(record, { title: title.replace(/\s+/g, " ").trim() });
|
|
1272
|
+
try {
|
|
1273
|
+
await store?.put(record);
|
|
1274
|
+
} catch (error) {
|
|
1275
|
+
record.title = before;
|
|
1276
|
+
throw persistenceFailed(`the name of ${record.id}`, error);
|
|
1277
|
+
}
|
|
1278
|
+
announceTitle(record.id, record.title);
|
|
1279
|
+
return { session: summary(record.id) };
|
|
1280
|
+
},
|
|
1281
|
+
/** Sets a root aside: it closes, with its tree, and leaves the lists until unarchived (ALPD §61). */
|
|
1282
|
+
async "session.archive"(_connection, { sessionId, archived = true }) {
|
|
1283
|
+
const record = rootRecord(sessionId);
|
|
1284
|
+
if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
|
|
1285
|
+
const before = { archived: record.archived, attention: record.attention };
|
|
1286
|
+
Object.assign(record, { archived: archived === true ? true : void 0 }, archived === true ? { attention: void 0 } : {});
|
|
1287
|
+
if (archived === true) pendingAcks.delete(record.id);
|
|
1288
|
+
try {
|
|
1289
|
+
await store?.put(record);
|
|
1290
|
+
} catch (error) {
|
|
1291
|
+
Object.assign(record, before);
|
|
1292
|
+
throw persistenceFailed(`the archive state of ${record.id}`, error);
|
|
1293
|
+
}
|
|
1294
|
+
if (before.attention && !record.attention) tellAttention(record.id, void 0);
|
|
1295
|
+
return { session: summary(record.id) };
|
|
1296
|
+
},
|
|
1297
|
+
"session.get"(_connection, { sessionId }) {
|
|
1298
|
+
return { session: known(sessionId) };
|
|
1299
|
+
},
|
|
1300
|
+
/**
|
|
1301
|
+
* Roots first, then newest first, by id last. With `limit` a page, and `nextCursor` while more
|
|
1302
|
+
* follow; `cursor` continues after the session it names; `query` keeps the sessions whose title
|
|
1303
|
+
* or id holds every word of it; `projectRoots` those of any of these projects, as a gateway lists
|
|
1304
|
+
* a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
|
|
1305
|
+
*/
|
|
1306
|
+
"session.list"(_connection, { projectRoot, projectRoots, rootsOnly = false, includeClosed = false, includeArchived = false, limit, cursor, query } = {}) {
|
|
1307
|
+
const projects = Array.isArray(projectRoots) ? new Set(projectRoots) : void 0;
|
|
1308
|
+
const after = cursor === void 0 ? void 0 : listCursor.decode(cursor);
|
|
1309
|
+
const words = typeof query === "string" ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
|
|
1310
|
+
const ids = /* @__PURE__ */ new Set([...runtime.list().map((session) => session.id), ...records.keys()]);
|
|
1311
|
+
const sessions = [...ids].map(summary).filter((session) => !!session).filter((session) => includeClosed || session.status === "idle" || session.status === "running").filter((session) => includeArchived || !session.archived).filter((session) => !rootsOnly || !session.parentId).filter((session) => projectRoot === void 0 || session.projectRoot === projectRoot).filter((session) => !projects || projects.has(session.projectRoot)).filter((session) => !words.length || words.every((word) => `${session.title ?? ""}
|
|
1312
|
+
${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(listCursor.key(a), listCursor.key(b))).filter((session) => !after || listCursor.compare(listCursor.key(session), after) > 0);
|
|
1313
|
+
if (limit === void 0 || sessions.length <= limit) return { sessions };
|
|
1314
|
+
const page = sessions.slice(0, limit);
|
|
1315
|
+
return { sessions: page, nextCursor: listCursor.encode(listCursor.key(page.at(-1))) };
|
|
1316
|
+
},
|
|
1317
|
+
/**
|
|
1318
|
+
* A scheduled continuation of a root session: alpd opens the turn itself
|
|
1319
|
+
* when the time comes, without a user message. The target is a live root session of
|
|
1320
|
+
* the project; a session that is closed when the job is due fails the job, and the
|
|
1321
|
+
* reason is kept.
|
|
1322
|
+
*/
|
|
1323
|
+
async "schedule.create"(_connection, { projectRoot, sessionId, dueAt, prompt } = {}) {
|
|
1324
|
+
if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
|
|
1325
|
+
if (typeof projectRoot !== "string" || typeof sessionId !== "string" || typeof dueAt !== "string" || typeof prompt !== "string") {
|
|
1326
|
+
throw new RpcError(RPC_ERROR.invalidParams, "projectRoot, sessionId, dueAt and prompt are required");
|
|
1327
|
+
}
|
|
1328
|
+
if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute path");
|
|
1329
|
+
const snapshot = runtime.snapshot(sessionId);
|
|
1330
|
+
if (!snapshot) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not open`);
|
|
1331
|
+
if (snapshot.parentId) throw new RpcError(RPC_ERROR.invalidParams, "A scheduled job continues a root session");
|
|
1332
|
+
if (projectKey(snapshot.projectRoot) !== projectKey(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, "That session does not belong to that project");
|
|
1333
|
+
if (!snapshot.persistent || !snapshot.threadId) log.warn(`a job on ${sessionId} cannot survive a restart of alpd: the session keeps no thread to resume`, { code: "ALP_SCHEDULE_SESSION_NOT_RESUMABLE", sessionId });
|
|
1334
|
+
scheduler?.holdSession(sessionId);
|
|
1335
|
+
try {
|
|
1336
|
+
const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt });
|
|
1337
|
+
scheduler?.hold(job);
|
|
1338
|
+
return { job };
|
|
1339
|
+
} catch (error) {
|
|
1340
|
+
throw scheduleFailed(error);
|
|
1341
|
+
} finally {
|
|
1342
|
+
scheduler?.releaseSession(sessionId);
|
|
1343
|
+
}
|
|
1344
|
+
},
|
|
1345
|
+
/** The jobs of this project, oldest first by the time they are due. */
|
|
1346
|
+
async "schedule.list"(_connection, { projectRoot, status } = {}) {
|
|
1347
|
+
if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
|
|
1348
|
+
requestedProject(projectRoot);
|
|
1349
|
+
try {
|
|
1350
|
+
return { jobs: await schedules.list({ projectRoot, status }) };
|
|
1351
|
+
} catch (error) {
|
|
1352
|
+
throw scheduleFailed(error);
|
|
1353
|
+
}
|
|
1354
|
+
},
|
|
1355
|
+
/** One job, with what became of it. */
|
|
1356
|
+
async "schedule.get"(_connection, { id, projectRoot } = {}) {
|
|
1357
|
+
if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
|
|
1358
|
+
if (typeof id !== "string") throw new RpcError(RPC_ERROR.invalidParams, "id is required");
|
|
1359
|
+
requestedProject(projectRoot);
|
|
1360
|
+
const job = await storeJob(id, projectRoot);
|
|
1361
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1362
|
+
return { job };
|
|
1363
|
+
},
|
|
1364
|
+
/** A job that will not run: cancelled before its time. */
|
|
1365
|
+
async "schedule.cancel"(_connection, { id, projectRoot } = {}) {
|
|
1366
|
+
if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
|
|
1367
|
+
if (typeof id !== "string") throw new RpcError(RPC_ERROR.invalidParams, "id is required");
|
|
1368
|
+
requestedProject(projectRoot);
|
|
1369
|
+
const job = await storeJob(id, projectRoot);
|
|
1370
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1371
|
+
if (scheduler?.delivering(id)) throw new RpcError(ERROR.conflict, `Job ${id} is being delivered now`, { reason: "key_conflict" });
|
|
1372
|
+
try {
|
|
1373
|
+
const cancelled = await schedules.cancel(id, { projectRoot });
|
|
1374
|
+
scheduler?.release(cancelled);
|
|
1375
|
+
return { job: cancelled };
|
|
1376
|
+
} catch (error) {
|
|
1377
|
+
throw scheduleFailed(error);
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
const registryCall = async (run) => {
|
|
1382
|
+
if (!registry) throw new RpcError(ERROR.unavailable, "Registry needs ALP_HOME");
|
|
1383
|
+
try {
|
|
1384
|
+
return await run();
|
|
1385
|
+
} catch (e) {
|
|
1386
|
+
if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data);
|
|
1387
|
+
throw new RpcError(ERROR.failed, e instanceof Error ? e.message : String(e), { reason: "persistence_failed" });
|
|
1388
|
+
}
|
|
1389
|
+
};
|
|
1390
|
+
const registryList = async (kind, params = {}) => registryCall(async () => {
|
|
1391
|
+
const r = await registry.snapshot();
|
|
1392
|
+
const allowed = params.projectRoots;
|
|
1393
|
+
let entries = r[kind].filter((e) => kind === "projects" ? params.includeRemoved || !e.removedAt : params.includeArchived || !e.archivedAt && !r.projects.find((p) => p.id === e.projectId)?.removedAt);
|
|
1394
|
+
if (allowed !== void 0) {
|
|
1395
|
+
entries = (await Promise.all(entries.map(async (e) => {
|
|
1396
|
+
const directory = kind === "projects" ? e.root : e.directory;
|
|
1397
|
+
const canonical = await fsRealpath(directory).catch(() => void 0);
|
|
1398
|
+
return canonical && (!e.canonical || canonical === e.canonical) && allowed.includes(canonical) ? e : void 0;
|
|
1399
|
+
}))).filter(Boolean);
|
|
1400
|
+
}
|
|
1401
|
+
const offset = params.cursor === void 0 ? 0 : Number(params.cursor);
|
|
1402
|
+
if (!Number.isSafeInteger(offset) || offset < 0) throw new RpcError(-32602, "Invalid registry cursor");
|
|
1403
|
+
const limit = params.limit ?? 100;
|
|
1404
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new RpcError(-32602, "Invalid registry limit");
|
|
1405
|
+
return { [kind]: await Promise.all(entries.slice(offset, offset + limit).map(async (e) => ({ ...kind === "workspaces" ? await workspaceDescriptor(e) : e, revision: r.revision }))), revision: r.revision, total: entries.length, nextCursor: offset + limit < entries.length ? String(offset + limit) : null };
|
|
1406
|
+
});
|
|
1407
|
+
const registryMutation = (method, p) => registryCall(async () => {
|
|
1408
|
+
if (!Number.isSafeInteger(p.ifRevision) || p.ifRevision < 0) throw new RpcError(-32602, "ifRevision is required");
|
|
1409
|
+
const { requestId, ifRevision, authorizedRoots, ...args } = p;
|
|
1410
|
+
const result = await registry.mutate(method, args, { requestId, ifRevision, allowedRoots: authorizedRoots });
|
|
1411
|
+
return result.workspace ? { ...result, workspace: await workspaceDescriptor(result.workspace) } : result;
|
|
1412
|
+
});
|
|
1413
|
+
runtime.bindSchedules?.(async (action, params) => handlers[`schedule.${action}`](void 0, params));
|
|
1414
|
+
for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
|
|
1415
|
+
Object.setPrototypeOf(handlers, null);
|
|
1416
|
+
const originalMethods = /* @__PURE__ */ new Set([...Object.keys(handlers), ...RPC_METHODS]);
|
|
1417
|
+
const reservedNamespaces = new Set([...originalMethods].map((method) => method.split(".")[0]));
|
|
1418
|
+
async function invokeExtended(owner, caller, method, params) {
|
|
1419
|
+
if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, "too many pending extension calls");
|
|
1420
|
+
const id = ++owner.nextId;
|
|
1421
|
+
const invocation = { jsonrpc: "2.0", id, method: "extension.invoke", params: { method, params } };
|
|
1422
|
+
if (Buffer.byteLength(encodeFrame(invocation), "utf8") > MAX_FRAME) throw new RpcError(-32600, "ALP daemon frame exceeds size limit");
|
|
1423
|
+
return new Promise((resolve, reject) => {
|
|
1424
|
+
const timer = setTimeout(() => {
|
|
1425
|
+
owner.pending.delete(id);
|
|
1426
|
+
reject(new RpcError(ERROR.failed, `${method} timed out`));
|
|
1427
|
+
}, 3e4);
|
|
1428
|
+
owner.pending.set(id, { resolve, reject, timer, caller });
|
|
1429
|
+
try {
|
|
1430
|
+
owner.send(invocation);
|
|
1431
|
+
} catch (error) {
|
|
1432
|
+
clearTimeout(timer);
|
|
1433
|
+
owner.pending.delete(id);
|
|
1434
|
+
reject(error);
|
|
1435
|
+
}
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
async function health() {
|
|
1439
|
+
const checks = [{ id: "accepting", ok: !closing, ...closing ? { code: "ALP_SHUTTING_DOWN", message: "alpd is shutting down" } : {} }];
|
|
1440
|
+
if (store) {
|
|
1441
|
+
const probe = await store.probe();
|
|
1442
|
+
checks.push({ id: "state", ...probe });
|
|
1443
|
+
const failing = store.failing();
|
|
1444
|
+
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` } : {} });
|
|
1445
|
+
}
|
|
1446
|
+
return { live: true, ready: checks.every((check) => check.ok), checks };
|
|
1447
|
+
}
|
|
1448
|
+
async function filesCall(projectRoot, read) {
|
|
1449
|
+
if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot) || path.resolve(projectRoot) !== projectRoot) {
|
|
1450
|
+
throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute, normalized path", { reason: "invalid_path" });
|
|
1451
|
+
}
|
|
1452
|
+
try {
|
|
1453
|
+
return await read();
|
|
1454
|
+
} catch (error) {
|
|
1455
|
+
if (error instanceof FileAccessError) throw new RpcError(error.code, error.message, { reason: error.reason });
|
|
1456
|
+
if (error instanceof FilesError) throw new RpcError(ERROR.notFound, error.message, { reason: "not_directory" });
|
|
1457
|
+
log.error("workspace file read failed", { code: "ALPD_FILES_FAILED", error });
|
|
1458
|
+
throw new RpcError(ERROR.failed, "alpd could not read the workspace file");
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
const capabilities = [...runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : [], CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : [], ...schedules ? [CAPABILITY.schedule] : [], ...registry ? ["workspace.registry", CAPABILITY.workspaceGit] : [], ...worktrees ? ["workspace.worktree"] : [], ...attachments ? [CAPABILITY.attachments] : [], ...conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : [], ...conversation?.reloads ? [CAPABILITY.sessionReload] : [], ...conversation?.configures ? [CAPABILITY.sessionConfigureLive] : [], ...conversation ? [CAPABILITY.sessionResumeCommand] : [], ...operations.capabilities];
|
|
1462
|
+
function fits(response) {
|
|
1463
|
+
if (frameBytes(response) <= MAX_FRAME) return response;
|
|
1464
|
+
log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
|
|
1465
|
+
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" } } };
|
|
1466
|
+
}
|
|
1467
|
+
async function dispatch(connection, message, receivedBytes) {
|
|
1468
|
+
const single = !!message && typeof message === "object" && !Array.isArray(message);
|
|
1469
|
+
const { id, method, params } = single ? message : {};
|
|
1470
|
+
const respond = (body) => connection.send(fits({ jsonrpc: "2.0", id: validId(id) ? id : null, ...body }));
|
|
1471
|
+
try {
|
|
1472
|
+
if (Array.isArray(message)) throw new RpcError(RPC_ERROR.invalidRequest, "Batch requests are not supported", { reason: "batch_unsupported" });
|
|
1473
|
+
if (!single || message.jsonrpc !== "2.0") throw new RpcError(RPC_ERROR.invalidRequest, "Invalid request");
|
|
1474
|
+
const oversized = (receivedBytes ?? frameBytes(message)) > MAX_FRAME;
|
|
1475
|
+
if (!Object.prototype.hasOwnProperty.call(message, "method")) {
|
|
1476
|
+
const hasResult = Object.prototype.hasOwnProperty.call(message, "result");
|
|
1477
|
+
const hasError = Object.prototype.hasOwnProperty.call(message, "error");
|
|
1478
|
+
if (id === void 0 || id === null || hasResult === hasError) return;
|
|
1479
|
+
const waiter = connection.pending.get(id);
|
|
1480
|
+
if (!waiter) return;
|
|
1481
|
+
connection.pending.delete(id);
|
|
1482
|
+
clearTimeout(waiter.timer);
|
|
1483
|
+
if (oversized) {
|
|
1484
|
+
waiter.reject(new RpcError(RPC_ERROR.invalidRequest, "ALP daemon frame exceeds size limit"));
|
|
1485
|
+
return;
|
|
1486
|
+
}
|
|
1487
|
+
if (hasError) waiter.reject(new RpcError(message.error?.code ?? ERROR.failed, message.error?.message ?? "extension call failed", message.error?.data));
|
|
1488
|
+
else waiter.resolve(message.result);
|
|
1489
|
+
return;
|
|
1490
|
+
}
|
|
1491
|
+
if (oversized) throw new RpcError(RPC_ERROR.invalidRequest, "ALP daemon frame exceeds size limit", { reason: "frame_too_large" });
|
|
1492
|
+
if (typeof method !== "string") throw new RpcError(RPC_ERROR.invalidRequest, "Invalid request");
|
|
1493
|
+
if (id === void 0) {
|
|
1494
|
+
log.debug("ignored a notification", { code: "ALP_IPC_NOTIFICATION_IGNORED", method });
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1497
|
+
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" });
|
|
1498
|
+
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" });
|
|
1499
|
+
if (method === "daemon.hello") {
|
|
1500
|
+
if (params?.protocolVersion !== PROTOCOL_VERSION) throw new RpcError(ERROR.protocol, `ALP daemon speaks protocol ${PROTOCOL_VERSION}; restart it after upgrading (alp daemon restart)`, { reason: "protocol_version", supported: [PROTOCOL_VERSION] });
|
|
1501
|
+
const issues2 = validateParams(method, params);
|
|
1502
|
+
if (issues2.length) throw invalidParams(issues2);
|
|
1503
|
+
connection.helloed = true;
|
|
1504
|
+
const terminalLimits = await terminals?.advertised();
|
|
1505
|
+
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities: terminalLimits ? [...capabilities, CAPABILITY.terminal] : capabilities, ...attachments ? { attachmentLimits: attachments.limits } : {}, ...terminalLimits ? { terminalLimits } : {} } });
|
|
1506
|
+
return;
|
|
1507
|
+
}
|
|
1508
|
+
if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first", { reason: "hello_required" });
|
|
1509
|
+
await restored;
|
|
1510
|
+
if (!connections.has(connection)) return;
|
|
1511
|
+
const handler = Object.hasOwn(handlers, method) ? handlers[method] : void 0;
|
|
1512
|
+
if (!handler) throw new RpcError(RPC_ERROR.methodNotFound, `Unknown method '${method}'`);
|
|
1513
|
+
const issues = validateParams(method, params);
|
|
1514
|
+
if (issues?.length) throw invalidParams(issues);
|
|
1515
|
+
respond({ result: await handler(connection, params ?? {}) });
|
|
1516
|
+
} catch (error) {
|
|
1517
|
+
const code = error instanceof RpcError ? error.code : /is not open/.test(String(error?.message)) ? ERROR.notFound : ERROR.failed;
|
|
1518
|
+
const data = error instanceof RpcError && error.data !== void 0 ? { data: error.data } : {};
|
|
1519
|
+
if (!(error instanceof RpcError) && code === ERROR.failed) log.warn(`${method} failed`, { code: "ALP_RPC_FAILED", requestId: id, sessionId: params?.sessionId, method, error });
|
|
1520
|
+
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 });
|
|
1521
|
+
respond({ error: { code, message: error instanceof Error ? error.message : String(error), ...data } });
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
const methodOwners = /* @__PURE__ */ new Map();
|
|
1525
|
+
function disconnect(connection) {
|
|
1526
|
+
const owned = methodOwners.get(connection);
|
|
1527
|
+
if (owned) for (const method of owned) {
|
|
1528
|
+
delete handlers[method];
|
|
1529
|
+
extensionOwners.delete(method);
|
|
1530
|
+
}
|
|
1531
|
+
methodOwners.delete(connection);
|
|
1532
|
+
for (const [id, waiting] of connection.pending) {
|
|
1533
|
+
clearTimeout(waiting.timer);
|
|
1534
|
+
waiting.reject(new Error("ALP daemon connection closed"));
|
|
1535
|
+
}
|
|
1536
|
+
connection.pending.clear();
|
|
1537
|
+
for (const owner of connections) for (const [id, waiting] of owner.pending) {
|
|
1538
|
+
if (waiting.caller !== connection) continue;
|
|
1539
|
+
clearTimeout(waiting.timer);
|
|
1540
|
+
owner.pending.delete(id);
|
|
1541
|
+
waiting.reject(new Error("ALP daemon caller connection closed"));
|
|
1542
|
+
}
|
|
1543
|
+
connections.delete(connection);
|
|
1544
|
+
watchers.delete(connection);
|
|
1545
|
+
terminals?.disconnect(connection);
|
|
1546
|
+
for (const root of [...connection.roots]) {
|
|
1547
|
+
detach(connection, root);
|
|
1548
|
+
void reap(root);
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
const server = net.createServer((socket) => {
|
|
1552
|
+
if (closing) {
|
|
1553
|
+
socket.destroy();
|
|
1554
|
+
return;
|
|
1555
|
+
}
|
|
1556
|
+
const connection = {
|
|
1557
|
+
socket,
|
|
1558
|
+
helloed: false,
|
|
1559
|
+
roots: /* @__PURE__ */ new Set(),
|
|
1560
|
+
send(message) {
|
|
1561
|
+
if (!socket.destroyed) socket.write(encodeFrame(message));
|
|
1562
|
+
},
|
|
1563
|
+
nextId: 0,
|
|
1564
|
+
pending: /* @__PURE__ */ new Map()
|
|
1565
|
+
};
|
|
1566
|
+
connections.add(connection);
|
|
1567
|
+
let buffer = "";
|
|
1568
|
+
let bytes = 0;
|
|
1569
|
+
socket.setEncoding("utf8");
|
|
1570
|
+
const tooLarge = () => {
|
|
1571
|
+
log.warn("closed a connection that sent a frame over the size limit", { code: "ALP_IPC_FRAME_TOO_LARGE" });
|
|
1572
|
+
buffer = "";
|
|
1573
|
+
bytes = 0;
|
|
1574
|
+
socket.destroy();
|
|
1575
|
+
};
|
|
1576
|
+
socket.on("data", (chunk) => {
|
|
1577
|
+
buffer += chunk;
|
|
1578
|
+
bytes += Buffer.byteLength(chunk, "utf8");
|
|
1579
|
+
if (!chunk.includes("\n")) {
|
|
1580
|
+
if (bytes >= MAX_FRAME) tooLarge();
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
let start = 0;
|
|
1584
|
+
for (let index = buffer.indexOf("\n", buffer.length - chunk.length); index >= 0; index = buffer.indexOf("\n", start)) {
|
|
1585
|
+
const line = buffer.slice(start, index);
|
|
1586
|
+
start = index + 1;
|
|
1587
|
+
if (Buffer.byteLength(line, "utf8") + 1 > MAX_FRAME) {
|
|
1588
|
+
tooLarge();
|
|
1589
|
+
return;
|
|
1590
|
+
}
|
|
1591
|
+
if (!line.trim()) continue;
|
|
1592
|
+
let message;
|
|
1593
|
+
try {
|
|
1594
|
+
message = JSON.parse(line);
|
|
1595
|
+
} catch {
|
|
1596
|
+
log.warn("a client sent a line that is not JSON", { code: "ALP_IPC_PARSE_ERROR", bytes: line.length });
|
|
1597
|
+
connection.send({ jsonrpc: "2.0", id: null, error: { code: RPC_ERROR.parseError, message: "Parse error" } });
|
|
1598
|
+
continue;
|
|
1599
|
+
}
|
|
1600
|
+
void dispatch(connection, message, Buffer.byteLength(line, "utf8") + 1);
|
|
1601
|
+
}
|
|
1602
|
+
buffer = buffer.slice(start);
|
|
1603
|
+
bytes = Buffer.byteLength(buffer, "utf8");
|
|
1604
|
+
if (bytes >= MAX_FRAME) tooLarge();
|
|
1605
|
+
});
|
|
1606
|
+
socket.on("error", (error) => log[error.code === "ECONNRESET" || error.code === "EPIPE" ? "debug" : "warn"]("a client connection failed", { code: "ALP_IPC_SOCKET_ERROR", error }));
|
|
1607
|
+
socket.on("close", () => disconnect(connection));
|
|
1608
|
+
});
|
|
1609
|
+
return {
|
|
1610
|
+
extend(method, handler, owner = null) {
|
|
1611
|
+
if (typeof method !== "string" || !method.trim()) throw new Error("extend needs a method name");
|
|
1612
|
+
if (originalMethods.has(method)) throw new Error(`${method} is a built-in method and cannot be overridden`);
|
|
1613
|
+
if (Object.hasOwn(handlers, method)) throw new Error(`${method} is already registered`);
|
|
1614
|
+
handlers[method] = async (_connection, params) => {
|
|
1615
|
+
try {
|
|
1616
|
+
const result = await handler(params ?? {});
|
|
1617
|
+
return result === void 0 ? {} : result;
|
|
1618
|
+
} catch (error) {
|
|
1619
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1620
|
+
throw new Error(message.length > 2e3 ? `${message.slice(0, 2e3)}...` : message);
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
1623
|
+
if (owner) {
|
|
1624
|
+
if (!methodOwners.has(owner)) methodOwners.set(owner, /* @__PURE__ */ new Set());
|
|
1625
|
+
methodOwners.get(owner).add(method);
|
|
1626
|
+
}
|
|
1627
|
+
},
|
|
1628
|
+
async listen() {
|
|
1629
|
+
if (process.platform !== "win32") {
|
|
1630
|
+
await assertPrivateDirectory(path.dirname(socketPath), { create: true });
|
|
1631
|
+
const existing = await lstat(socketPath).catch((error) => {
|
|
1632
|
+
if (error.code === "ENOENT") return void 0;
|
|
1633
|
+
throw error;
|
|
1634
|
+
});
|
|
1635
|
+
if (existing) {
|
|
1636
|
+
await assertPrivateSocket(socketPath);
|
|
1637
|
+
const active = await new Promise((resolve, reject) => {
|
|
1638
|
+
const probe = net.createConnection(socketPath);
|
|
1639
|
+
probe.once("connect", () => {
|
|
1640
|
+
probe.destroy();
|
|
1641
|
+
resolve(true);
|
|
1642
|
+
});
|
|
1643
|
+
probe.once("error", (error) => {
|
|
1644
|
+
probe.destroy();
|
|
1645
|
+
if (error.code === "ECONNREFUSED") resolve(false);
|
|
1646
|
+
else reject(error);
|
|
1647
|
+
});
|
|
1648
|
+
probe.setTimeout(1e3, () => {
|
|
1649
|
+
probe.destroy();
|
|
1650
|
+
reject(new Error("IPC endpoint probe timed out"));
|
|
1651
|
+
});
|
|
1652
|
+
});
|
|
1653
|
+
if (active) throw new Error("IPC endpoint already in use by a running daemon");
|
|
1654
|
+
const current2 = await assertPrivateSocket(socketPath);
|
|
1655
|
+
if (!current2 || current2.dev !== existing.dev || current2.ino !== existing.ino) throw new Error("IPC endpoint changed during validation");
|
|
1656
|
+
await unlink(socketPath);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
const bindPath = process.platform === "win32" ? socketPath : path.join(path.dirname(socketPath), `.s${randomBytes(3).toString("hex")}`);
|
|
1660
|
+
await new Promise((resolve, reject) => {
|
|
1661
|
+
server.once("error", reject);
|
|
1662
|
+
server.listen(bindPath, () => {
|
|
1663
|
+
server.off("error", reject);
|
|
1664
|
+
resolve();
|
|
1665
|
+
});
|
|
1666
|
+
});
|
|
1667
|
+
if (process.platform !== "win32") {
|
|
1668
|
+
try {
|
|
1669
|
+
await chmod(bindPath, 384);
|
|
1670
|
+
const info = await lstat(bindPath);
|
|
1671
|
+
await rename(bindPath, socketPath);
|
|
1672
|
+
socketIdentity = { dev: info.dev, ino: info.ino };
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
1675
|
+
throw error;
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
},
|
|
1679
|
+
local() {
|
|
1680
|
+
const events = /* @__PURE__ */ new Set();
|
|
1681
|
+
const notifications = /* @__PURE__ */ new Set();
|
|
1682
|
+
const closes = /* @__PURE__ */ new Set();
|
|
1683
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1684
|
+
let sequence = 0;
|
|
1685
|
+
let ended = false;
|
|
1686
|
+
const connection = {
|
|
1687
|
+
helloed: true,
|
|
1688
|
+
roots: /* @__PURE__ */ new Set(),
|
|
1689
|
+
nextId: 0,
|
|
1690
|
+
pending: /* @__PURE__ */ new Map(),
|
|
1691
|
+
send(message) {
|
|
1692
|
+
if (message.method === "event") {
|
|
1693
|
+
for (const listener of events) listener(message.params);
|
|
1694
|
+
return;
|
|
1695
|
+
}
|
|
1696
|
+
if (typeof message.method === "string" && message.id === void 0) {
|
|
1697
|
+
for (const listener of notifications) listener(message.method, message.params);
|
|
1698
|
+
return;
|
|
1699
|
+
}
|
|
1700
|
+
const waiter = pending.get(message.id);
|
|
1701
|
+
if (!waiter) return;
|
|
1702
|
+
pending.delete(message.id);
|
|
1703
|
+
if (message.error) waiter.reject(new AlpRpcError(message.error));
|
|
1704
|
+
else waiter.resolve(message.result);
|
|
1705
|
+
}
|
|
1706
|
+
};
|
|
1707
|
+
connections.add(connection);
|
|
1708
|
+
return {
|
|
1709
|
+
request(method, params = {}) {
|
|
1710
|
+
if (ended) return Promise.reject(new Error("ALP daemon connection closed"));
|
|
1711
|
+
const id = ++sequence;
|
|
1712
|
+
return new Promise((resolve, reject) => {
|
|
1713
|
+
pending.set(id, { resolve, reject });
|
|
1714
|
+
void dispatch(connection, { jsonrpc: "2.0", id, method, params });
|
|
1715
|
+
});
|
|
1716
|
+
},
|
|
1717
|
+
onEvent(listener) {
|
|
1718
|
+
events.add(listener);
|
|
1719
|
+
return () => events.delete(listener);
|
|
1720
|
+
},
|
|
1721
|
+
onNotification(listener) {
|
|
1722
|
+
notifications.add(listener);
|
|
1723
|
+
return () => notifications.delete(listener);
|
|
1724
|
+
},
|
|
1725
|
+
onClose(listener) {
|
|
1726
|
+
closes.add(listener);
|
|
1727
|
+
return () => closes.delete(listener);
|
|
1728
|
+
},
|
|
1729
|
+
close() {
|
|
1730
|
+
if (ended) return;
|
|
1731
|
+
ended = true;
|
|
1732
|
+
disconnect(connection);
|
|
1733
|
+
const error = new Error("ALP daemon connection closed");
|
|
1734
|
+
for (const waiter of pending.values()) waiter.reject(error);
|
|
1735
|
+
pending.clear();
|
|
1736
|
+
for (const listener of closes) listener(error);
|
|
1737
|
+
closes.clear();
|
|
1738
|
+
}
|
|
1739
|
+
};
|
|
1740
|
+
},
|
|
1741
|
+
accept(send) {
|
|
1742
|
+
const connection = { helloed: false, roots: /* @__PURE__ */ new Set(), send, nextId: 0, pending: /* @__PURE__ */ new Map() };
|
|
1743
|
+
connections.add(connection);
|
|
1744
|
+
let ended = false;
|
|
1745
|
+
return {
|
|
1746
|
+
receive(message) {
|
|
1747
|
+
if (!ended) void dispatch(connection, message);
|
|
1748
|
+
},
|
|
1749
|
+
close() {
|
|
1750
|
+
if (ended) return;
|
|
1751
|
+
ended = true;
|
|
1752
|
+
disconnect(connection);
|
|
1753
|
+
}
|
|
1754
|
+
};
|
|
1755
|
+
},
|
|
1756
|
+
async close() {
|
|
1757
|
+
closing = true;
|
|
1758
|
+
if (sweeper) clearInterval(sweeper);
|
|
1759
|
+
attachments?.close();
|
|
1760
|
+
await terminals?.shutdown();
|
|
1761
|
+
await scheduler?.stop();
|
|
1762
|
+
const stopped = new Promise((resolve) => server.close(() => resolve()));
|
|
1763
|
+
for (const connection of connections) connection.socket?.destroy();
|
|
1764
|
+
await stopped;
|
|
1765
|
+
if (socketIdentity) {
|
|
1766
|
+
const current2 = await lstat(socketPath).catch((error) => {
|
|
1767
|
+
if (error.code === "ENOENT") return void 0;
|
|
1768
|
+
throw error;
|
|
1769
|
+
});
|
|
1770
|
+
if (current2?.isSocket() && current2.dev === socketIdentity.dev && current2.ino === socketIdentity.ino) await unlink(socketPath);
|
|
1771
|
+
socketIdentity = void 0;
|
|
1772
|
+
}
|
|
1773
|
+
await store?.flush();
|
|
1774
|
+
}
|
|
1775
|
+
};
|
|
1776
|
+
}
|
|
1777
|
+
export {
|
|
1778
|
+
ERROR2 as ERROR,
|
|
1779
|
+
createDaemonServer
|
|
1780
|
+
};
|