@anhlp/alp-daemon 0.0.1-beta.3 → 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/README.md +4 -0
- package/dist/alpd.js +10350 -3346
- package/dist/attachments.d.ts +211 -0
- package/dist/attachments.js +819 -0
- package/dist/build-manifest.json +21 -1
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +672 -0
- package/dist/files.d.ts +13 -0
- package/dist/files.js +15 -0
- package/dist/git.d.ts +87 -0
- package/dist/git.js +1093 -0
- package/dist/gitignore.d.ts +5 -0
- package/dist/gitignore.js +7 -1
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +18 -1
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/main.js +9 -3
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -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 +11 -1
- package/dist/server.js +698 -76
- package/dist/store.d.ts +69 -1
- package/dist/store.js +109 -3
- 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 +64 -5
- package/src/attachments.ts +870 -0
- package/src/conversation.ts +837 -0
- package/src/files.ts +23 -2
- package/src/git.ts +1045 -0
- package/src/gitignore.ts +10 -0
- package/src/history.ts +118 -0
- package/src/index.ts +6 -0
- package/src/lifecycle.ts +283 -0
- package/src/main.ts +9 -3
- package/src/registry.ts +238 -0
- package/src/scheduler.ts +422 -0
- package/src/schedules.ts +294 -0
- package/src/server.ts +810 -86
- package/src/store.ts +115 -3
- package/src/terminals.ts +591 -0
- package/src/worktrees.ts +287 -0
package/dist/server.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
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";
|
|
2
6
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
7
|
import { appendFile, chmod, mkdir, readFile, unlink, lstat, rename } from "node:fs/promises";
|
|
4
8
|
import net from "node:net";
|
|
@@ -13,6 +17,13 @@ import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtim
|
|
|
13
17
|
import { RpcError } from "./rpc-error.js";
|
|
14
18
|
import { createOperations } from "./operations.js";
|
|
15
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";
|
|
16
27
|
var log = createLogger({ component: "alpd.ipc" });
|
|
17
28
|
var recoveryLog = createLogger({ component: "alpd.recovery" });
|
|
18
29
|
function validId(id) {
|
|
@@ -29,6 +40,30 @@ function crashPoint(name) {
|
|
|
29
40
|
process.kill(process.pid, "SIGKILL");
|
|
30
41
|
}
|
|
31
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
|
+
}
|
|
32
67
|
function digest(value) {
|
|
33
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");
|
|
34
69
|
}
|
|
@@ -43,6 +78,10 @@ function titleFromPrompt(text) {
|
|
|
43
78
|
const line = text.split(/\r?\n/).map((entry) => entry.replace(/\s+/g, " ").trim()).find(Boolean);
|
|
44
79
|
return line ? [...line].slice(0, PROMPT_TITLE_CHARS).join("").trim() || void 0 : void 0;
|
|
45
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
|
+
}
|
|
46
85
|
var listCursor = {
|
|
47
86
|
key: (session) => [session.parentId ? 1 : 0, session.updatedAt ?? "", session.id],
|
|
48
87
|
compare([childA, updatedA, idA], [childB, updatedB, idB]) {
|
|
@@ -61,7 +100,7 @@ var listCursor = {
|
|
|
61
100
|
return key;
|
|
62
101
|
}
|
|
63
102
|
};
|
|
64
|
-
function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates }) {
|
|
103
|
+
function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions }) {
|
|
65
104
|
const connections = /* @__PURE__ */ new Set();
|
|
66
105
|
const rootOf = /* @__PURE__ */ new Map();
|
|
67
106
|
const attached = /* @__PURE__ */ new Map();
|
|
@@ -74,8 +113,136 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
74
113
|
let socketIdentity;
|
|
75
114
|
const recovering = /* @__PURE__ */ new Map();
|
|
76
115
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
77
|
-
const
|
|
78
|
-
const
|
|
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
|
+
};
|
|
79
246
|
const watchers = /* @__PURE__ */ new Map();
|
|
80
247
|
function projectOf(root) {
|
|
81
248
|
return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
|
|
@@ -91,6 +258,26 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
91
258
|
deliver(connection, announced);
|
|
92
259
|
}
|
|
93
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
|
+
}
|
|
94
281
|
function save(record, changes = {}) {
|
|
95
282
|
Object.assign(record, changes, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
96
283
|
records.set(record.id, record);
|
|
@@ -121,17 +308,19 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
121
308
|
}
|
|
122
309
|
if (!record) return false;
|
|
123
310
|
if (event.type === "session.updated") save(record, { session: { ...record.session, ...event.session, ...event.session.parked ? {} : { parked: void 0 } } });
|
|
124
|
-
else if (event.type === "turn.started") save(record, { status: "running", activeTurnId: event.turnId, archived: void 0 });
|
|
311
|
+
else if (event.type === "turn.started") save(record, { status: "running", activeTurnId: event.turnId, archived: void 0, ...sessionId === root ? { attention: void 0 } : {} });
|
|
125
312
|
else if (event.type === "turn.ended") save(record, {
|
|
126
313
|
status: "idle",
|
|
127
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) } : {},
|
|
128
317
|
...record.session ? { session: { ...record.session, parked: event.state === "failed" ? runtime.snapshot(sessionId)?.parked : void 0 } } : {},
|
|
129
318
|
...event.state === "failed" ? { lastError: { message: event.error?.message ?? "Turn failed" } } : {}
|
|
130
319
|
});
|
|
131
320
|
else if (event.type === "usage" && record.session) record.session = { ...record.session, usage: event.usage };
|
|
132
321
|
else if (event.type === "session.failed") save(record, { status: "error", lastError: event.error });
|
|
133
322
|
else if (event.type === "session.closed") save(record, { status: record.status === "error" ? "error" : "closed", activeTurnId: void 0 });
|
|
134
|
-
else if (event.type === "item" && sessionId === root && !record.title && event.item.kind === "user_message" &&
|
|
323
|
+
else if (event.type === "item" && sessionId === root && !record.title && event.item.kind === "user_message" && fromUser(event.item)) {
|
|
135
324
|
const title = titleFromPrompt(event.item.text);
|
|
136
325
|
if (title) {
|
|
137
326
|
save(record, { title });
|
|
@@ -140,6 +329,11 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
140
329
|
}
|
|
141
330
|
return false;
|
|
142
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
|
+
}
|
|
143
337
|
function announceTitle(root, title) {
|
|
144
338
|
const session = runtime.snapshot(root);
|
|
145
339
|
if (!session || rootOf.get(root) !== root) return;
|
|
@@ -166,7 +360,11 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
166
360
|
log2.push(envelope);
|
|
167
361
|
if (log2.length > TREE_LOG_LIMIT) log2.splice(0, log2.length - TREE_LOG_LIMIT);
|
|
168
362
|
logs.set(root, log2);
|
|
363
|
+
const before = records.get(root)?.attention;
|
|
169
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);
|
|
170
368
|
}
|
|
171
369
|
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
172
370
|
if (event.type === "question" || event.type === "question.resolved") tellWatchers(root, envelope);
|
|
@@ -180,19 +378,23 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
180
378
|
});
|
|
181
379
|
async function restore() {
|
|
182
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 }));
|
|
183
382
|
const loaded = await store.list();
|
|
184
383
|
await reconcileReceipts(loaded);
|
|
185
384
|
const now = Date.now();
|
|
186
385
|
const ended = { code: "daemon_restarted", message: "alpd stopped while this session was working" };
|
|
187
386
|
const epoch = `restart-${startedAt}`;
|
|
188
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));
|
|
189
391
|
const reopen = [];
|
|
190
392
|
const byRoot = trees(loaded);
|
|
191
393
|
const removed = await expire(byRoot, now);
|
|
192
394
|
for (const [root, tree] of byRoot) {
|
|
193
395
|
const head = tree.find((record) => record.id === root);
|
|
194
396
|
if (removed.has(root)) continue;
|
|
195
|
-
if (head && resumable(head) && (head.status === "running" || head.status === "idle" && head.session?.parked || tree.some((record) => continuing.has(record.id)))) reopen.push({ record: head, working: head.status === "running" });
|
|
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" });
|
|
196
398
|
if (tree.some((record) => LIVE.includes(record.status))) seen(root, await store.timeline(root));
|
|
197
399
|
for (const record of tree) {
|
|
198
400
|
records.set(record.id, record);
|
|
@@ -214,12 +416,22 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
214
416
|
}
|
|
215
417
|
}
|
|
216
418
|
}
|
|
419
|
+
if (conversation) await conversation.recover().catch((error) => recoveryLog.error("could not recover lifecycle operations", { code: "ALPD_LIFECYCLE_RECOVERY_FAILED", error }));
|
|
217
420
|
const reopened = new Set(reopen.map((entry) => entry.record.id));
|
|
218
421
|
for (const rootId of new Set(runtime.recoverable().map((entry) => entry.rootId))) {
|
|
219
422
|
if (!reopened.has(rootId)) await runtime.abandon(rootId, "its root session cannot be reopened").catch(() => {
|
|
220
423
|
});
|
|
221
424
|
}
|
|
222
|
-
for (const { record, working } of reopen)
|
|
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
|
+
}
|
|
223
435
|
}
|
|
224
436
|
function trees(list) {
|
|
225
437
|
const byRoot = /* @__PURE__ */ new Map();
|
|
@@ -235,20 +447,27 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
235
447
|
}
|
|
236
448
|
const continuing = new Set(runtime.recoverable().map((entry) => entry.rootId));
|
|
237
449
|
for (const [root, tree] of byRoot) {
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
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();
|
|
252
471
|
}
|
|
253
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 });
|
|
254
473
|
return removed;
|
|
@@ -258,6 +477,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
258
477
|
try {
|
|
259
478
|
await restored;
|
|
260
479
|
await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
|
|
480
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS);
|
|
261
481
|
await expire(trees(records.values()));
|
|
262
482
|
} catch (error) {
|
|
263
483
|
recoveryLog.warn("retention sweep failed", { code: "ALP_RETENTION_FAILED", error });
|
|
@@ -265,6 +485,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
265
485
|
}
|
|
266
486
|
const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : void 0;
|
|
267
487
|
sweeper?.unref();
|
|
488
|
+
scheduler?.start(scheduleTickMs);
|
|
268
489
|
async function reconcileReceipts(loaded) {
|
|
269
490
|
const rootOfRecord = new Map(loaded.map((record) => [record.id, record.rootId]));
|
|
270
491
|
const timelines = /* @__PURE__ */ new Map();
|
|
@@ -284,20 +505,30 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
284
505
|
function resumable(record) {
|
|
285
506
|
return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
|
|
286
507
|
}
|
|
287
|
-
async function recoverTree(record, working) {
|
|
508
|
+
async function recoverTree(record, working, opened) {
|
|
288
509
|
const session = record.session;
|
|
510
|
+
let openedOnce = false;
|
|
511
|
+
const open = () => {
|
|
512
|
+
if (openedOnce) return;
|
|
513
|
+
openedOnce = true;
|
|
514
|
+
opened?.();
|
|
515
|
+
};
|
|
289
516
|
try {
|
|
517
|
+
if (worktrees && record.spec?.cwd) await worktrees.assertAvailable(record.spec.cwd);
|
|
290
518
|
const stored = await treeLog(record.id);
|
|
291
519
|
seen(record.id, stored);
|
|
292
520
|
logs.set(record.id, [...stored]);
|
|
293
521
|
await runtime.open(record.id, {
|
|
294
522
|
...record.spec,
|
|
295
523
|
persist: true,
|
|
296
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
|
|
524
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...record.base ? { base: record.base } : {} }
|
|
297
525
|
}, { history: "skip", delegation: record.delegation ?? true });
|
|
526
|
+
open();
|
|
298
527
|
const outcomes = await runtime.recover(record.id, { continueRoot: working, parkedRoot: session.parked });
|
|
299
528
|
recoveryLog.info(`recovered ${record.id}: ${outcomes.map((outcome) => `${outcome.agent} ${outcome.outcome}`).join(", ") || "root"}`, { event: "recovered", sessionId: record.id, rootId: record.rootId });
|
|
300
529
|
} catch (error) {
|
|
530
|
+
open();
|
|
531
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
301
532
|
recoveryLog.error(`could not recover ${record.id}`, { code: "ALP_RECOVERY_FAILED", sessionId: record.id, rootId: record.rootId, error });
|
|
302
533
|
await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {
|
|
303
534
|
});
|
|
@@ -306,7 +537,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
306
537
|
setImmediate(() => void reap(record.id));
|
|
307
538
|
}
|
|
308
539
|
}
|
|
309
|
-
function deliverOnce(sessionId, clientMessageId, fingerprint, send) {
|
|
540
|
+
function deliverOnce(sessionId, clientMessageId, fingerprint, send, { requireReceipt = false, prepare, abandon } = {}) {
|
|
310
541
|
const key = digest(["prompt", sessionId, clientMessageId]);
|
|
311
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" });
|
|
312
543
|
const answer = (receipt, extra = {}) => ({ outcome: receipt.outcome ?? "accepted", ...receipt.error ? { error: receipt.error } : {}, ...extra });
|
|
@@ -325,12 +556,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
325
556
|
if (existing.state === "pending" || existing.outcome === "unknown") throw unknown();
|
|
326
557
|
return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
|
|
327
558
|
}
|
|
559
|
+
if (requireReceipt) throw unknown();
|
|
328
560
|
const receipt = (state, changes = {}) => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
329
561
|
live(sessionId);
|
|
562
|
+
await prepare?.(key);
|
|
330
563
|
crashPoint("prompt.before-receipt");
|
|
331
564
|
try {
|
|
332
565
|
await store.putReceipt(key, receipt("pending"));
|
|
333
566
|
} catch (error) {
|
|
567
|
+
await abandon?.(key).catch(() => {
|
|
568
|
+
});
|
|
334
569
|
throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error);
|
|
335
570
|
}
|
|
336
571
|
crashPoint("prompt.after-receipt");
|
|
@@ -345,6 +580,8 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
345
580
|
} catch (error) {
|
|
346
581
|
await store.removeReceipt(key).catch(() => {
|
|
347
582
|
});
|
|
583
|
+
await abandon?.(key).catch(() => {
|
|
584
|
+
});
|
|
348
585
|
throw error;
|
|
349
586
|
} finally {
|
|
350
587
|
stop();
|
|
@@ -366,7 +603,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
366
603
|
};
|
|
367
604
|
const previous = delivering.get(key) ?? Promise.resolve();
|
|
368
605
|
const result = previous.catch(() => {
|
|
369
|
-
}).then(attempt);
|
|
606
|
+
}).then(() => gated(sessionId, attempt));
|
|
370
607
|
delivering.set(key, result);
|
|
371
608
|
void result.finally(() => {
|
|
372
609
|
if (delivering.get(key) === result) delivering.delete(key);
|
|
@@ -374,17 +611,29 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
374
611
|
});
|
|
375
612
|
return result;
|
|
376
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
|
+
}
|
|
377
621
|
async function persisted(root) {
|
|
378
622
|
if (!store) return {};
|
|
379
623
|
return { durable: (await store.drain({ records: [root], timelines: [root] })).length === 0 };
|
|
380
624
|
}
|
|
381
625
|
function forget(root) {
|
|
382
626
|
if (runtime.snapshot(root)) return;
|
|
383
|
-
for (const [id, candidate] of rootOf) if (candidate === root)
|
|
627
|
+
for (const [id, candidate] of rootOf) if (candidate === root) {
|
|
628
|
+
rootOf.delete(id);
|
|
629
|
+
recoveryErrors.delete(id);
|
|
630
|
+
}
|
|
631
|
+
recoveryErrors.delete(root);
|
|
384
632
|
logs.delete(root);
|
|
385
633
|
}
|
|
386
634
|
async function reap(root) {
|
|
387
635
|
if (closing || attached.get(root)?.size || recovering.has(root)) return false;
|
|
636
|
+
if (scheduler?.holds(root)) return false;
|
|
388
637
|
const session = runtime.snapshot(root);
|
|
389
638
|
if (!session || session.busy) return false;
|
|
390
639
|
await runtime.close(root).catch(() => {
|
|
@@ -408,7 +657,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
408
657
|
const session = live2 ?? record?.session;
|
|
409
658
|
if (!session) return void 0;
|
|
410
659
|
const status = live2 ? live2.activeTurnId ? "running" : "idle" : record?.status === "error" ? "error" : "closed";
|
|
411
|
-
return { ...session, ...live2 ? {} : { busy: false, activeTurnId: void 0 }, status, title: record?.title, ...record?.archived ? { archived: true } : {}, lastError: record?.lastError, createdAt: record?.createdAt, updatedAt: record?.updatedAt };
|
|
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) : {} };
|
|
412
661
|
}
|
|
413
662
|
function rootRecord(sessionId) {
|
|
414
663
|
if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
|
|
@@ -470,25 +719,83 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
470
719
|
if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, "This session cannot be resumed");
|
|
471
720
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
472
721
|
if (agent !== void 0 && agent !== session.agent) throw new RpcError(ERROR.failed, "Cannot resume a session as a different ALP agent");
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
attach(connection, record.id);
|
|
722
|
+
markOpening(record.id);
|
|
723
|
+
recoveryErrors.delete(record.id);
|
|
724
|
+
let applied = false;
|
|
477
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);
|
|
478
731
|
const opened = await runtime.open(record.id, {
|
|
479
732
|
...record.spec,
|
|
480
733
|
...spec.mode !== void 0 ? { mode: spec.mode } : {},
|
|
481
734
|
...spec.thinking !== void 0 ? { thinking: spec.thinking } : {},
|
|
482
735
|
persist: true,
|
|
483
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
|
|
736
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...record.base ? { base: record.base } : {} }
|
|
484
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 });
|
|
485
740
|
if (history === "replay") replayHistory(connection, record.id, stored);
|
|
486
741
|
return opened;
|
|
487
742
|
} catch (error) {
|
|
743
|
+
if (applied) throw error;
|
|
488
744
|
detach(connection, record.id);
|
|
745
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
489
746
|
throw error;
|
|
747
|
+
} finally {
|
|
748
|
+
clearOpening(record.id);
|
|
490
749
|
}
|
|
491
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
|
+
};
|
|
492
799
|
const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
|
|
493
800
|
const extensionOwners = /* @__PURE__ */ new Map();
|
|
494
801
|
const handlers = {
|
|
@@ -556,11 +863,40 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
556
863
|
* The questions waiting now; from then on this connection is told of `question` and
|
|
557
864
|
* `question.resolved` in every tree, or those of `projectRoot`, attached or not. Calling it
|
|
558
865
|
* again replaces the filter; it lasts as long as the connection (ALPD §15). With `turns`, also
|
|
559
|
-
* of `turn.ended` of every root
|
|
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).
|
|
560
868
|
*/
|
|
561
|
-
"question.watch"(connection, { projectRoot, turns } = {}) {
|
|
562
|
-
watchers.set(connection, { projectRoot, turns: turns === true });
|
|
563
|
-
return {
|
|
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 };
|
|
564
900
|
},
|
|
565
901
|
/**
|
|
566
902
|
* The files of a directory whose path matches a query, read-only and confined to it: no link
|
|
@@ -633,17 +969,96 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
633
969
|
setImmediate(() => onShutdown?.());
|
|
634
970
|
return {};
|
|
635
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),
|
|
636
1004
|
"catalog.get": () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
|
|
637
|
-
|
|
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
|
+
}
|
|
638
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));
|
|
639
1037
|
if (sessionId !== void 0 && (typeof sessionId !== "string" || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, "Invalid session id");
|
|
640
1038
|
if (history !== "replay" && history !== "skip") throw new RpcError(-32602, "history must be replay or skip");
|
|
641
1039
|
const id = sessionId ?? `ses_${randomBytes(8).toString("hex")}`;
|
|
642
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
|
+
};
|
|
643
1057
|
const existing = runtime.snapshot(id);
|
|
644
1058
|
if (existing) {
|
|
645
1059
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
646
1060
|
if (existing.parentId || agent !== void 0 && agent !== existing.agent) throw new RpcError(ERROR.failed, "Session is already open");
|
|
1061
|
+
await reserve();
|
|
647
1062
|
attach(connection, id);
|
|
648
1063
|
announce(connection, id, history);
|
|
649
1064
|
return { session: existing, attached: true };
|
|
@@ -651,8 +1066,14 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
651
1066
|
const record = records.get(id);
|
|
652
1067
|
if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
|
|
653
1068
|
if (record) {
|
|
654
|
-
|
|
655
|
-
|
|
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
|
+
}
|
|
656
1077
|
}
|
|
657
1078
|
const { restore: _restore, ...kept } = spec;
|
|
658
1079
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -664,14 +1085,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
664
1085
|
if (records.get(id) === created) records.delete(id);
|
|
665
1086
|
throw persistenceFailed(`session ${id}; it was not started`, error);
|
|
666
1087
|
}
|
|
667
|
-
attach(connection, id);
|
|
668
1088
|
try {
|
|
1089
|
+
await reserve();
|
|
1090
|
+
attach(connection, id);
|
|
669
1091
|
const session = await runtime.open(id, spec, { history, delegation });
|
|
670
1092
|
return { session, attached: false, ...await persisted(id) };
|
|
671
1093
|
} catch (error) {
|
|
672
1094
|
detach(connection, id);
|
|
673
1095
|
records.delete(id);
|
|
674
1096
|
await store?.remove(id, [id]);
|
|
1097
|
+
await rollback();
|
|
675
1098
|
throw error;
|
|
676
1099
|
}
|
|
677
1100
|
},
|
|
@@ -685,42 +1108,72 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
685
1108
|
* events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
|
|
686
1109
|
* with the whole timeline. The replay and the live events that follow are in cursor order.
|
|
687
1110
|
*/
|
|
688
|
-
async "session.
|
|
689
|
-
|
|
690
|
-
|
|
1111
|
+
async "session.history"(_connection, { sessionId, before, limit, maxBytes }) {
|
|
1112
|
+
known(sessionId);
|
|
1113
|
+
if (!store) throw new RpcError(1005, "Durable history unavailable");
|
|
691
1114
|
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
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;
|
|
697
1120
|
}
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
const
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
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 ?? [];
|
|
709
1136
|
}
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
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
|
+
}
|
|
713
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 } : {} };
|
|
714
1169
|
}
|
|
715
|
-
announceQuestions(connection, root);
|
|
716
|
-
return { session: root === found.id ? found : summary(root), cursor: tip, ...reset ? { reset: true } : {} };
|
|
717
1170
|
},
|
|
718
1171
|
async "session.release"(connection, { sessionId }) {
|
|
719
1172
|
const root = rootOf.get(sessionId) ?? sessionId;
|
|
720
1173
|
detach(connection, root);
|
|
721
1174
|
return { closed: await reap(root) };
|
|
722
1175
|
},
|
|
723
|
-
async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content }) {
|
|
1176
|
+
async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content, ...context }) {
|
|
724
1177
|
if (typeof clientMessageId !== "string" || !Array.isArray(content)) throw new RpcError(-32602, "clientMessageId and content are required");
|
|
725
1178
|
if (delivery !== "auto" && delivery !== "steer") throw new RpcError(-32602, "delivery must be auto or steer");
|
|
726
1179
|
const images = content.filter((part) => part?.type === "image");
|
|
@@ -732,22 +1185,79 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
732
1185
|
if (bytes > PROMPT_IMAGES.maxBytes) throw new RpcError(-32602, `An image in a prompt is at most ${PROMPT_IMAGES.maxBytes} bytes`);
|
|
733
1186
|
if (total > PROMPT_IMAGES.maxTotalBytes) throw new RpcError(-32602, `The images of a prompt are at most ${PROMPT_IMAGES.maxTotalBytes} bytes together`);
|
|
734
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;
|
|
735
1197
|
const send = async () => {
|
|
736
1198
|
live(sessionId);
|
|
737
|
-
await runtime.prompt(sessionId, { clientMessageId, delivery, content });
|
|
1199
|
+
await runtime.prompt(sessionId, { clientMessageId, delivery, content: delivered });
|
|
738
1200
|
};
|
|
739
1201
|
if (!store) {
|
|
740
|
-
await send
|
|
1202
|
+
await gated(sessionId, send);
|
|
741
1203
|
return {};
|
|
742
1204
|
}
|
|
743
|
-
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
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) });
|
|
744
1218
|
},
|
|
745
|
-
|
|
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
|
+
}
|
|
746
1240
|
await runtime.interrupt(sessionId);
|
|
747
1241
|
return {};
|
|
748
1242
|
},
|
|
749
|
-
|
|
750
|
-
|
|
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) };
|
|
751
1261
|
},
|
|
752
1262
|
async "session.close"(_connection, { sessionId }) {
|
|
753
1263
|
await runtime.close(sessionId);
|
|
@@ -772,14 +1282,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
772
1282
|
async "session.archive"(_connection, { sessionId, archived = true }) {
|
|
773
1283
|
const record = rootRecord(sessionId);
|
|
774
1284
|
if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
|
|
775
|
-
const before = record.archived;
|
|
776
|
-
Object.assign(record, { archived: archived === true ? true : void 0 });
|
|
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);
|
|
777
1288
|
try {
|
|
778
1289
|
await store?.put(record);
|
|
779
1290
|
} catch (error) {
|
|
780
|
-
record
|
|
1291
|
+
Object.assign(record, before);
|
|
781
1292
|
throw persistenceFailed(`the archive state of ${record.id}`, error);
|
|
782
1293
|
}
|
|
1294
|
+
if (before.attention && !record.attention) tellAttention(record.id, void 0);
|
|
783
1295
|
return { session: summary(record.id) };
|
|
784
1296
|
},
|
|
785
1297
|
"session.get"(_connection, { sessionId }) {
|
|
@@ -801,8 +1313,104 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
801
1313
|
if (limit === void 0 || sessions.length <= limit) return { sessions };
|
|
802
1314
|
const page = sessions.slice(0, limit);
|
|
803
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
|
+
}
|
|
804
1379
|
}
|
|
805
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));
|
|
806
1414
|
for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
|
|
807
1415
|
Object.setPrototypeOf(handlers, null);
|
|
808
1416
|
const originalMethods = /* @__PURE__ */ new Set([...Object.keys(handlers), ...RPC_METHODS]);
|
|
@@ -850,7 +1458,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
850
1458
|
throw new RpcError(ERROR.failed, "alpd could not read the workspace file");
|
|
851
1459
|
}
|
|
852
1460
|
}
|
|
853
|
-
const capabilities = [CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts] : [], ...operations.capabilities];
|
|
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];
|
|
854
1462
|
function fits(response) {
|
|
855
1463
|
if (frameBytes(response) <= MAX_FRAME) return response;
|
|
856
1464
|
log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
|
|
@@ -893,7 +1501,8 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
893
1501
|
const issues2 = validateParams(method, params);
|
|
894
1502
|
if (issues2.length) throw invalidParams(issues2);
|
|
895
1503
|
connection.helloed = true;
|
|
896
|
-
|
|
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 } : {} } });
|
|
897
1506
|
return;
|
|
898
1507
|
}
|
|
899
1508
|
if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first", { reason: "hello_required" });
|
|
@@ -933,6 +1542,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
933
1542
|
}
|
|
934
1543
|
connections.delete(connection);
|
|
935
1544
|
watchers.delete(connection);
|
|
1545
|
+
terminals?.disconnect(connection);
|
|
936
1546
|
for (const root of [...connection.roots]) {
|
|
937
1547
|
detach(connection, root);
|
|
938
1548
|
void reap(root);
|
|
@@ -1068,6 +1678,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1068
1678
|
},
|
|
1069
1679
|
local() {
|
|
1070
1680
|
const events = /* @__PURE__ */ new Set();
|
|
1681
|
+
const notifications = /* @__PURE__ */ new Set();
|
|
1071
1682
|
const closes = /* @__PURE__ */ new Set();
|
|
1072
1683
|
const pending = /* @__PURE__ */ new Map();
|
|
1073
1684
|
let sequence = 0;
|
|
@@ -1082,6 +1693,10 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1082
1693
|
for (const listener of events) listener(message.params);
|
|
1083
1694
|
return;
|
|
1084
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
|
+
}
|
|
1085
1700
|
const waiter = pending.get(message.id);
|
|
1086
1701
|
if (!waiter) return;
|
|
1087
1702
|
pending.delete(message.id);
|
|
@@ -1103,6 +1718,10 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1103
1718
|
events.add(listener);
|
|
1104
1719
|
return () => events.delete(listener);
|
|
1105
1720
|
},
|
|
1721
|
+
onNotification(listener) {
|
|
1722
|
+
notifications.add(listener);
|
|
1723
|
+
return () => notifications.delete(listener);
|
|
1724
|
+
},
|
|
1106
1725
|
onClose(listener) {
|
|
1107
1726
|
closes.add(listener);
|
|
1108
1727
|
return () => closes.delete(listener);
|
|
@@ -1137,6 +1756,9 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1137
1756
|
async close() {
|
|
1138
1757
|
closing = true;
|
|
1139
1758
|
if (sweeper) clearInterval(sweeper);
|
|
1759
|
+
attachments?.close();
|
|
1760
|
+
await terminals?.shutdown();
|
|
1761
|
+
await scheduler?.stop();
|
|
1140
1762
|
const stopped = new Promise((resolve) => server.close(() => resolve()));
|
|
1141
1763
|
for (const connection of connections) connection.socket?.destroy();
|
|
1142
1764
|
await stopped;
|