@anhlp/alp-daemon 0.0.1-beta.3 → 0.0.1-beta.5
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/THIRD-PARTY-NOTICES.txt +26 -1
- package/dist/alpd.js +29928 -14898
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +34 -1
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +688 -0
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +154 -2
- package/dist/files.js +392 -68
- package/dist/git.d.ts +93 -0
- package/dist/git.js +1192 -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 +7 -0
- package/dist/index.js +21 -1
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/main.js +43 -11
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +198 -0
- package/dist/operations.d.ts +8 -2
- package/dist/operations.js +20 -10
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +296 -0
- package/dist/schedules.d.ts +70 -0
- package/dist/schedules.js +246 -0
- package/dist/server.d.ts +14 -2
- package/dist/server.js +836 -90
- package/dist/store.d.ts +72 -2
- package/dist/store.js +111 -4
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal-screen.d.ts +24 -0
- package/dist/terminal-screen.js +99 -0
- package/dist/terminals.d.ts +193 -0
- package/dist/terminals.js +570 -0
- package/dist/windows-terminal.d.ts +29 -0
- package/dist/windows-terminal.js +122 -0
- package/dist/worktrees.d.ts +65 -0
- package/dist/worktrees.js +318 -0
- package/native/README.md +201 -0
- package/native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/native/prebuilt/darwin-x64/manifest.json +11 -0
- package/native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/native/terminal-owner.c +389 -0
- package/package.json +70 -7
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +528 -82
- package/src/git.ts +1140 -0
- package/src/gitignore.ts +10 -0
- package/src/history.ts +118 -0
- package/src/index.ts +7 -0
- package/src/lifecycle.ts +283 -0
- package/src/main.ts +37 -12
- package/src/native-terminal.ts +122 -0
- package/src/operations.ts +27 -11
- package/src/registry.ts +238 -0
- package/src/scheduler.ts +432 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +948 -102
- package/src/store.ts +117 -4
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +641 -0
- package/src/windows-terminal.ts +123 -0
- package/src/worktrees.ts +382 -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";
|
|
@@ -12,7 +16,14 @@ import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
|
|
|
12
16
|
import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
|
|
13
17
|
import { RpcError } from "./rpc-error.js";
|
|
14
18
|
import { createOperations } from "./operations.js";
|
|
15
|
-
import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from "./files.js";
|
|
19
|
+
import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, 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,10 +40,39 @@ 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
|
}
|
|
35
70
|
var TREE_LOG_LIMIT = 2e4;
|
|
71
|
+
var AGENT_CAPABILITY = "principal.agent";
|
|
72
|
+
var agentRefused = (connection, method) => {
|
|
73
|
+
if (connection.agent) throw new RpcError(ERROR.forbidden, `${method} is the user's; this connection was opened by an ALP agent`, { reason: "user_only" });
|
|
74
|
+
return void 0;
|
|
75
|
+
};
|
|
36
76
|
var SESSION_ID = /^[\w.:-]{1,128}$/;
|
|
37
77
|
var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
38
78
|
var RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
@@ -43,6 +83,10 @@ function titleFromPrompt(text) {
|
|
|
43
83
|
const line = text.split(/\r?\n/).map((entry) => entry.replace(/\s+/g, " ").trim()).find(Boolean);
|
|
44
84
|
return line ? [...line].slice(0, PROMPT_TITLE_CHARS).join("").trim() || void 0 : void 0;
|
|
45
85
|
}
|
|
86
|
+
function fromUser(item) {
|
|
87
|
+
if (item.clientMessageId?.startsWith("alp-")) return false;
|
|
88
|
+
return item.origin !== void 0 ? item.origin === "user" : item.clientMessageId !== void 0;
|
|
89
|
+
}
|
|
46
90
|
var listCursor = {
|
|
47
91
|
key: (session) => [session.parentId ? 1 : 0, session.updatedAt ?? "", session.id],
|
|
48
92
|
compare([childA, updatedA, idA], [childB, updatedB, idB]) {
|
|
@@ -61,8 +105,26 @@ var listCursor = {
|
|
|
61
105
|
return key;
|
|
62
106
|
}
|
|
63
107
|
};
|
|
64
|
-
function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates }) {
|
|
108
|
+
function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions, modelCatalog }) {
|
|
65
109
|
const connections = /* @__PURE__ */ new Set();
|
|
110
|
+
const catalogResult = () => {
|
|
111
|
+
const state = modelCatalog?.state();
|
|
112
|
+
return {
|
|
113
|
+
models,
|
|
114
|
+
modes,
|
|
115
|
+
thinkingOptions,
|
|
116
|
+
defaultModel: `codex:${DEFAULT_MODEL}`,
|
|
117
|
+
...state ? { fetchedAt: state.fetchedAt, providers: Object.fromEntries(Object.entries(state.providers).map(([runtime2, provider]) => [runtime2, { status: provider.status, fetchedAt: provider.fetchedAt, ...provider.error ? { error: provider.error } : {} }])) } : {}
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
const unsubscribeCatalog = modelCatalog?.onUpdated((snapshot) => {
|
|
121
|
+
for (const connection of connections) if (connection.helloed) {
|
|
122
|
+
try {
|
|
123
|
+
connection.send({ jsonrpc: "2.0", method: "catalog.updated", params: { fetchedAt: snapshot.fetchedAt } });
|
|
124
|
+
} catch {
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
});
|
|
66
128
|
const rootOf = /* @__PURE__ */ new Map();
|
|
67
129
|
const attached = /* @__PURE__ */ new Map();
|
|
68
130
|
const logs = /* @__PURE__ */ new Map();
|
|
@@ -74,12 +136,144 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
74
136
|
let socketIdentity;
|
|
75
137
|
const recovering = /* @__PURE__ */ new Map();
|
|
76
138
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
77
|
-
const
|
|
78
|
-
const
|
|
139
|
+
const clock = () => Date.now();
|
|
140
|
+
const schedules = home && store ? createScheduleStore(path.join(home, "schedules"), { now: clock }) : void 0;
|
|
141
|
+
const storeJob = async (id, projectRoot) => {
|
|
142
|
+
if (!schedules) return void 0;
|
|
143
|
+
try {
|
|
144
|
+
return await schedules.get(id, { projectRoot });
|
|
145
|
+
} catch (error) {
|
|
146
|
+
throw scheduleFailed(error);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
const attachments = home && store && process.platform !== "win32" ? createAttachmentStore({
|
|
150
|
+
root: path.join(home, "state", "attachments"),
|
|
151
|
+
sessionProject: (sessionId) => runtime.snapshot(sessionId)?.projectRoot ?? records.get(sessionId)?.session?.projectRoot,
|
|
152
|
+
crashPoint,
|
|
153
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
154
|
+
// A collected object's staged copy goes with it.
|
|
155
|
+
onDiscard: (attachmentId) => runtime.dropAttachment?.(attachmentId),
|
|
156
|
+
...attachmentOptions
|
|
157
|
+
}) : void 0;
|
|
158
|
+
runtime.bindAttachments?.(attachments?.reader);
|
|
159
|
+
const holds = /* @__PURE__ */ new Map();
|
|
160
|
+
let holdRevision = 0;
|
|
161
|
+
function holdPrompts(root) {
|
|
162
|
+
holdRevision++;
|
|
163
|
+
let gate = holds.get(root);
|
|
164
|
+
if (!gate) {
|
|
165
|
+
let release;
|
|
166
|
+
const open = new Promise((resolve) => {
|
|
167
|
+
release = resolve;
|
|
168
|
+
});
|
|
169
|
+
gate = { count: 0, open, release };
|
|
170
|
+
holds.set(root, gate);
|
|
171
|
+
}
|
|
172
|
+
gate.count++;
|
|
173
|
+
const held = gate;
|
|
174
|
+
let released = false;
|
|
175
|
+
return () => {
|
|
176
|
+
if (released) return;
|
|
177
|
+
released = true;
|
|
178
|
+
if (--held.count === 0) {
|
|
179
|
+
if (holds.get(root) === held) holds.delete(root);
|
|
180
|
+
held.release();
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const promptsInFlight = /* @__PURE__ */ new Map();
|
|
185
|
+
const rootIdOf = (sessionId) => rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
186
|
+
async function gated(sessionId, run) {
|
|
187
|
+
const root = rootIdOf(sessionId);
|
|
188
|
+
while (holds.has(root)) await holds.get(root).open;
|
|
189
|
+
refuseFenced(root);
|
|
190
|
+
promptsInFlight.set(root, (promptsInFlight.get(root) ?? 0) + 1);
|
|
191
|
+
try {
|
|
192
|
+
return await run();
|
|
193
|
+
} finally {
|
|
194
|
+
const left = (promptsInFlight.get(root) ?? 1) - 1;
|
|
195
|
+
if (left > 0) promptsInFlight.set(root, left);
|
|
196
|
+
else promptsInFlight.delete(root);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function fencedRoot(root) {
|
|
200
|
+
return conversation?.fenced(root);
|
|
201
|
+
}
|
|
202
|
+
function refuseFenced(root) {
|
|
203
|
+
const requestId = fencedRoot(root);
|
|
204
|
+
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" });
|
|
205
|
+
}
|
|
206
|
+
const journal = store ? createLifecycleJournal(path.join(store.root, "lifecycle")) : void 0;
|
|
207
|
+
const conversation = store && journal ? createConversation({
|
|
208
|
+
runtime,
|
|
209
|
+
store,
|
|
210
|
+
journal,
|
|
211
|
+
records,
|
|
212
|
+
cursors,
|
|
213
|
+
logs,
|
|
214
|
+
treeLogLimit: TREE_LOG_LIMIT,
|
|
215
|
+
summary: (id) => summary(id),
|
|
216
|
+
digest,
|
|
217
|
+
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,
|
|
218
|
+
holdPrompts,
|
|
219
|
+
broadcast: (root, envelope) => {
|
|
220
|
+
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
221
|
+
},
|
|
222
|
+
get registry() {
|
|
223
|
+
return registry;
|
|
224
|
+
},
|
|
225
|
+
get worktrees() {
|
|
226
|
+
return worktrees;
|
|
227
|
+
},
|
|
228
|
+
attachments,
|
|
229
|
+
crashPoint,
|
|
230
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
231
|
+
startedAt
|
|
232
|
+
}) : void 0;
|
|
233
|
+
let restored = Promise.resolve();
|
|
234
|
+
const openingSessions = /* @__PURE__ */ new Map();
|
|
235
|
+
const recoveryErrors = /* @__PURE__ */ new Map();
|
|
236
|
+
const markOpening = (sessionId) => openingSessions.set(sessionId, (openingSessions.get(sessionId) ?? 0) + 1);
|
|
237
|
+
const clearOpening = (sessionId) => {
|
|
238
|
+
const count = (openingSessions.get(sessionId) ?? 0) - 1;
|
|
239
|
+
if (count > 0) openingSessions.set(sessionId, count);
|
|
240
|
+
else openingSessions.delete(sessionId);
|
|
241
|
+
};
|
|
242
|
+
function keepRecoveryError(sessionId, message) {
|
|
243
|
+
if (scheduler?.holds(sessionId)) recoveryErrors.set(sessionId, message);
|
|
244
|
+
}
|
|
245
|
+
function dropRecoveryError(sessionId) {
|
|
246
|
+
if (!scheduler?.holds(sessionId)) recoveryErrors.delete(sessionId);
|
|
247
|
+
}
|
|
248
|
+
const scheduler = schedules ? createScheduler({
|
|
249
|
+
store: schedules,
|
|
250
|
+
runtime,
|
|
251
|
+
deliver: deliverJob,
|
|
252
|
+
ready: () => restored,
|
|
253
|
+
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,
|
|
254
|
+
settled: (sessionId) => dropRecoveryError(sessionId),
|
|
255
|
+
stopping: () => closing,
|
|
256
|
+
now: clock,
|
|
257
|
+
...scheduleDeliveryTimeoutMs === void 0 ? {} : { deliveryTimeoutMs: scheduleDeliveryTimeoutMs }
|
|
258
|
+
}) : void 0;
|
|
259
|
+
restored = store ? restore() : Promise.resolve();
|
|
260
|
+
const deliver = (connection, envelope) => {
|
|
261
|
+
const message = { jsonrpc: "2.0", method: "event", params: envelope };
|
|
262
|
+
const bytes = frameBytes(message);
|
|
263
|
+
if (bytes > 512 * 1024 && envelope.cursor !== void 0) message.params = {
|
|
264
|
+
...envelope,
|
|
265
|
+
event: { type: "item", item: { kind: "notice", id: `oversized:${envelope.cursor}`, level: "warning", text: `History event ${envelope.cursor} is too large to display (${bytes} bytes).` } }
|
|
266
|
+
};
|
|
267
|
+
connection.send(message);
|
|
268
|
+
};
|
|
79
269
|
const watchers = /* @__PURE__ */ new Map();
|
|
80
270
|
function projectOf(root) {
|
|
81
271
|
return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
|
|
82
272
|
}
|
|
273
|
+
const sameProject = (a, b) => {
|
|
274
|
+
if (a === void 0 || b === void 0) return a === b;
|
|
275
|
+
return a === b || projectKey(a) === projectKey(b);
|
|
276
|
+
};
|
|
83
277
|
function tellWatchers(root, envelope, turn = false) {
|
|
84
278
|
if (!watchers.size) return;
|
|
85
279
|
const { cursor: _cursor, ...announced } = envelope;
|
|
@@ -87,10 +281,30 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
87
281
|
for (const [connection, { projectRoot, turns }] of watchers) {
|
|
88
282
|
if (turn && !turns) continue;
|
|
89
283
|
if (attached.get(root)?.has(connection)) continue;
|
|
90
|
-
if (projectRoot !== void 0 && project
|
|
284
|
+
if (projectRoot !== void 0 && !sameProject(project, projectRoot)) continue;
|
|
91
285
|
deliver(connection, announced);
|
|
92
286
|
}
|
|
93
287
|
}
|
|
288
|
+
function tellAttention(root, attention) {
|
|
289
|
+
if (!watchers.size) return;
|
|
290
|
+
const project = projectOf(root);
|
|
291
|
+
const envelope = { sessionId: root, epoch: `attention-${startedAt}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "attention", ...attention ? { attention } : {} } };
|
|
292
|
+
for (const [connection, watch] of watchers) {
|
|
293
|
+
if (!watch.attention) continue;
|
|
294
|
+
if (watch.projectRoot !== void 0 && !sameProject(project, watch.projectRoot)) continue;
|
|
295
|
+
deliver(connection, envelope);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const pendingAcks = /* @__PURE__ */ new Map();
|
|
299
|
+
function attentionOf(projectRoot) {
|
|
300
|
+
const found = [];
|
|
301
|
+
for (const record of records.values()) {
|
|
302
|
+
if (record.id !== record.rootId || !record.attention || record.archived) continue;
|
|
303
|
+
if (projectRoot !== void 0 && !sameProject(projectOf(record.id), projectRoot)) continue;
|
|
304
|
+
found.push({ sessionId: record.id, attention: record.attention });
|
|
305
|
+
}
|
|
306
|
+
return found;
|
|
307
|
+
}
|
|
94
308
|
function save(record, changes = {}) {
|
|
95
309
|
Object.assign(record, changes, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
96
310
|
records.set(record.id, record);
|
|
@@ -121,17 +335,19 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
121
335
|
}
|
|
122
336
|
if (!record) return false;
|
|
123
337
|
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 });
|
|
338
|
+
else if (event.type === "turn.started") save(record, { status: "running", activeTurnId: event.turnId, archived: void 0, ...sessionId === root ? { attention: void 0 } : {} });
|
|
125
339
|
else if (event.type === "turn.ended") save(record, {
|
|
126
340
|
status: "idle",
|
|
127
341
|
activeTurnId: void 0,
|
|
342
|
+
// A root's turn that completed or failed asks every client for a look until one acknowledges it (Paseo's checkAndSetAttention).
|
|
343
|
+
...sessionId === root ? { attention: turnAttention(event) } : {},
|
|
128
344
|
...record.session ? { session: { ...record.session, parked: event.state === "failed" ? runtime.snapshot(sessionId)?.parked : void 0 } } : {},
|
|
129
345
|
...event.state === "failed" ? { lastError: { message: event.error?.message ?? "Turn failed" } } : {}
|
|
130
346
|
});
|
|
131
347
|
else if (event.type === "usage" && record.session) record.session = { ...record.session, usage: event.usage };
|
|
132
348
|
else if (event.type === "session.failed") save(record, { status: "error", lastError: event.error });
|
|
133
349
|
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" &&
|
|
350
|
+
else if (event.type === "item" && sessionId === root && !record.title && event.item.kind === "user_message" && fromUser(event.item)) {
|
|
135
351
|
const title = titleFromPrompt(event.item.text);
|
|
136
352
|
if (title) {
|
|
137
353
|
save(record, { title });
|
|
@@ -140,6 +356,11 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
140
356
|
}
|
|
141
357
|
return false;
|
|
142
358
|
}
|
|
359
|
+
function turnAttention(event) {
|
|
360
|
+
if (event.state === "canceled") return void 0;
|
|
361
|
+
const message = event.error?.message?.trim();
|
|
362
|
+
return { reason: event.state === "completed" ? "finished" : "error", at: (/* @__PURE__ */ new Date()).toISOString(), turnId: event.turnId, ...event.state === "failed" && message ? { message: event.error.message } : {} };
|
|
363
|
+
}
|
|
143
364
|
function announceTitle(root, title) {
|
|
144
365
|
const session = runtime.snapshot(root);
|
|
145
366
|
if (!session || rootOf.get(root) !== root) return;
|
|
@@ -166,7 +387,11 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
166
387
|
log2.push(envelope);
|
|
167
388
|
if (log2.length > TREE_LOG_LIMIT) log2.splice(0, log2.length - TREE_LOG_LIMIT);
|
|
168
389
|
logs.set(root, log2);
|
|
390
|
+
const before = records.get(root)?.attention;
|
|
169
391
|
named = track(sessionId, root, event);
|
|
392
|
+
const after = records.get(root)?.attention;
|
|
393
|
+
if (sessionId === root && (event.type === "turn.started" || event.type === "turn.ended")) pendingAcks.delete(root);
|
|
394
|
+
if (after !== before) tellAttention(root, after);
|
|
170
395
|
}
|
|
171
396
|
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
172
397
|
if (event.type === "question" || event.type === "question.resolved") tellWatchers(root, envelope);
|
|
@@ -180,19 +405,23 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
180
405
|
});
|
|
181
406
|
async function restore() {
|
|
182
407
|
await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: true });
|
|
408
|
+
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
409
|
const loaded = await store.list();
|
|
184
410
|
await reconcileReceipts(loaded);
|
|
185
411
|
const now = Date.now();
|
|
186
412
|
const ended = { code: "daemon_restarted", message: "alpd stopped while this session was working" };
|
|
187
413
|
const epoch = `restart-${startedAt}`;
|
|
188
414
|
const continuing = new Set(runtime.recoverable().map((entry) => entry.assignmentId));
|
|
415
|
+
const pending = await schedules?.all({ status: "pending" }) ?? [];
|
|
416
|
+
for (const job of pending) scheduler?.hold(job);
|
|
417
|
+
const scheduled = new Set(pending.map((job) => job.sessionId));
|
|
189
418
|
const reopen = [];
|
|
190
419
|
const byRoot = trees(loaded);
|
|
191
420
|
const removed = await expire(byRoot, now);
|
|
192
421
|
for (const [root, tree] of byRoot) {
|
|
193
422
|
const head = tree.find((record) => record.id === root);
|
|
194
423
|
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" });
|
|
424
|
+
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
425
|
if (tree.some((record) => LIVE.includes(record.status))) seen(root, await store.timeline(root));
|
|
197
426
|
for (const record of tree) {
|
|
198
427
|
records.set(record.id, record);
|
|
@@ -214,12 +443,22 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
214
443
|
}
|
|
215
444
|
}
|
|
216
445
|
}
|
|
446
|
+
if (conversation) await conversation.recover().catch((error) => recoveryLog.error("could not recover lifecycle operations", { code: "ALPD_LIFECYCLE_RECOVERY_FAILED", error }));
|
|
217
447
|
const reopened = new Set(reopen.map((entry) => entry.record.id));
|
|
218
448
|
for (const rootId of new Set(runtime.recoverable().map((entry) => entry.rootId))) {
|
|
219
449
|
if (!reopened.has(rootId)) await runtime.abandon(rootId, "its root session cannot be reopened").catch(() => {
|
|
220
450
|
});
|
|
221
451
|
}
|
|
222
|
-
for (const { record, working } of reopen)
|
|
452
|
+
for (const { record, working } of reopen) {
|
|
453
|
+
if (fencedRoot(record.id)) {
|
|
454
|
+
recoveryLog.warn(`${record.id} is not reopened: a rewind of it is not finished`, { code: "ALPD_REWIND_FENCED", sessionId: record.id });
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
markOpening(record.id);
|
|
458
|
+
recovering.set(record.id, recoverTree(record, working, () => {
|
|
459
|
+
clearOpening(record.id);
|
|
460
|
+
}));
|
|
461
|
+
}
|
|
223
462
|
}
|
|
224
463
|
function trees(list) {
|
|
225
464
|
const byRoot = /* @__PURE__ */ new Map();
|
|
@@ -235,36 +474,49 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
235
474
|
}
|
|
236
475
|
const continuing = new Set(runtime.recoverable().map((entry) => entry.rootId));
|
|
237
476
|
for (const [root, tree] of byRoot) {
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
477
|
+
const remove = async () => {
|
|
478
|
+
if (!tree.some((record) => record.id === root)) return;
|
|
479
|
+
if (tree.some((record) => LIVE.includes(record.status))) return;
|
|
480
|
+
if (now - Math.max(...tree.map((record) => Date.parse(record.updatedAt) || now)) <= RETENTION_MS) return;
|
|
481
|
+
if (tree.some((record) => now - (receiptWritten.get(record.id) ?? 0) <= RECEIPT_RETENTION_MS)) return;
|
|
482
|
+
if (continuing.has(root) || rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
483
|
+
if (scheduler?.holds(root)) return;
|
|
484
|
+
const ids = tree.map((record) => record.id);
|
|
485
|
+
if (now - await store.writtenAt(ids) <= RETENTION_MS) return;
|
|
486
|
+
if (rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
487
|
+
if (await conversation?.retainsFork(root)) return;
|
|
488
|
+
for (const id of ids) records.delete(id);
|
|
489
|
+
cursors.delete(root);
|
|
490
|
+
await store.remove(root, ids);
|
|
491
|
+
await attachments?.releaseSessions(ids).catch((error) => recoveryLog.warn("could not release the attachments of removed sessions", { code: "ALPD_ATTACHMENT_RELEASE_FAILED", error }));
|
|
492
|
+
if (runLogDir) await unlink(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`)).catch(() => {
|
|
493
|
+
});
|
|
494
|
+
removed.add(root);
|
|
495
|
+
};
|
|
496
|
+
if (conversation) await conversation.lifecycle.serial(root, remove);
|
|
497
|
+
else await remove();
|
|
252
498
|
}
|
|
253
499
|
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
500
|
return removed;
|
|
255
501
|
}
|
|
502
|
+
let sweeping = false;
|
|
256
503
|
async function sweep() {
|
|
257
|
-
if (closing || !store) return;
|
|
504
|
+
if (closing || !store || sweeping) return;
|
|
505
|
+
sweeping = true;
|
|
258
506
|
try {
|
|
259
507
|
await restored;
|
|
260
508
|
await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
|
|
509
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS);
|
|
261
510
|
await expire(trees(records.values()));
|
|
262
511
|
} catch (error) {
|
|
263
512
|
recoveryLog.warn("retention sweep failed", { code: "ALP_RETENTION_FAILED", error });
|
|
513
|
+
} finally {
|
|
514
|
+
sweeping = false;
|
|
264
515
|
}
|
|
265
516
|
}
|
|
266
517
|
const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : void 0;
|
|
267
518
|
sweeper?.unref();
|
|
519
|
+
scheduler?.start(scheduleTickMs);
|
|
268
520
|
async function reconcileReceipts(loaded) {
|
|
269
521
|
const rootOfRecord = new Map(loaded.map((record) => [record.id, record.rootId]));
|
|
270
522
|
const timelines = /* @__PURE__ */ new Map();
|
|
@@ -284,20 +536,30 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
284
536
|
function resumable(record) {
|
|
285
537
|
return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
|
|
286
538
|
}
|
|
287
|
-
async function recoverTree(record, working) {
|
|
539
|
+
async function recoverTree(record, working, opened) {
|
|
288
540
|
const session = record.session;
|
|
541
|
+
let openedOnce = false;
|
|
542
|
+
const open = () => {
|
|
543
|
+
if (openedOnce) return;
|
|
544
|
+
openedOnce = true;
|
|
545
|
+
opened?.();
|
|
546
|
+
};
|
|
289
547
|
try {
|
|
548
|
+
if (worktrees && record.spec?.cwd) await worktrees.assertAvailable(record.spec.cwd);
|
|
290
549
|
const stored = await treeLog(record.id);
|
|
291
550
|
seen(record.id, stored);
|
|
292
551
|
logs.set(record.id, [...stored]);
|
|
293
552
|
await runtime.open(record.id, {
|
|
294
553
|
...record.spec,
|
|
295
554
|
persist: true,
|
|
296
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
|
|
555
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...record.base ? { base: record.base } : {} }
|
|
297
556
|
}, { history: "skip", delegation: record.delegation ?? true });
|
|
557
|
+
open();
|
|
298
558
|
const outcomes = await runtime.recover(record.id, { continueRoot: working, parkedRoot: session.parked });
|
|
299
559
|
recoveryLog.info(`recovered ${record.id}: ${outcomes.map((outcome) => `${outcome.agent} ${outcome.outcome}`).join(", ") || "root"}`, { event: "recovered", sessionId: record.id, rootId: record.rootId });
|
|
300
560
|
} catch (error) {
|
|
561
|
+
open();
|
|
562
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
301
563
|
recoveryLog.error(`could not recover ${record.id}`, { code: "ALP_RECOVERY_FAILED", sessionId: record.id, rootId: record.rootId, error });
|
|
302
564
|
await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {
|
|
303
565
|
});
|
|
@@ -306,7 +568,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
306
568
|
setImmediate(() => void reap(record.id));
|
|
307
569
|
}
|
|
308
570
|
}
|
|
309
|
-
function deliverOnce(sessionId, clientMessageId, fingerprint, send) {
|
|
571
|
+
function deliverOnce(sessionId, clientMessageId, fingerprint, send, { requireReceipt = false, prepare, abandon } = {}) {
|
|
310
572
|
const key = digest(["prompt", sessionId, clientMessageId]);
|
|
311
573
|
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
574
|
const answer = (receipt, extra = {}) => ({ outcome: receipt.outcome ?? "accepted", ...receipt.error ? { error: receipt.error } : {}, ...extra });
|
|
@@ -325,12 +587,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
325
587
|
if (existing.state === "pending" || existing.outcome === "unknown") throw unknown();
|
|
326
588
|
return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
|
|
327
589
|
}
|
|
590
|
+
if (requireReceipt) throw unknown();
|
|
328
591
|
const receipt = (state, changes = {}) => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
329
592
|
live(sessionId);
|
|
593
|
+
await prepare?.(key);
|
|
330
594
|
crashPoint("prompt.before-receipt");
|
|
331
595
|
try {
|
|
332
596
|
await store.putReceipt(key, receipt("pending"));
|
|
333
597
|
} catch (error) {
|
|
598
|
+
await abandon?.(key).catch(() => {
|
|
599
|
+
});
|
|
334
600
|
throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error);
|
|
335
601
|
}
|
|
336
602
|
crashPoint("prompt.after-receipt");
|
|
@@ -345,6 +611,8 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
345
611
|
} catch (error) {
|
|
346
612
|
await store.removeReceipt(key).catch(() => {
|
|
347
613
|
});
|
|
614
|
+
await abandon?.(key).catch(() => {
|
|
615
|
+
});
|
|
348
616
|
throw error;
|
|
349
617
|
} finally {
|
|
350
618
|
stop();
|
|
@@ -366,7 +634,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
366
634
|
};
|
|
367
635
|
const previous = delivering.get(key) ?? Promise.resolve();
|
|
368
636
|
const result = previous.catch(() => {
|
|
369
|
-
}).then(attempt);
|
|
637
|
+
}).then(() => gated(sessionId, attempt));
|
|
370
638
|
delivering.set(key, result);
|
|
371
639
|
void result.finally(() => {
|
|
372
640
|
if (delivering.get(key) === result) delivering.delete(key);
|
|
@@ -374,17 +642,29 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
374
642
|
});
|
|
375
643
|
return result;
|
|
376
644
|
}
|
|
645
|
+
async function deliverJob(job, content, messageId, send = (id, input) => runtime.prompt(id, input)) {
|
|
646
|
+
const clientMessageId = messageId || scheduleMessageId(job);
|
|
647
|
+
return deliverOnce(job.sessionId, clientMessageId, digest({ delivery: "auto", content }), async () => {
|
|
648
|
+
live(job.sessionId);
|
|
649
|
+
await send(job.sessionId, { clientMessageId, delivery: "auto", content });
|
|
650
|
+
}, { requireReceipt: job.attempts > 1 });
|
|
651
|
+
}
|
|
377
652
|
async function persisted(root) {
|
|
378
653
|
if (!store) return {};
|
|
379
654
|
return { durable: (await store.drain({ records: [root], timelines: [root] })).length === 0 };
|
|
380
655
|
}
|
|
381
656
|
function forget(root) {
|
|
382
657
|
if (runtime.snapshot(root)) return;
|
|
383
|
-
for (const [id, candidate] of rootOf) if (candidate === root)
|
|
658
|
+
for (const [id, candidate] of rootOf) if (candidate === root) {
|
|
659
|
+
rootOf.delete(id);
|
|
660
|
+
recoveryErrors.delete(id);
|
|
661
|
+
}
|
|
662
|
+
recoveryErrors.delete(root);
|
|
384
663
|
logs.delete(root);
|
|
385
664
|
}
|
|
386
665
|
async function reap(root) {
|
|
387
666
|
if (closing || attached.get(root)?.size || recovering.has(root)) return false;
|
|
667
|
+
if (scheduler?.holds(root)) return false;
|
|
388
668
|
const session = runtime.snapshot(root);
|
|
389
669
|
if (!session || session.busy) return false;
|
|
390
670
|
await runtime.close(root).catch(() => {
|
|
@@ -408,7 +688,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
408
688
|
const session = live2 ?? record?.session;
|
|
409
689
|
if (!session) return void 0;
|
|
410
690
|
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 };
|
|
691
|
+
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
692
|
}
|
|
413
693
|
function rootRecord(sessionId) {
|
|
414
694
|
if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
|
|
@@ -470,27 +750,107 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
470
750
|
if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, "This session cannot be resumed");
|
|
471
751
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
472
752
|
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);
|
|
753
|
+
markOpening(record.id);
|
|
754
|
+
recoveryErrors.delete(record.id);
|
|
755
|
+
let applied = false;
|
|
477
756
|
try {
|
|
757
|
+
if (worktrees) await worktrees.assertAvailable(record.spec.cwd);
|
|
758
|
+
const stored = await treeLog(record.id);
|
|
759
|
+
seen(record.id, stored);
|
|
760
|
+
logs.set(record.id, [...stored]);
|
|
761
|
+
attach(connection, record.id);
|
|
478
762
|
const opened = await runtime.open(record.id, {
|
|
479
763
|
...record.spec,
|
|
480
764
|
...spec.mode !== void 0 ? { mode: spec.mode } : {},
|
|
481
765
|
...spec.thinking !== void 0 ? { thinking: spec.thinking } : {},
|
|
482
766
|
persist: true,
|
|
483
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
|
|
767
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...record.base ? { base: record.base } : {} }
|
|
484
768
|
}, { history: stored.length ? "skip" : history, delegation: record.delegation ?? delegation });
|
|
769
|
+
applied = true;
|
|
770
|
+
await persistAcceptedSpec(record.id, opened, { mode: spec.mode !== void 0, thinking: spec.thinking !== void 0 });
|
|
485
771
|
if (history === "replay") replayHistory(connection, record.id, stored);
|
|
486
772
|
return opened;
|
|
487
773
|
} catch (error) {
|
|
774
|
+
if (applied) throw error;
|
|
488
775
|
detach(connection, record.id);
|
|
776
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
489
777
|
throw error;
|
|
778
|
+
} finally {
|
|
779
|
+
clearOpening(record.id);
|
|
490
780
|
}
|
|
491
781
|
}
|
|
492
|
-
|
|
782
|
+
async function persistAcceptedSpec(id, accepted, fields) {
|
|
783
|
+
const record = records.get(id);
|
|
784
|
+
if (!record?.spec || !fields.mode && !fields.thinking) return;
|
|
785
|
+
record.spec = {
|
|
786
|
+
...record.spec,
|
|
787
|
+
...fields.mode ? { mode: accepted.mode } : {},
|
|
788
|
+
...fields.thinking ? { thinking: accepted.thinking } : {}
|
|
789
|
+
};
|
|
790
|
+
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
791
|
+
try {
|
|
792
|
+
await store?.put(record);
|
|
793
|
+
} catch (error) {
|
|
794
|
+
throw persistenceFailed(`the configuration of ${id}; the runtime already applied it`, error);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
const registry = home ? createRegistry(home) : void 0;
|
|
798
|
+
const worktrees = home && registry && process.platform !== "win32" ? createWorkspaceWorktrees(
|
|
799
|
+
home,
|
|
800
|
+
registry,
|
|
801
|
+
async (directory, run) => {
|
|
802
|
+
if (!runtime.withWorkspaceMutation) throw new RegistryError(1005, "Runtime cannot prove safe worktree removal", { reason: "guard_unavailable" });
|
|
803
|
+
try {
|
|
804
|
+
return await runtime.withWorkspaceMutation(directory, run);
|
|
805
|
+
} catch (error) {
|
|
806
|
+
if (error?.data?.reason) throw new RegistryError(1004, "Workspace is in use or has retained assignment results", error.data);
|
|
807
|
+
throw error;
|
|
808
|
+
}
|
|
809
|
+
},
|
|
810
|
+
async (directory) => {
|
|
811
|
+
if (!runtime.registerWorkspace) throw new RegistryError(1005, "Runtime cannot register safe workspace ownership", { reason: "guard_unavailable" });
|
|
812
|
+
await runtime.registerWorkspace(directory);
|
|
813
|
+
},
|
|
814
|
+
// Owner-audited adoption (t-c1ba); no RPC exposes it yet, so the default stays refusal.
|
|
815
|
+
runtime.adoptWorkspace ? async (directory, verify) => {
|
|
816
|
+
try {
|
|
817
|
+
await runtime.adoptWorkspace(directory, verify);
|
|
818
|
+
} catch (error) {
|
|
819
|
+
if (error?.data?.reason && !(error instanceof RegistryError)) throw new RegistryError(1004, "Workspace is in use, has retained assignment results or changed identity", error.data);
|
|
820
|
+
throw error;
|
|
821
|
+
}
|
|
822
|
+
} : void 0
|
|
823
|
+
) : void 0;
|
|
824
|
+
const workspaceDescriptor = async (w) => worktrees ? worktrees.describe(w) : w;
|
|
825
|
+
const gitReader = registry ? createGitReader({ registry, log: (message, fields) => log.warn(message, { code: "ALPD_GIT_READ_FAILED", ...fields }) }) : void 0;
|
|
826
|
+
const gitFacts = createGitReader({ log: (message, fields) => log.warn(message, { code: "ALPD_GIT_READ_FAILED", ...fields }) });
|
|
827
|
+
const terminals = home && registry ? createTerminalService({
|
|
828
|
+
home,
|
|
829
|
+
resolveWorkspace: (workspaceId) => registry.resolve(workspaceId),
|
|
830
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
831
|
+
...terminalOptions
|
|
832
|
+
}) : void 0;
|
|
833
|
+
const terminalCall = (run) => {
|
|
834
|
+
if (!terminals) throw new RpcError(ERROR.unavailable, "This alpd has no home: it serves no terminals", { reason: "terminal_unsupported" });
|
|
835
|
+
return run(terminals);
|
|
836
|
+
};
|
|
837
|
+
const attachmentCall = async (run) => {
|
|
838
|
+
if (!attachments) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not store attachments (capability attachments is not listed)");
|
|
839
|
+
try {
|
|
840
|
+
return await run(attachments);
|
|
841
|
+
} catch (error) {
|
|
842
|
+
if (error instanceof RpcError) throw error;
|
|
843
|
+
log.warn("attachment call failed", { code: "ALPD_ATTACHMENT_FAILED", error });
|
|
844
|
+
throw new RpcError(ERROR.failed, "alpd could not store the attachment; the upload was aborted", { reason: "persistence_failed" });
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
const gitCall = (run) => {
|
|
848
|
+
if (!gitReader) throw new RpcError(ERROR.unavailable, "Registry needs ALP_HOME");
|
|
849
|
+
return run(gitReader);
|
|
850
|
+
};
|
|
851
|
+
const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])), onGateChange: (root) => runtime.syncGates?.(root) });
|
|
493
852
|
const extensionOwners = /* @__PURE__ */ new Map();
|
|
853
|
+
const findPages = createFindPages();
|
|
494
854
|
const handlers = {
|
|
495
855
|
"extension.register": async (connection, params) => {
|
|
496
856
|
const method = params?.method;
|
|
@@ -550,17 +910,46 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
550
910
|
return { rootId: root, entries };
|
|
551
911
|
},
|
|
552
912
|
"question.list"(_connection, { projectRoot } = {}) {
|
|
553
|
-
return { questions: runtime.questions().filter((question) => projectRoot === void 0 || projectOf(question.rootId)
|
|
913
|
+
return { questions: runtime.questions().filter((question) => projectRoot === void 0 || sameProject(projectOf(question.rootId), projectRoot)) };
|
|
554
914
|
},
|
|
555
915
|
/**
|
|
556
916
|
* The questions waiting now; from then on this connection is told of `question` and
|
|
557
917
|
* `question.resolved` in every tree, or those of `projectRoot`, attached or not. Calling it
|
|
558
918
|
* again replaces the filter; it lasts as long as the connection (ALPD §15). With `turns`, also
|
|
559
|
-
* of `turn.ended` of every root
|
|
919
|
+
* of `turn.ended` of every root; with `attention`, also of each root's attention, now and as it
|
|
920
|
+
* changes (docs/protocol/alp-json-rpc-v1.md §12.2).
|
|
921
|
+
*/
|
|
922
|
+
"question.watch"(connection, { projectRoot, turns, attention } = {}) {
|
|
923
|
+
watchers.set(connection, { projectRoot, turns: turns === true, attention: attention === true });
|
|
924
|
+
return {
|
|
925
|
+
questions: runtime.questions().filter((question) => projectRoot === void 0 || sameProject(projectOf(question.rootId), projectRoot)),
|
|
926
|
+
...attention === true ? { attention: attentionOf(projectRoot) } : {}
|
|
927
|
+
};
|
|
928
|
+
},
|
|
929
|
+
/**
|
|
930
|
+
* Acknowledges a root's attention for every client, as Paseo's clear_agent_attention; with `at`,
|
|
931
|
+
* only the attention set then, so a look at an older turn end never hides a newer one (§12.2).
|
|
560
932
|
*/
|
|
561
|
-
"
|
|
562
|
-
|
|
563
|
-
|
|
933
|
+
async "session.attention.clear"(_connection, { sessionId, at }) {
|
|
934
|
+
if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
|
|
935
|
+
if (at !== void 0 && typeof at !== "string") throw new RpcError(-32602, "at must be a string");
|
|
936
|
+
const record = records.get(sessionId);
|
|
937
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
|
|
938
|
+
const attention = record.attention;
|
|
939
|
+
if (!attention || at !== void 0 && attention.at !== at) return { cleared: false };
|
|
940
|
+
const ack = {};
|
|
941
|
+
pendingAcks.set(record.id, ack);
|
|
942
|
+
record.attention = void 0;
|
|
943
|
+
try {
|
|
944
|
+
await store?.put(record);
|
|
945
|
+
} catch (error) {
|
|
946
|
+
if (pendingAcks.get(record.id) === ack && !record.attention) record.attention = attention;
|
|
947
|
+
throw persistenceFailed(`the attention of ${record.id}`, error);
|
|
948
|
+
} finally {
|
|
949
|
+
if (pendingAcks.get(record.id) === ack) pendingAcks.delete(record.id);
|
|
950
|
+
}
|
|
951
|
+
tellAttention(record.id, record.attention);
|
|
952
|
+
return { cleared: true };
|
|
564
953
|
},
|
|
565
954
|
/**
|
|
566
955
|
* The files of a directory whose path matches a query, read-only and confined to it: no link
|
|
@@ -582,12 +971,27 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
582
971
|
* read-only, confined to it, no link followed, blocked paths always refused, .gitignore'd ones
|
|
583
972
|
* unless includeIgnored (docs/protocol/alp-json-rpc-v1.md §12.4, ALPD §15).
|
|
584
973
|
*/
|
|
585
|
-
async "workspace.files.list"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
586
|
-
return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
974
|
+
async "workspace.files.list"(_connection, { projectRoot, path: relative, includeIgnored, cursor, internalLinks } = {}) {
|
|
975
|
+
return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true, cursor, internalLinks: internalLinks === true }));
|
|
587
976
|
},
|
|
588
977
|
async "workspace.files.read"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
589
978
|
return filesCall(projectRoot, () => readWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
590
979
|
},
|
|
980
|
+
/**
|
|
981
|
+
* Every name under projectRoot in pages of a snapshot kept for this connection, and a file's
|
|
982
|
+
* preview in chunks (docs/protocol/alp-json-rpc-v1.md §12.11): what the Paseo bridge's Files
|
|
983
|
+
* panel and suggestions read, confined as workspace.files.read is. The gateway exposes neither.
|
|
984
|
+
*/
|
|
985
|
+
async "workspace.files.find"(connection, { projectRoot, query, kinds, matchMode, limit, cursor } = {}) {
|
|
986
|
+
return filesCall(projectRoot, () => findPages(connection, projectRoot, { query, kinds, matchMode, limit, cursor }));
|
|
987
|
+
},
|
|
988
|
+
async "workspace.files.preview"(_connection, { projectRoot, path: relative, includeIgnored, internalLinks, maxBytes, offset, revision } = {}) {
|
|
989
|
+
return filesCall(projectRoot, () => previewWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true, internalLinks: internalLinks === true, maxBytes, offset, revision }));
|
|
990
|
+
},
|
|
991
|
+
/** The host's directories for the folder to add as a project (§12.11): the owner's own names, never remote. */
|
|
992
|
+
async "host.directories.search"(_connection, { query, limit } = {}) {
|
|
993
|
+
return searchHostDirectories(query, { limit });
|
|
994
|
+
},
|
|
591
995
|
/** The project board: live claims, decisions and findings (ALPD §18). */
|
|
592
996
|
async "board.list"(_connection, { projectRoot } = {}) {
|
|
593
997
|
if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, "An absolute projectRoot is required");
|
|
@@ -621,29 +1025,125 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
621
1025
|
throw new RpcError(ERROR.failed, error?.message ?? String(error));
|
|
622
1026
|
}
|
|
623
1027
|
},
|
|
624
|
-
"question.answer"(
|
|
1028
|
+
"question.answer"(connection, { questionId, text, dismiss = false, reason }) {
|
|
1029
|
+
if (connection.agent) throw new RpcError(ERROR.forbidden, "Only the user answers a question; this connection was opened by an ALP agent", { reason: "user_only" });
|
|
625
1030
|
if (typeof questionId !== "string") throw new RpcError(-32602, "questionId is required");
|
|
626
1031
|
if (dismiss !== true && typeof text !== "string") throw new RpcError(-32602, "text or dismiss is required");
|
|
627
1032
|
const matches = runtime.questions().filter((question) => question.id === questionId || question.id.startsWith(questionId));
|
|
628
1033
|
if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
|
|
629
|
-
|
|
1034
|
+
const channel = connection.client?.startsWith("alp-paseo") ? "paseo" : "web";
|
|
1035
|
+
runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
|
|
630
1036
|
return { questionId: matches[0].id };
|
|
631
1037
|
},
|
|
632
1038
|
"daemon.shutdown": () => {
|
|
633
1039
|
setImmediate(() => onShutdown?.());
|
|
634
1040
|
return {};
|
|
635
1041
|
},
|
|
636
|
-
"
|
|
637
|
-
|
|
1042
|
+
"registry.owner": (_c, params) => registryCall(async () => {
|
|
1043
|
+
const result = params.operation ? await registry.mutate(params.operation, params.args ?? {}, { requestId: params.requestId, ifRevision: params.ifRevision }) : void 0;
|
|
1044
|
+
const { receipts: _receipts, ...metadata } = await registry.snapshot();
|
|
1045
|
+
return { ...result ? { result } : {}, registry: metadata };
|
|
1046
|
+
}),
|
|
1047
|
+
"registry.worktree": (_c, p) => registryCall(async () => worktrees ? worktrees.grants(p) : { mappings: [], workspaces: [] }),
|
|
1048
|
+
"workspace.worktree.options": (_c, p) => registryCall(async () => {
|
|
1049
|
+
const w = (await registry.snapshot()).workspaces.find((w2) => w2.id === p.workspaceId);
|
|
1050
|
+
if (!w) throw new RegistryError(1001, "No workspace", { reason: "not_found" });
|
|
1051
|
+
const grants = worktrees ? await worktrees.grants(p) : { mappings: [], workspaces: [] };
|
|
1052
|
+
return { mappingIds: grants.mappings.filter((m) => m.source === (w.canonical ?? w.directory)).map((m) => m.id) };
|
|
1053
|
+
}),
|
|
1054
|
+
"workspace.worktree.create": (_c, p) => registryCall(async () => {
|
|
1055
|
+
if (!worktrees) throw new RegistryError(1005, "Worktrees are unavailable on this platform", { reason: "worktrees_unsupported" });
|
|
1056
|
+
const result = await worktrees.mutate("create", p, p);
|
|
1057
|
+
return { ...result, workspace: await workspaceDescriptor(result.workspace) };
|
|
1058
|
+
}),
|
|
1059
|
+
"workspace.worktree.remove": (_c, p) => registryCall(async () => {
|
|
1060
|
+
if (!worktrees) throw new RegistryError(1005, "Worktrees are unavailable on this platform", { reason: "worktrees_unsupported" });
|
|
1061
|
+
const result = await worktrees.mutate("remove", p, p);
|
|
1062
|
+
return { ...result, workspace: await workspaceDescriptor(result.workspace) };
|
|
1063
|
+
}),
|
|
1064
|
+
"workspace.git.status": (_c, p) => gitCall((reader) => reader.status(p.workspaceId)),
|
|
1065
|
+
"workspace.git.diff": (_c, p) => gitCall((reader) => reader.diff({ workspaceId: p.workspaceId, compare: p.compare, path: p.path, cursor: p.cursor })),
|
|
1066
|
+
"workspace.git.facts": (c, p) => agentRefused(c, "workspace.git.facts") ?? gitFacts.facts(p.directory),
|
|
1067
|
+
"project.list": (_c, p) => registryList("projects", p),
|
|
1068
|
+
"workspace.list": (_c, p) => registryList("workspaces", p),
|
|
1069
|
+
"workspace.get": (_c, p) => registryCall(async () => {
|
|
1070
|
+
await registry.resolve(p.workspaceId, void 0, true);
|
|
1071
|
+
const r = await registry.snapshot();
|
|
1072
|
+
return { workspace: { ...await workspaceDescriptor(r.workspaces.find((w) => w.id === p.workspaceId)), revision: r.revision }, revision: r.revision };
|
|
1073
|
+
}),
|
|
1074
|
+
"project.register": (_c, p) => registryMutation("project.register", p),
|
|
1075
|
+
"project.remove": (_c, p) => registryMutation("project.remove", p),
|
|
1076
|
+
"workspace.update": (_c, p) => registryMutation("workspace.update", p),
|
|
1077
|
+
"catalog.get": () => catalogResult(),
|
|
1078
|
+
"catalog.refresh": async () => {
|
|
1079
|
+
if (!modelCatalog) throw new RpcError(ERROR.unavailable, "The live model catalog is not available");
|
|
1080
|
+
await modelCatalog.refresh();
|
|
1081
|
+
return catalogResult();
|
|
1082
|
+
},
|
|
1083
|
+
// attachment.* (§12.6): each call acts for its principal context; without the store (no home or
|
|
1084
|
+
// store, or Windows) alpd does not serve them, as for any method it does not know.
|
|
1085
|
+
// terminal.* (§12.10): each call acts for its principal context; input, resize and the stream
|
|
1086
|
+
// belong to the connection that attached the terminal.
|
|
1087
|
+
"terminal.create": (c, p) => agentRefused(c, "terminal.create") ?? terminalCall((service) => service.create(principalOf(p), p)),
|
|
1088
|
+
"terminal.watch": (c, p) => terminalCall((service) => service.watch(principalOf(p), c, p)),
|
|
1089
|
+
"terminal.unwatch": (c) => terminalCall((service) => service.unwatch(c)),
|
|
1090
|
+
"terminal.capture": (_c, p) => terminalCall((service) => service.capture(principalOf(p), p)),
|
|
1091
|
+
"terminal.list": (_c, p) => terminalCall((service) => service.list(principalOf(p), p)),
|
|
1092
|
+
"terminal.attach": (c, p) => agentRefused(c, "terminal.attach") ?? terminalCall((service) => service.attach(principalOf(p), c, p)),
|
|
1093
|
+
"terminal.input": (c, p) => agentRefused(c, "terminal.input") ?? terminalCall((service) => service.input(principalOf(p), c, p)),
|
|
1094
|
+
"terminal.resize": (c, p) => terminalCall((service) => service.resize(principalOf(p), c, p)),
|
|
1095
|
+
"terminal.close": (_c, p) => terminalCall((service) => service.close(principalOf(p), p)),
|
|
1096
|
+
"terminal.revoke": (_c, p) => terminalCall((service) => service.revoke(p.principalId)),
|
|
1097
|
+
"attachment.begin": (_c, p) => attachmentCall((store2) => store2.begin(principalOf(p), p)),
|
|
1098
|
+
"attachment.chunk": (_c, p) => attachmentCall((store2) => store2.chunk(principalOf(p), p)),
|
|
1099
|
+
"attachment.commit": (_c, p) => attachmentCall((store2) => store2.commit(principalOf(p), p)),
|
|
1100
|
+
"attachment.abort": (_c, p) => attachmentCall((store2) => store2.abort(principalOf(p), p)),
|
|
1101
|
+
"attachment.get": (_c, p) => attachmentCall((store2) => store2.get(principalOf(p), p)),
|
|
1102
|
+
"attachment.delete": (_c, p) => attachmentCall((store2) => store2.remove(principalOf(p), p)),
|
|
1103
|
+
async "session.create"(connection, { sessionId, workspaceId, spec, history = "skip", delegation = true, resume: resuming = false }) {
|
|
1104
|
+
if (workspaceId !== void 0) {
|
|
1105
|
+
if (!registry || typeof workspaceId !== "string") throw new RpcError(-32602, "Invalid workspaceId");
|
|
1106
|
+
try {
|
|
1107
|
+
spec = { ...spec, cwd: await registry.resolve(workspaceId, spec?.cwd) };
|
|
1108
|
+
} catch (e) {
|
|
1109
|
+
if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data);
|
|
1110
|
+
throw e;
|
|
1111
|
+
}
|
|
1112
|
+
const placements = (await registryCall(() => registry.snapshot())).sessions;
|
|
1113
|
+
const prior = Object.hasOwn(placements, sessionId) ? placements[sessionId] : void 0;
|
|
1114
|
+
if (prior && prior !== workspaceId) throw new RpcError(ERROR.conflict, "Session belongs to another workspace", { reason: "workspace_mismatch" });
|
|
1115
|
+
}
|
|
638
1116
|
if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
|
|
1117
|
+
if (connection.agent && spec.restore !== void 0) {
|
|
1118
|
+
const { restore: _restore2, ...owned } = spec;
|
|
1119
|
+
spec = owned;
|
|
1120
|
+
}
|
|
1121
|
+
if (worktrees) await registryCall(() => worktrees.assertAvailable(spec.cwd));
|
|
639
1122
|
if (sessionId !== void 0 && (typeof sessionId !== "string" || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, "Invalid session id");
|
|
640
1123
|
if (history !== "replay" && history !== "skip") throw new RpcError(-32602, "history must be replay or skip");
|
|
641
1124
|
const id = sessionId ?? `ses_${randomBytes(8).toString("hex")}`;
|
|
642
1125
|
await recovering.get(id);
|
|
1126
|
+
while (holds.has(id)) await holds.get(id).open;
|
|
1127
|
+
refuseFenced(id);
|
|
1128
|
+
let reservedWorkspaceId;
|
|
1129
|
+
const reserve = async () => {
|
|
1130
|
+
if (!registry) return;
|
|
1131
|
+
const directory = runtime.snapshot(id)?.projectRoot ?? records.get(id)?.session?.projectRoot ?? records.get(id)?.spec?.cwd ?? spec.cwd;
|
|
1132
|
+
if (workspaceId) await registryCall(() => registry.resolve(workspaceId, directory));
|
|
1133
|
+
if (Object.hasOwn((await registry.snapshot()).sessions, id)) return;
|
|
1134
|
+
if (workspaceId) await registryCall(() => registry.mutate("placement.assign", { sessionId: id, workspaceId }, { requestId: `reserve:${randomBytes(12).toString("hex")}` }));
|
|
1135
|
+
else await registryCall(() => registry.mutate("placement.prepare", { sessions: [{ id, projectRoot: directory }] }, { requestId: `prepare:${randomBytes(12).toString("hex")}` }));
|
|
1136
|
+
reservedWorkspaceId = (await registry.snapshot()).sessions[id];
|
|
1137
|
+
};
|
|
1138
|
+
const rollback = async () => {
|
|
1139
|
+
if (!registry || !reservedWorkspaceId) return;
|
|
1140
|
+
await registryCall(() => registry.mutate("placement.remove", { sessionId: id, workspaceId: reservedWorkspaceId }, { requestId: `rollback:${randomBytes(12).toString("hex")}` }));
|
|
1141
|
+
};
|
|
643
1142
|
const existing = runtime.snapshot(id);
|
|
644
1143
|
if (existing) {
|
|
645
1144
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
646
1145
|
if (existing.parentId || agent !== void 0 && agent !== existing.agent) throw new RpcError(ERROR.failed, "Session is already open");
|
|
1146
|
+
await reserve();
|
|
647
1147
|
attach(connection, id);
|
|
648
1148
|
announce(connection, id, history);
|
|
649
1149
|
return { session: existing, attached: true };
|
|
@@ -651,8 +1151,14 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
651
1151
|
const record = records.get(id);
|
|
652
1152
|
if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
|
|
653
1153
|
if (record) {
|
|
654
|
-
|
|
655
|
-
|
|
1154
|
+
await reserve();
|
|
1155
|
+
try {
|
|
1156
|
+
const session = await resume(connection, record, spec, history, delegation);
|
|
1157
|
+
return { session, attached: false, resumed: true, ...await persisted(id) };
|
|
1158
|
+
} catch (error) {
|
|
1159
|
+
if (!runtime.snapshot(id)) await rollback();
|
|
1160
|
+
throw error;
|
|
1161
|
+
}
|
|
656
1162
|
}
|
|
657
1163
|
const { restore: _restore, ...kept } = spec;
|
|
658
1164
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -664,14 +1170,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
664
1170
|
if (records.get(id) === created) records.delete(id);
|
|
665
1171
|
throw persistenceFailed(`session ${id}; it was not started`, error);
|
|
666
1172
|
}
|
|
667
|
-
attach(connection, id);
|
|
668
1173
|
try {
|
|
1174
|
+
await reserve();
|
|
1175
|
+
attach(connection, id);
|
|
669
1176
|
const session = await runtime.open(id, spec, { history, delegation });
|
|
670
1177
|
return { session, attached: false, ...await persisted(id) };
|
|
671
1178
|
} catch (error) {
|
|
672
1179
|
detach(connection, id);
|
|
673
1180
|
records.delete(id);
|
|
674
1181
|
await store?.remove(id, [id]);
|
|
1182
|
+
await rollback();
|
|
675
1183
|
throw error;
|
|
676
1184
|
}
|
|
677
1185
|
},
|
|
@@ -685,42 +1193,75 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
685
1193
|
* events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
|
|
686
1194
|
* with the whole timeline. The replay and the live events that follow are in cursor order.
|
|
687
1195
|
*/
|
|
688
|
-
async "session.
|
|
689
|
-
|
|
690
|
-
|
|
1196
|
+
async "session.history"(_connection, { sessionId, before, limit, maxBytes }) {
|
|
1197
|
+
known(sessionId);
|
|
1198
|
+
if (!store) throw new RpcError(1005, "Durable history unavailable");
|
|
691
1199
|
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
1200
|
+
try {
|
|
1201
|
+
return await store.history(root, sessionId, { before, limit, maxBytes });
|
|
1202
|
+
} catch (error) {
|
|
1203
|
+
if (error instanceof HistoryError) throw new RpcError(error.reason === "stale_cursor" ? 1004 : -32602, error.message, { reason: error.reason });
|
|
1204
|
+
throw error;
|
|
697
1205
|
}
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
const
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
1206
|
+
},
|
|
1207
|
+
async "session.attach"(connection, { sessionId, replay = true, after, generation }) {
|
|
1208
|
+
if (after !== void 0 && (!Number.isSafeInteger(after) || after < 0)) throw new RpcError(-32602, "after must be a cursor");
|
|
1209
|
+
known(sessionId);
|
|
1210
|
+
const root = rootIdOf(sessionId);
|
|
1211
|
+
for (; ; ) {
|
|
1212
|
+
while (holds.has(root)) await holds.get(root).open;
|
|
1213
|
+
refuseFenced(root);
|
|
1214
|
+
const revision = holdRevision;
|
|
1215
|
+
const found = known(sessionId);
|
|
1216
|
+
let stored = [];
|
|
1217
|
+
if (replay || store && !cursors.has(root)) {
|
|
1218
|
+
const memory = logs.get(root);
|
|
1219
|
+
const covered = !!memory?.length && (memory[0].cursor ?? 1) <= (after ?? 0) + 1;
|
|
1220
|
+
if (!covered) stored = store ? await store.timeline(root) : memory ?? [];
|
|
709
1221
|
}
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
1222
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1223
|
+
if (generation !== void 0) {
|
|
1224
|
+
const checkpoint = await store?.history(root, sessionId, { limit: 1 });
|
|
1225
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1226
|
+
if (checkpoint?.generation !== generation) throw new RpcError(1004, "History generation changed", { reason: "stale_cursor" });
|
|
713
1227
|
}
|
|
1228
|
+
const live2 = logs.get(root) ?? [];
|
|
1229
|
+
const tip = Math.max(cursors.get(root) ?? 0, stored.at(-1)?.cursor ?? 0, live2.at(-1)?.cursor ?? 0);
|
|
1230
|
+
if (generation !== void 0 && replay) {
|
|
1231
|
+
const covered = Math.max(after ?? 0, stored.at(-1)?.cursor ?? 0);
|
|
1232
|
+
const next = live2.find((envelope) => (envelope.cursor ?? 0) > covered)?.cursor;
|
|
1233
|
+
if (next !== void 0 && next > covered + 1 || next === void 0 && tip > covered) {
|
|
1234
|
+
throw new RpcError(1005, "History advanced beyond replay coverage; retry attach", { reason: "history_gap" });
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
const first = replay ? [...stored, ...live2].find((envelope) => envelope.cursor !== void 0)?.cursor : void 0;
|
|
1238
|
+
const reset = after !== void 0 && (after > tip || replay && after < tip && (first === void 0 || first > after + 1) || !!conversation?.discarded(records.get(root), after));
|
|
1239
|
+
const from = reset ? 0 : after ?? 0;
|
|
1240
|
+
attach(connection, root);
|
|
1241
|
+
if (replay) {
|
|
1242
|
+
let last = from;
|
|
1243
|
+
for (const envelope of stored) if ((envelope.cursor ?? 0) > last) {
|
|
1244
|
+
if (current(envelope)) deliver(connection, envelope);
|
|
1245
|
+
last = envelope.cursor ?? last;
|
|
1246
|
+
}
|
|
1247
|
+
for (const envelope of live2) if ((envelope.cursor ?? 0) > last) {
|
|
1248
|
+
if (current(envelope)) deliver(connection, envelope);
|
|
1249
|
+
last = envelope.cursor ?? last;
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
announceQuestions(connection, root);
|
|
1253
|
+
const gateProject = runtime.snapshot(root)?.projectRoot;
|
|
1254
|
+
if (gateProject) void runtime.syncGates?.(gateProject)?.catch(() => {
|
|
1255
|
+
});
|
|
1256
|
+
return { session: root === found.id ? found : summary(root), cursor: tip, ...reset ? { reset: true } : {} };
|
|
714
1257
|
}
|
|
715
|
-
announceQuestions(connection, root);
|
|
716
|
-
return { session: root === found.id ? found : summary(root), cursor: tip, ...reset ? { reset: true } : {} };
|
|
717
1258
|
},
|
|
718
1259
|
async "session.release"(connection, { sessionId }) {
|
|
719
1260
|
const root = rootOf.get(sessionId) ?? sessionId;
|
|
720
1261
|
detach(connection, root);
|
|
721
1262
|
return { closed: await reap(root) };
|
|
722
1263
|
},
|
|
723
|
-
async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content }) {
|
|
1264
|
+
async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content, ...context }) {
|
|
724
1265
|
if (typeof clientMessageId !== "string" || !Array.isArray(content)) throw new RpcError(-32602, "clientMessageId and content are required");
|
|
725
1266
|
if (delivery !== "auto" && delivery !== "steer") throw new RpcError(-32602, "delivery must be auto or steer");
|
|
726
1267
|
const images = content.filter((part) => part?.type === "image");
|
|
@@ -732,22 +1273,89 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
732
1273
|
if (bytes > PROMPT_IMAGES.maxBytes) throw new RpcError(-32602, `An image in a prompt is at most ${PROMPT_IMAGES.maxBytes} bytes`);
|
|
733
1274
|
if (total > PROMPT_IMAGES.maxTotalBytes) throw new RpcError(-32602, `The images of a prompt are at most ${PROMPT_IMAGES.maxTotalBytes} bytes together`);
|
|
734
1275
|
}
|
|
1276
|
+
const attached2 = content.filter((part) => part?.type === "attachment");
|
|
1277
|
+
let resolved = [];
|
|
1278
|
+
if (attached2.length) {
|
|
1279
|
+
if (!attachments || !store) throw new RpcError(ERROR.unavailable, "This alpd does not store attachments", { reason: "attachment_unsupported" });
|
|
1280
|
+
resolved = await attachments.resolve(principalOf(context), sessionId, attached2.map((part) => part.attachmentId));
|
|
1281
|
+
}
|
|
1282
|
+
let index = 0;
|
|
1283
|
+
const delivered = attached2.length ? content.map((part) => part?.type === "attachment" ? resolved[index++] : part) : content;
|
|
1284
|
+
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
1285
|
const send = async () => {
|
|
736
1286
|
live(sessionId);
|
|
737
|
-
await runtime.prompt(sessionId, { clientMessageId, delivery, content });
|
|
1287
|
+
await runtime.prompt(sessionId, { clientMessageId, delivery, content: delivered });
|
|
738
1288
|
};
|
|
739
1289
|
if (!store) {
|
|
740
|
-
await send
|
|
1290
|
+
await gated(sessionId, send);
|
|
741
1291
|
return {};
|
|
742
1292
|
}
|
|
743
|
-
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
1293
|
+
if (!attached2.length) return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
1294
|
+
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content: fingerprinted }), send, {
|
|
1295
|
+
prepare: async (key) => {
|
|
1296
|
+
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" });
|
|
1297
|
+
await attachments.pin(`prompt:${key}`, sessionId, resolved.map((entry) => entry.attachmentId));
|
|
1298
|
+
},
|
|
1299
|
+
abandon: (key) => attachments.release(`prompt:${key}`)
|
|
1300
|
+
});
|
|
1301
|
+
},
|
|
1302
|
+
/** A new root from a root's conversation cut at a turn, or from a branch a rewind set aside (§12.7). */
|
|
1303
|
+
async "session.fork"(_connection, params) {
|
|
1304
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not fork conversations (capability session.fork is not listed)");
|
|
1305
|
+
return conversation.fork({ ...params, principal: principalOf(params) });
|
|
1306
|
+
},
|
|
1307
|
+
/** The root's conversation from before a turn on, same id; the later turns stay a recoverable branch, files untouched (§12.7). */
|
|
1308
|
+
async "session.rewind"(_connection, params) {
|
|
1309
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not rewind conversations (capability session.rewind is not listed)");
|
|
1310
|
+
return conversation.rewind(params);
|
|
1311
|
+
},
|
|
1312
|
+
/** Restarts a live root's native process on its own conversation at the idle barrier (§12.8). */
|
|
1313
|
+
async "session.reload"(_connection, params) {
|
|
1314
|
+
if (!conversation?.reloads) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not reload sessions (capability session.reload is not listed)");
|
|
1315
|
+
return conversation.reload(params);
|
|
1316
|
+
},
|
|
1317
|
+
/** Compacts a live root's context now or at its next turn boundary (t-0e56). */
|
|
1318
|
+
async "session.compact"(_connection, { sessionId }) {
|
|
1319
|
+
if (typeof sessionId !== "string" || !sessionId) throw new RpcError(-32602, "sessionId is required");
|
|
1320
|
+
if (!runtime.compact) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not compact sessions");
|
|
1321
|
+
try {
|
|
1322
|
+
return runtime.compact(sessionId);
|
|
1323
|
+
} catch (error) {
|
|
1324
|
+
throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error));
|
|
1325
|
+
}
|
|
744
1326
|
},
|
|
745
|
-
|
|
1327
|
+
/** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
|
|
1328
|
+
async "session.resumeCommand"(_connection, { sessionId }) {
|
|
1329
|
+
if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd has no resume command (capability session.resumeCommand is not listed)");
|
|
1330
|
+
return conversation.resumeCommand(sessionId);
|
|
1331
|
+
},
|
|
1332
|
+
async "session.interrupt"(_connection, { sessionId, turnId }) {
|
|
1333
|
+
if (turnId !== void 0) {
|
|
1334
|
+
if (typeof turnId !== "string" || !turnId) throw new RpcError(-32602, "turnId must be a nonempty string");
|
|
1335
|
+
if (!runtime.interruptTurn) throw new RpcError(ERROR.unavailable, "This runtime cannot interrupt a specific turn");
|
|
1336
|
+
return { interrupted: await runtime.interruptTurn(sessionId, turnId) };
|
|
1337
|
+
}
|
|
746
1338
|
await runtime.interrupt(sessionId);
|
|
747
1339
|
return {};
|
|
748
1340
|
},
|
|
749
|
-
|
|
750
|
-
|
|
1341
|
+
/**
|
|
1342
|
+
* A session's permissions mode while idle; with model, thinking or team, a live root's configuration
|
|
1343
|
+
* at the idle barrier through a restart on the same conversation (§12.9, capability session.configure.live).
|
|
1344
|
+
*/
|
|
1345
|
+
async "session.configure"(_connection, params) {
|
|
1346
|
+
const { sessionId, mode } = params;
|
|
1347
|
+
if (params.model !== void 0 || params.thinking !== void 0 || params.team !== void 0) {
|
|
1348
|
+
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" });
|
|
1349
|
+
return conversation.configure(params);
|
|
1350
|
+
}
|
|
1351
|
+
return { session: await runtime.configure(sessionId, { mode }, {
|
|
1352
|
+
onApplied: (accepted) => persistAcceptedSpec(sessionId, accepted, { mode: true })
|
|
1353
|
+
}) };
|
|
1354
|
+
},
|
|
1355
|
+
/** What a change of model, thinking, team or mode would run a live root with (§12.9). */
|
|
1356
|
+
async "session.configure.preview"(_connection, params) {
|
|
1357
|
+
if (!conversation?.configures) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not preview configurations (capability session.configure.live is not listed)");
|
|
1358
|
+
return { preview: await conversation.configurePreview(params) };
|
|
751
1359
|
},
|
|
752
1360
|
async "session.close"(_connection, { sessionId }) {
|
|
753
1361
|
await runtime.close(sessionId);
|
|
@@ -772,14 +1380,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
772
1380
|
async "session.archive"(_connection, { sessionId, archived = true }) {
|
|
773
1381
|
const record = rootRecord(sessionId);
|
|
774
1382
|
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 });
|
|
1383
|
+
const before = { archived: record.archived, attention: record.attention };
|
|
1384
|
+
Object.assign(record, { archived: archived === true ? true : void 0 }, archived === true ? { attention: void 0 } : {});
|
|
1385
|
+
if (archived === true) pendingAcks.delete(record.id);
|
|
777
1386
|
try {
|
|
778
1387
|
await store?.put(record);
|
|
779
1388
|
} catch (error) {
|
|
780
|
-
record
|
|
1389
|
+
Object.assign(record, before);
|
|
781
1390
|
throw persistenceFailed(`the archive state of ${record.id}`, error);
|
|
782
1391
|
}
|
|
1392
|
+
if (before.attention && !record.attention) tellAttention(record.id, void 0);
|
|
783
1393
|
return { session: summary(record.id) };
|
|
784
1394
|
},
|
|
785
1395
|
"session.get"(_connection, { sessionId }) {
|
|
@@ -792,18 +1402,137 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
792
1402
|
* a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
|
|
793
1403
|
*/
|
|
794
1404
|
"session.list"(_connection, { projectRoot, projectRoots, rootsOnly = false, includeClosed = false, includeArchived = false, limit, cursor, query } = {}) {
|
|
795
|
-
const
|
|
1405
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1406
|
+
const keyOf = (root) => {
|
|
1407
|
+
let key = cache.get(root);
|
|
1408
|
+
if (key === void 0) {
|
|
1409
|
+
key = projectKey(root);
|
|
1410
|
+
cache.set(root, key);
|
|
1411
|
+
}
|
|
1412
|
+
return key;
|
|
1413
|
+
};
|
|
1414
|
+
const wantedKey = projectRoot === void 0 ? void 0 : keyOf(projectRoot);
|
|
1415
|
+
const allowedKeys = Array.isArray(projectRoots) ? new Set(projectRoots.map(keyOf)) : void 0;
|
|
796
1416
|
const after = cursor === void 0 ? void 0 : listCursor.decode(cursor);
|
|
797
1417
|
const words = typeof query === "string" ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
|
|
798
|
-
const
|
|
799
|
-
const
|
|
1418
|
+
const live2 = runtime.list();
|
|
1419
|
+
const liveChildren = rootsOnly ? new Set(live2.filter((session) => !!session.parentId).map((session) => session.id)) : void 0;
|
|
1420
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1421
|
+
for (const session of live2) {
|
|
1422
|
+
if (!rootsOnly || !session.parentId) ids.add(session.id);
|
|
1423
|
+
}
|
|
1424
|
+
for (const [id, record] of records) {
|
|
1425
|
+
if (!rootsOnly) {
|
|
1426
|
+
ids.add(id);
|
|
1427
|
+
} else if (record.id === record.rootId && !record.session?.parentId && !liveChildren.has(id)) {
|
|
1428
|
+
ids.add(id);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
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) => wantedKey === void 0 || keyOf(session.projectRoot) === wantedKey).filter((session) => !allowedKeys || allowedKeys.has(keyOf(session.projectRoot))).filter((session) => !words.length || words.every((word) => `${session.title ?? ""}
|
|
800
1432
|
${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);
|
|
801
1433
|
if (limit === void 0 || sessions.length <= limit) return { sessions };
|
|
802
1434
|
const page = sessions.slice(0, limit);
|
|
803
1435
|
return { sessions: page, nextCursor: listCursor.encode(listCursor.key(page.at(-1))) };
|
|
1436
|
+
},
|
|
1437
|
+
/**
|
|
1438
|
+
* A scheduled continuation of a root session: alpd opens the turn itself
|
|
1439
|
+
* when the time comes, without a user message. The target is a live root session of
|
|
1440
|
+
* the project; a session that is closed when the job is due fails the job, and the
|
|
1441
|
+
* reason is kept.
|
|
1442
|
+
*/
|
|
1443
|
+
async "schedule.create"(_connection, { projectRoot, sessionId, dueAt, prompt, keepsSession } = {}) {
|
|
1444
|
+
if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
|
|
1445
|
+
if (typeof projectRoot !== "string" || typeof sessionId !== "string" || typeof dueAt !== "string" || typeof prompt !== "string") {
|
|
1446
|
+
throw new RpcError(RPC_ERROR.invalidParams, "projectRoot, sessionId, dueAt and prompt are required");
|
|
1447
|
+
}
|
|
1448
|
+
if (keepsSession !== void 0 && typeof keepsSession !== "boolean") throw new RpcError(RPC_ERROR.invalidParams, "keepsSession must be true or false");
|
|
1449
|
+
if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute path");
|
|
1450
|
+
const snapshot = runtime.snapshot(sessionId);
|
|
1451
|
+
if (!snapshot) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not open`);
|
|
1452
|
+
if (snapshot.parentId) throw new RpcError(RPC_ERROR.invalidParams, "A scheduled job continues a root session");
|
|
1453
|
+
if (projectKey(snapshot.projectRoot) !== projectKey(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, "That session does not belong to that project");
|
|
1454
|
+
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 });
|
|
1455
|
+
scheduler?.holdSession(sessionId);
|
|
1456
|
+
try {
|
|
1457
|
+
const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt, keepsSession });
|
|
1458
|
+
scheduler?.hold(job);
|
|
1459
|
+
return { job };
|
|
1460
|
+
} catch (error) {
|
|
1461
|
+
throw scheduleFailed(error);
|
|
1462
|
+
} finally {
|
|
1463
|
+
scheduler?.releaseSession(sessionId);
|
|
1464
|
+
}
|
|
1465
|
+
},
|
|
1466
|
+
/** The jobs of this project, oldest first by the time they are due. */
|
|
1467
|
+
async "schedule.list"(_connection, { projectRoot, status } = {}) {
|
|
1468
|
+
if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
|
|
1469
|
+
requestedProject(projectRoot);
|
|
1470
|
+
try {
|
|
1471
|
+
return { jobs: await schedules.list({ projectRoot, status }) };
|
|
1472
|
+
} catch (error) {
|
|
1473
|
+
throw scheduleFailed(error);
|
|
1474
|
+
}
|
|
1475
|
+
},
|
|
1476
|
+
/** One job, with what became of it. */
|
|
1477
|
+
async "schedule.get"(_connection, { id, projectRoot } = {}) {
|
|
1478
|
+
if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
|
|
1479
|
+
if (typeof id !== "string") throw new RpcError(RPC_ERROR.invalidParams, "id is required");
|
|
1480
|
+
requestedProject(projectRoot);
|
|
1481
|
+
const job = await storeJob(id, projectRoot);
|
|
1482
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1483
|
+
return { job };
|
|
1484
|
+
},
|
|
1485
|
+
/** A job that will not run: cancelled before its time. */
|
|
1486
|
+
async "schedule.cancel"(_connection, { id, projectRoot } = {}) {
|
|
1487
|
+
if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
|
|
1488
|
+
if (typeof id !== "string") throw new RpcError(RPC_ERROR.invalidParams, "id is required");
|
|
1489
|
+
requestedProject(projectRoot);
|
|
1490
|
+
const job = await storeJob(id, projectRoot);
|
|
1491
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1492
|
+
if (scheduler?.delivering(id)) throw new RpcError(ERROR.conflict, `Job ${id} is being delivered now`, { reason: "key_conflict" });
|
|
1493
|
+
try {
|
|
1494
|
+
const cancelled = await schedules.cancel(id, { projectRoot });
|
|
1495
|
+
scheduler?.release(cancelled);
|
|
1496
|
+
return { job: cancelled };
|
|
1497
|
+
} catch (error) {
|
|
1498
|
+
throw scheduleFailed(error);
|
|
1499
|
+
}
|
|
804
1500
|
}
|
|
805
1501
|
};
|
|
806
|
-
|
|
1502
|
+
const registryCall = async (run) => {
|
|
1503
|
+
if (!registry) throw new RpcError(ERROR.unavailable, "Registry needs ALP_HOME");
|
|
1504
|
+
try {
|
|
1505
|
+
return await run();
|
|
1506
|
+
} catch (e) {
|
|
1507
|
+
if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data);
|
|
1508
|
+
throw new RpcError(ERROR.failed, e instanceof Error ? e.message : String(e), { reason: "persistence_failed" });
|
|
1509
|
+
}
|
|
1510
|
+
};
|
|
1511
|
+
const registryList = async (kind, params = {}) => registryCall(async () => {
|
|
1512
|
+
const r = await registry.snapshot();
|
|
1513
|
+
const allowed = params.projectRoots;
|
|
1514
|
+
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);
|
|
1515
|
+
if (allowed !== void 0) {
|
|
1516
|
+
entries = (await Promise.all(entries.map(async (e) => {
|
|
1517
|
+
const directory = kind === "projects" ? e.root : e.directory;
|
|
1518
|
+
const canonical = await fsRealpath(directory).catch(() => void 0);
|
|
1519
|
+
return canonical && (!e.canonical || canonical === e.canonical) && allowed.includes(canonical) ? e : void 0;
|
|
1520
|
+
}))).filter(Boolean);
|
|
1521
|
+
}
|
|
1522
|
+
const offset = params.cursor === void 0 ? 0 : Number(params.cursor);
|
|
1523
|
+
if (!Number.isSafeInteger(offset) || offset < 0) throw new RpcError(-32602, "Invalid registry cursor");
|
|
1524
|
+
const limit = params.limit ?? 100;
|
|
1525
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new RpcError(-32602, "Invalid registry limit");
|
|
1526
|
+
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 };
|
|
1527
|
+
});
|
|
1528
|
+
const registryMutation = (method, p) => registryCall(async () => {
|
|
1529
|
+
if (!Number.isSafeInteger(p.ifRevision) || p.ifRevision < 0) throw new RpcError(-32602, "ifRevision is required");
|
|
1530
|
+
const { requestId, ifRevision, authorizedRoots, ...args } = p;
|
|
1531
|
+
const result = await registry.mutate(method, args, { requestId, ifRevision, allowedRoots: authorizedRoots });
|
|
1532
|
+
return result.workspace ? { ...result, workspace: await workspaceDescriptor(result.workspace) } : result;
|
|
1533
|
+
});
|
|
1534
|
+
runtime.bindSchedules?.(async (action, params) => handlers[`schedule.${action}`](void 0, params));
|
|
1535
|
+
for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (connection, params) => handler(params, { agent: connection.agent === true });
|
|
807
1536
|
Object.setPrototypeOf(handlers, null);
|
|
808
1537
|
const originalMethods = /* @__PURE__ */ new Set([...Object.keys(handlers), ...RPC_METHODS]);
|
|
809
1538
|
const reservedNamespaces = new Set([...originalMethods].map((method) => method.split(".")[0]));
|
|
@@ -850,7 +1579,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
850
1579
|
throw new RpcError(ERROR.failed, "alpd could not read the workspace file");
|
|
851
1580
|
}
|
|
852
1581
|
}
|
|
853
|
-
const capabilities = [CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts] : [], ...operations.capabilities];
|
|
1582
|
+
const capabilities = [...runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : [], CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.workspaceFilesBrowse, CAPABILITY.hostDirectories, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : [], ...schedules ? [CAPABILITY.schedule] : [], ...registry ? ["workspace.registry", CAPABILITY.workspaceGit] : [], CAPABILITY.workspaceGitFacts, ...worktrees ? ["workspace.worktree"] : [], ...attachments ? [CAPABILITY.attachments] : [], ...conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : [], ...conversation?.reloads ? [CAPABILITY.sessionReload] : [], ...conversation?.configures ? [CAPABILITY.sessionConfigureLive] : [], ...conversation ? [CAPABILITY.sessionResumeCommand] : [], ...modelCatalog ? [CAPABILITY.catalogLive] : [], ...operations.capabilities];
|
|
854
1583
|
function fits(response) {
|
|
855
1584
|
if (frameBytes(response) <= MAX_FRAME) return response;
|
|
856
1585
|
log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
|
|
@@ -893,7 +1622,10 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
893
1622
|
const issues2 = validateParams(method, params);
|
|
894
1623
|
if (issues2.length) throw invalidParams(issues2);
|
|
895
1624
|
connection.helloed = true;
|
|
896
|
-
|
|
1625
|
+
connection.agent = connection.agent === true || Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY);
|
|
1626
|
+
if (typeof params?.client?.name === "string") connection.client = params.client.name;
|
|
1627
|
+
const terminalLimits = await terminals?.advertised();
|
|
1628
|
+
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities: terminalLimits ? [...capabilities, CAPABILITY.terminal, CAPABILITY.terminalCapture, CAPABILITY.terminalWatch] : capabilities, ...attachments ? { attachmentLimits: attachments.limits } : {}, ...terminalLimits ? { terminalLimits } : {} } });
|
|
897
1629
|
return;
|
|
898
1630
|
}
|
|
899
1631
|
if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first", { reason: "hello_required" });
|
|
@@ -933,6 +1665,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
933
1665
|
}
|
|
934
1666
|
connections.delete(connection);
|
|
935
1667
|
watchers.delete(connection);
|
|
1668
|
+
terminals?.disconnect(connection);
|
|
936
1669
|
for (const root of [...connection.roots]) {
|
|
937
1670
|
detach(connection, root);
|
|
938
1671
|
void reap(root);
|
|
@@ -1068,6 +1801,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1068
1801
|
},
|
|
1069
1802
|
local() {
|
|
1070
1803
|
const events = /* @__PURE__ */ new Set();
|
|
1804
|
+
const notifications = /* @__PURE__ */ new Set();
|
|
1071
1805
|
const closes = /* @__PURE__ */ new Set();
|
|
1072
1806
|
const pending = /* @__PURE__ */ new Map();
|
|
1073
1807
|
let sequence = 0;
|
|
@@ -1082,6 +1816,10 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1082
1816
|
for (const listener of events) listener(message.params);
|
|
1083
1817
|
return;
|
|
1084
1818
|
}
|
|
1819
|
+
if (typeof message.method === "string" && message.id === void 0) {
|
|
1820
|
+
for (const listener of notifications) listener(message.method, message.params);
|
|
1821
|
+
return;
|
|
1822
|
+
}
|
|
1085
1823
|
const waiter = pending.get(message.id);
|
|
1086
1824
|
if (!waiter) return;
|
|
1087
1825
|
pending.delete(message.id);
|
|
@@ -1103,6 +1841,10 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1103
1841
|
events.add(listener);
|
|
1104
1842
|
return () => events.delete(listener);
|
|
1105
1843
|
},
|
|
1844
|
+
onNotification(listener) {
|
|
1845
|
+
notifications.add(listener);
|
|
1846
|
+
return () => notifications.delete(listener);
|
|
1847
|
+
},
|
|
1106
1848
|
onClose(listener) {
|
|
1107
1849
|
closes.add(listener);
|
|
1108
1850
|
return () => closes.delete(listener);
|
|
@@ -1135,8 +1877,12 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1135
1877
|
};
|
|
1136
1878
|
},
|
|
1137
1879
|
async close() {
|
|
1880
|
+
unsubscribeCatalog?.();
|
|
1138
1881
|
closing = true;
|
|
1139
1882
|
if (sweeper) clearInterval(sweeper);
|
|
1883
|
+
await attachments?.close();
|
|
1884
|
+
await terminals?.shutdown();
|
|
1885
|
+
await scheduler?.stop();
|
|
1140
1886
|
const stopped = new Promise((resolve) => server.close(() => resolve()));
|
|
1141
1887
|
for (const connection of connections) connection.socket?.destroy();
|
|
1142
1888
|
await stopped;
|