@anhlp/alp-daemon 0.0.1-beta.3 → 0.0.1-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/alpd.js +10350 -3346
- package/dist/attachments.d.ts +211 -0
- package/dist/attachments.js +819 -0
- package/dist/build-manifest.json +21 -1
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +672 -0
- package/dist/files.d.ts +13 -0
- package/dist/files.js +15 -0
- package/dist/git.d.ts +87 -0
- package/dist/git.js +1093 -0
- package/dist/gitignore.d.ts +5 -0
- package/dist/gitignore.js +7 -1
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +18 -1
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/main.js +9 -3
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +290 -0
- package/dist/schedules.d.ts +69 -0
- package/dist/schedules.js +244 -0
- package/dist/server.d.ts +11 -1
- package/dist/server.js +698 -76
- package/dist/store.d.ts +69 -1
- package/dist/store.js +109 -3
- package/dist/terminals.d.ts +157 -0
- package/dist/terminals.js +487 -0
- package/dist/worktrees.d.ts +41 -0
- package/dist/worktrees.js +246 -0
- package/package.json +64 -5
- package/src/attachments.ts +870 -0
- package/src/conversation.ts +837 -0
- package/src/files.ts +23 -2
- package/src/git.ts +1045 -0
- package/src/gitignore.ts +10 -0
- package/src/history.ts +118 -0
- package/src/index.ts +6 -0
- package/src/lifecycle.ts +283 -0
- package/src/main.ts +9 -3
- package/src/registry.ts +238 -0
- package/src/scheduler.ts +422 -0
- package/src/schedules.ts +294 -0
- package/src/server.ts +810 -86
- package/src/store.ts +115 -3
- package/src/terminals.ts +591 -0
- package/src/worktrees.ts +287 -0
package/src/server.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { realpath as fsRealpath } from 'node:fs/promises';
|
|
2
|
+
import { createRegistry, RegistryError } from './registry.js';
|
|
3
|
+
import { createWorkspaceWorktrees } from './worktrees.js';
|
|
4
|
+
import { HistoryError } from './history.js';
|
|
1
5
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
6
|
import { appendFile, chmod, mkdir, readFile, unlink, lstat, rename } from 'node:fs/promises';
|
|
3
7
|
import net from 'node:net';
|
|
@@ -10,10 +14,19 @@ import { validateParams } from '@anhlp/alp-protocol/contract';
|
|
|
10
14
|
export { ERROR } from '@anhlp/alp-protocol';
|
|
11
15
|
import { DEFAULT_MODEL, models, modes, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
|
|
12
16
|
import type { Receipt, SessionRecord, SessionStatus, Store, UnreadableReceipt } from './store.js';
|
|
13
|
-
import type { SessionSummary } from '@anhlp/alp-protocol/session';
|
|
17
|
+
import type { PromptContent, SessionSummary } from '@anhlp/alp-protocol/session';
|
|
18
|
+
import type { ScheduleJob, TurnAttention } from '@anhlp/alp-protocol/index';
|
|
14
19
|
import { RpcError } from './rpc-error.js';
|
|
15
20
|
import { createOperations, type OperationsOptions } from './operations.js';
|
|
16
21
|
import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from './files.js';
|
|
22
|
+
import { createGitReader } from './git.js';
|
|
23
|
+
import { createScheduleStore, projectKey } from './schedules.js';
|
|
24
|
+
import { createAttachmentStore, type AttachmentRuntime, type AttachmentStoreOptions, type Principal } from './attachments.js';
|
|
25
|
+
import type { RuntimeAttachment } from '@anhlp/alp-protocol/session';
|
|
26
|
+
import { clientMessageId as scheduleMessageId, createScheduler, SCHEDULE_TICK_MS, type ScheduleDelivery } from './scheduler.js';
|
|
27
|
+
import { createLifecycleJournal, LIFECYCLE_RETENTION_MS } from './lifecycle.js';
|
|
28
|
+
import { createConversation } from './conversation.js';
|
|
29
|
+
import { createTerminalService, type TerminalServiceOptions } from './terminals.js';
|
|
17
30
|
|
|
18
31
|
/**
|
|
19
32
|
* alpd's JSON-RPC surface over one shared runtime (plans/reference/ALPD.md §3, §6, §14).
|
|
@@ -56,6 +69,43 @@ function crashPoint(name: string) {
|
|
|
56
69
|
const persistenceFailed = (what: string, error: unknown) =>
|
|
57
70
|
new RpcError(ERROR.failed, `alpd could not record ${what}: ${error instanceof Error ? error.message : String(error)}`, { reason: 'persistence_failed' });
|
|
58
71
|
|
|
72
|
+
/** A job store's refusal as a protocol error: what it refused, and why. */
|
|
73
|
+
const scheduleFailed = (error: any) => {
|
|
74
|
+
if (error instanceof RpcError) return error;
|
|
75
|
+
switch (error?.code) {
|
|
76
|
+
case 'SCHEDULE_NOT_FOUND': return new RpcError(ERROR.notFound, error.message, { reason: 'not_found' });
|
|
77
|
+
case 'SCHEDULE_NOT_PENDING': return new RpcError(ERROR.conflict, error.message, { reason: 'task_state' });
|
|
78
|
+
case 'INVALID_SCHEDULE': return new RpcError(RPC_ERROR.invalidParams, error.message, { reason: 'invalid_params' });
|
|
79
|
+
}
|
|
80
|
+
return error;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The project of a request: an absolute path, or nothing. The three methods that read
|
|
85
|
+
* or change a job refuse a missing project the same way, so a client that names no
|
|
86
|
+
* project is told what is wrong, not shown the jobs of the host.
|
|
87
|
+
*/
|
|
88
|
+
const requestedProject = (projectRoot: unknown): string => {
|
|
89
|
+
if (typeof projectRoot !== 'string' || !projectRoot) throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot is required');
|
|
90
|
+
// A relative path would be read against the daemon's own directory, which is another
|
|
91
|
+
// project.
|
|
92
|
+
if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot must be an absolute path');
|
|
93
|
+
return projectRoot;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Who an attachment call acts for: the principal context a trusted gateway puts on its own
|
|
98
|
+
* connection (its credential id and grant epoch, and the canonical workspaces it may use now), or
|
|
99
|
+
* the local owner, as workspace.worktree does (§12.6, §16).
|
|
100
|
+
*/
|
|
101
|
+
function principalOf(params: { principalId?: unknown; principalEpoch?: unknown; authorizedRoots?: unknown }): Principal {
|
|
102
|
+
return {
|
|
103
|
+
id: typeof params.principalId === 'string' ? params.principalId : 'owner',
|
|
104
|
+
epoch: typeof params.principalEpoch === 'string' ? params.principalEpoch : 'owner',
|
|
105
|
+
...(Array.isArray(params.authorizedRoots) ? { roots: params.authorizedRoots.filter((root): root is string => typeof root === 'string') } : {}),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
59
109
|
/** A stable hash of JSON data, independent of key order (as Paseo's receipts). */
|
|
60
110
|
function digest(value: unknown) {
|
|
61
111
|
return createHash('sha256').update(JSON.stringify(value, (_key, candidate) =>
|
|
@@ -93,6 +143,17 @@ function titleFromPrompt(text: string): string | undefined {
|
|
|
93
143
|
return line ? [...line].slice(0, PROMPT_TITLE_CHARS).join('').trim() || undefined : undefined;
|
|
94
144
|
}
|
|
95
145
|
|
|
146
|
+
/**
|
|
147
|
+
* Whether a message is the user's own words, which alone may name a root: ALP's mail, briefs,
|
|
148
|
+
* resumes and scheduled jobs (`alp-` ids) never do. A runtime says who wrote it in `origin`;
|
|
149
|
+
* without it, only a message a client sent (its clientMessageId) counts, so a replayed message
|
|
150
|
+
* nobody can place does not.
|
|
151
|
+
*/
|
|
152
|
+
function fromUser(item: { origin?: string; clientMessageId?: string }) {
|
|
153
|
+
if (item.clientMessageId?.startsWith('alp-')) return false;
|
|
154
|
+
return item.origin !== undefined ? item.origin === 'user' : item.clientMessageId !== undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
96
157
|
/**
|
|
97
158
|
* session.list's order and its keyset cursor: roots before children, the latest `updatedAt`
|
|
98
159
|
* first, then by id, so a page continues after the last session it holds, as Paseo's history pages
|
|
@@ -137,7 +198,7 @@ export type DaemonServer = {
|
|
|
137
198
|
* shape so every viewer agrees; re-exported here to keep `@anhlp/alp-daemon/server`'s API. */
|
|
138
199
|
export type { SessionSummary };
|
|
139
200
|
|
|
140
|
-
export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates }: {
|
|
201
|
+
export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions }: {
|
|
141
202
|
runtime: AlpRuntime;
|
|
142
203
|
socketPath: string;
|
|
143
204
|
version: string;
|
|
@@ -154,6 +215,14 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
154
215
|
home?: OperationsOptions['home'];
|
|
155
216
|
/** ALP's built-in agents and teams, for the library and team methods. */
|
|
156
217
|
templates?: OperationsOptions['templates'];
|
|
218
|
+
/** How often the scheduler looks for jobs whose time has come; tests shorten it. */
|
|
219
|
+
scheduleTickMs?: number;
|
|
220
|
+
/** How long a job's delivery may take; tests shorten it. */
|
|
221
|
+
scheduleDeliveryTimeoutMs?: number;
|
|
222
|
+
/** Lower attachment limits (an operator's, never higher than ATTACHMENTS) and test hooks. */
|
|
223
|
+
attachmentOptions?: Partial<Pick<AttachmentStoreOptions, 'limits' | 'now' | 'io' | 'sweepMs'>>;
|
|
224
|
+
/** Lower terminal limits (never higher than TERMINAL or the operator's) and test hooks. */
|
|
225
|
+
terminalOptions?: Partial<Pick<TerminalServiceOptions, 'limits' | 'now' | 'spawn' | 'processes' | 'sweepMs' | 'killGraceMs' | 'maxBufferedBytes' | 'platform'>>;
|
|
157
226
|
}): DaemonServer {
|
|
158
227
|
const connections = new Set<Connection>();
|
|
159
228
|
/** Root of every live session. */
|
|
@@ -172,11 +241,162 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
172
241
|
/** Roots alpd reopens after a restart; they stay open until their recovery has started. */
|
|
173
242
|
const recovering = new Map<string, Promise<void>>();
|
|
174
243
|
const startedAt = new Date().toISOString();
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
244
|
+
/** The clock of this daemon: the job store and the scheduler share it. */
|
|
245
|
+
const clock = () => Date.now();
|
|
246
|
+
/**
|
|
247
|
+
* The scheduled continuations of this host; their own directory, beside the state.
|
|
248
|
+
* They need the prompt receipt (the store) to deliver a job at most once, so a
|
|
249
|
+
* daemon without a store serves no jobs at all.
|
|
250
|
+
*/
|
|
251
|
+
const schedules = home && store ? createScheduleStore(path.join(home, 'schedules'), { now: clock }) : undefined;
|
|
252
|
+
/**
|
|
253
|
+
* The job of that id in that project: the store keeps the project boundary, and a
|
|
254
|
+
* refusal of the store is answered like one of the daemon's own.
|
|
255
|
+
*/
|
|
256
|
+
const storeJob = async (id: string, projectRoot: string) => {
|
|
257
|
+
if (!schedules) return undefined;
|
|
258
|
+
try { return await schedules.get(id, { projectRoot }); }
|
|
259
|
+
catch (error) { throw scheduleFailed(error); }
|
|
260
|
+
};
|
|
261
|
+
/**
|
|
262
|
+
* Non-image attachments (§12.6): with a home and a store (prompt receipts pin their references),
|
|
263
|
+
* never on Windows (no O_NOFOLLOW, no POSIX modes: not a supported platform for them).
|
|
264
|
+
*/
|
|
265
|
+
const attachments = home && store && process.platform !== 'win32' ? createAttachmentStore({
|
|
266
|
+
root: path.join(home, 'state', 'attachments'),
|
|
267
|
+
sessionProject: sessionId => runtime.snapshot(sessionId)?.projectRoot ?? records.get(sessionId)?.session?.projectRoot,
|
|
268
|
+
crashPoint,
|
|
269
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
270
|
+
// A collected object's staged copy goes with it.
|
|
271
|
+
onDiscard: attachmentId => (runtime as AlpRuntime & AttachmentRuntime).dropAttachment?.(attachmentId),
|
|
272
|
+
...attachmentOptions,
|
|
273
|
+
}) : undefined;
|
|
274
|
+
// The runtime side of the seam (issue #121 branch J): a runtime that takes attachment parts reads them through this.
|
|
275
|
+
(runtime as AlpRuntime & AttachmentRuntime).bindAttachments?.(attachments?.reader);
|
|
276
|
+
/**
|
|
277
|
+
* Gates of roots whose conversation a lifecycle operation changes (a rewind): prompts, scheduled
|
|
278
|
+
* deliveries and reopens of the root wait until it is through (§12.7).
|
|
279
|
+
*/
|
|
280
|
+
const holds = new Map<string, { count: number; open: Promise<void>; release: () => void }>();
|
|
281
|
+
// Conservatively invalidate in-flight attach reads even when a lifecycle hold ends during I/O.
|
|
282
|
+
let holdRevision = 0;
|
|
283
|
+
function holdPrompts(root: string) {
|
|
284
|
+
holdRevision++;
|
|
285
|
+
let gate = holds.get(root);
|
|
286
|
+
if (!gate) {
|
|
287
|
+
let release!: () => void;
|
|
288
|
+
const open = new Promise<void>(resolve => { release = resolve; });
|
|
289
|
+
gate = { count: 0, open, release };
|
|
290
|
+
holds.set(root, gate);
|
|
291
|
+
}
|
|
292
|
+
gate.count++;
|
|
293
|
+
const held = gate;
|
|
294
|
+
let released = false;
|
|
295
|
+
return () => {
|
|
296
|
+
if (released) return;
|
|
297
|
+
released = true;
|
|
298
|
+
if (--held.count === 0) { if (holds.get(root) === held) holds.delete(root); held.release(); }
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
/** Prompt deliveries in flight per root: a rewind refuses while one is on its way. */
|
|
302
|
+
const promptsInFlight = new Map<string, number>();
|
|
303
|
+
const rootIdOf = (sessionId: string) => rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
304
|
+
/** Waits while the root's conversation is being changed, then counts a delivery in flight until `run` settles. */
|
|
305
|
+
async function gated<T>(sessionId: string, run: () => Promise<T>): Promise<T> {
|
|
306
|
+
const root = rootIdOf(sessionId);
|
|
307
|
+
while (holds.has(root)) await holds.get(root)!.open;
|
|
308
|
+
refuseFenced(root);
|
|
309
|
+
promptsInFlight.set(root, (promptsInFlight.get(root) ?? 0) + 1);
|
|
310
|
+
try { return await run(); }
|
|
311
|
+
finally {
|
|
312
|
+
const left = (promptsInFlight.get(root) ?? 1) - 1;
|
|
313
|
+
if (left > 0) promptsInFlight.set(root, left); else promptsInFlight.delete(root);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/** A root whose rewind is applied but not committed takes no prompt or reopen until that rewind is sent again. */
|
|
317
|
+
function fencedRoot(root: string): string | undefined { return conversation?.fenced(root); }
|
|
318
|
+
function refuseFenced(root: string) {
|
|
319
|
+
const requestId = fencedRoot(root);
|
|
320
|
+
if (requestId !== undefined) throw new RpcError(ERROR.conflict, `A rewind of this session is not finished; send session.rewind again with requestId ${requestId}`, { reason: 'session_busy' });
|
|
321
|
+
}
|
|
322
|
+
/** Forks and rewinds of Codex and Claude conversations (§12.7): with a store, through the lifecycle journal. */
|
|
323
|
+
const journal = store ? createLifecycleJournal(path.join(store.root, 'lifecycle')) : undefined;
|
|
324
|
+
const conversation: ReturnType<typeof createConversation> | undefined = store && journal ? createConversation({
|
|
325
|
+
runtime, store, journal, records, cursors, logs, treeLogLimit: TREE_LOG_LIMIT,
|
|
326
|
+
summary: id => summary(id), digest,
|
|
327
|
+
unsettled: (root): string | undefined => fencedRoot(root) ? 'a rewind of it is not finished; send that rewind again'
|
|
328
|
+
: recovering.has(root) ? 'it is being reopened after a restart'
|
|
329
|
+
: openingSessions.has(root) ? 'it is opening'
|
|
330
|
+
: promptsInFlight.get(root) ? 'a prompt is being delivered' : undefined,
|
|
331
|
+
holdPrompts,
|
|
332
|
+
broadcast: (root, envelope) => { for (const connection of attached.get(root) ?? []) deliver(connection, envelope); },
|
|
333
|
+
get registry() { return registry; },
|
|
334
|
+
get worktrees() { return worktrees; },
|
|
335
|
+
attachments,
|
|
336
|
+
crashPoint,
|
|
337
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
338
|
+
startedAt,
|
|
339
|
+
}) : undefined;
|
|
340
|
+
/** The daemon's own start-up; the scheduler waits for it before it delivers. */
|
|
341
|
+
let restored: Promise<unknown> = Promise.resolve();
|
|
342
|
+
/**
|
|
343
|
+
* The sessions the recovery is opening again, and the ones it could not open. A job
|
|
344
|
+
* that waits for such a session waits for it, and a session that could not be opened
|
|
345
|
+
* fails the job with the reason.
|
|
346
|
+
*/
|
|
347
|
+
const openingSessions = new Map<string, number>();
|
|
348
|
+
const recoveryErrors = new Map<string, string>();
|
|
349
|
+
/** A session is being opened again; two opens at once are counted, not overwritten. */
|
|
350
|
+
const markOpening = (sessionId: string) => openingSessions.set(sessionId, (openingSessions.get(sessionId) ?? 0) + 1);
|
|
351
|
+
/** The session is open again (or was never open): the next open is counted anew. */
|
|
352
|
+
const clearOpening = (sessionId: string) => {
|
|
353
|
+
const count = (openingSessions.get(sessionId) ?? 0) - 1;
|
|
354
|
+
if (count > 0) openingSessions.set(sessionId, count);
|
|
355
|
+
else openingSessions.delete(sessionId);
|
|
356
|
+
};
|
|
357
|
+
/**
|
|
358
|
+
* The reason a session could not be opened again belongs to the jobs that wait for
|
|
359
|
+
* that session: a reason no job needs is no reason at all, and the map of them must
|
|
360
|
+
* not grow with the number of sessions.
|
|
361
|
+
*/
|
|
362
|
+
function keepRecoveryError(sessionId: string, message: string) {
|
|
363
|
+
if (scheduler?.holds(sessionId)) recoveryErrors.set(sessionId, message);
|
|
364
|
+
}
|
|
365
|
+
/** The reason is dropped when the last job that needed it is through. */
|
|
366
|
+
function dropRecoveryError(sessionId: string) {
|
|
367
|
+
if (!scheduler?.holds(sessionId)) recoveryErrors.delete(sessionId);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* The tick that delivers the jobs whose time has come.
|
|
371
|
+
*/
|
|
372
|
+
const scheduler = schedules ? createScheduler({
|
|
373
|
+
store: schedules,
|
|
374
|
+
runtime,
|
|
375
|
+
deliver: deliverJob,
|
|
376
|
+
ready: () => restored,
|
|
377
|
+
session: sessionId => openingSessions.has(sessionId)
|
|
378
|
+
? { opening: true }
|
|
379
|
+
: recoveryErrors.has(sessionId)
|
|
380
|
+
? { error: { message: `The session this job continues could not be opened again: ${recoveryErrors.get(sessionId)}`, code: 'session_open_failed' } }
|
|
381
|
+
: undefined,
|
|
382
|
+
settled: sessionId => dropRecoveryError(sessionId),
|
|
383
|
+
stopping: () => closing,
|
|
384
|
+
now: clock,
|
|
385
|
+
...(scheduleDeliveryTimeoutMs === undefined ? {} : { deliveryTimeoutMs: scheduleDeliveryTimeoutMs }),
|
|
386
|
+
}) : undefined;
|
|
387
|
+
restored = store ? restore() : Promise.resolve();
|
|
388
|
+
|
|
389
|
+
const deliver = (connection: Connection, envelope: Envelope) => {
|
|
390
|
+
const message = { jsonrpc: '2.0', method: 'event', params: envelope };
|
|
391
|
+
// Stable events too large for transport still advance the replay position explicitly.
|
|
392
|
+
const bytes = frameBytes(message);
|
|
393
|
+
if (bytes > 512 * 1024 && envelope.cursor !== undefined) message.params = {
|
|
394
|
+
...envelope, event: { type: 'item', item: { kind: 'notice', id: `oversized:${envelope.cursor}`, level: 'warning', text: `History event ${envelope.cursor} is too large to display (${bytes} bytes).` } },
|
|
395
|
+
};
|
|
396
|
+
connection.send(message);
|
|
397
|
+
};
|
|
398
|
+
/** Connections that called question.watch, with the projectRoot they asked for and whether they want roots' turn ends and attention. */
|
|
399
|
+
const watchers = new Map<Connection, { projectRoot?: string; turns: boolean; attention: boolean }>();
|
|
180
400
|
|
|
181
401
|
/** The project of a tree, live or recorded. */
|
|
182
402
|
function projectOf(root: string) {
|
|
@@ -200,6 +420,40 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
200
420
|
}
|
|
201
421
|
}
|
|
202
422
|
|
|
423
|
+
/**
|
|
424
|
+
* Tells the connections watching attention that a root's changed: `attention` when set, none when
|
|
425
|
+
* cleared. Never kept: a client reads the current ones from question.watch (§12.2), so a change
|
|
426
|
+
* missed while it was away is not lost.
|
|
427
|
+
*/
|
|
428
|
+
function tellAttention(root: string, attention: TurnAttention | undefined) {
|
|
429
|
+
if (!watchers.size) return;
|
|
430
|
+
const project = projectOf(root);
|
|
431
|
+
const envelope: Envelope = { sessionId: root, epoch: `attention-${startedAt}`, seq: 0, ts: new Date().toISOString(), event: { type: 'attention', ...(attention ? { attention } : {}) } };
|
|
432
|
+
for (const [connection, watch] of watchers) {
|
|
433
|
+
if (!watch.attention) continue;
|
|
434
|
+
if (watch.projectRoot !== undefined && project !== watch.projectRoot) continue;
|
|
435
|
+
deliver(connection, envelope);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* The acknowledgement of each root whose write is on its way. Whatever else can change a root's
|
|
441
|
+
* attention (a turn of the root starting or ending, archiving) drops it, so a failed write brings
|
|
442
|
+
* the attention back only when nothing changed it meanwhile; it lives no longer than the write.
|
|
443
|
+
*/
|
|
444
|
+
const pendingAcks = new Map<string, object>();
|
|
445
|
+
|
|
446
|
+
/** The attention of the roots of `projectRoot` (every project when absent): archived roots never ask. */
|
|
447
|
+
function attentionOf(projectRoot?: string) {
|
|
448
|
+
const found: Array<{ sessionId: string; attention: TurnAttention }> = [];
|
|
449
|
+
for (const record of records.values()) {
|
|
450
|
+
if (record.id !== record.rootId || !record.attention || record.archived) continue;
|
|
451
|
+
if (projectRoot !== undefined && projectOf(record.id) !== projectRoot) continue;
|
|
452
|
+
found.push({ sessionId: record.id, attention: record.attention });
|
|
453
|
+
}
|
|
454
|
+
return found;
|
|
455
|
+
}
|
|
456
|
+
|
|
203
457
|
/** Records a change; the write is queued, and a failure is logged and counted in daemon.status. */
|
|
204
458
|
function save(record: SessionRecord & { activeTurnId?: string }, changes: Partial<SessionRecord & { activeTurnId?: string }> = {}) {
|
|
205
459
|
Object.assign(record, changes, { updatedAt: new Date().toISOString() });
|
|
@@ -238,15 +492,18 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
238
492
|
if (!record) return false;
|
|
239
493
|
if (event.type === 'session.updated') save(record, { session: { ...record.session, ...event.session, ...(event.session.parked ? {} : { parked: undefined }) } });
|
|
240
494
|
// Work on an archived session brings it back.
|
|
241
|
-
|
|
495
|
+
// A root's new turn ends the attention of its last one, as Paseo clears it then.
|
|
496
|
+
else if (event.type === 'turn.started') save(record, { status: 'running', activeTurnId: event.turnId, archived: undefined, ...(sessionId === root ? { attention: undefined } : {}) });
|
|
242
497
|
else if (event.type === 'turn.ended') save(record, { status: 'idle', activeTurnId: undefined,
|
|
498
|
+
// A root's turn that completed or failed asks every client for a look until one acknowledges it (Paseo's checkAndSetAttention).
|
|
499
|
+
...(sessionId === root ? { attention: turnAttention(event) } : {}),
|
|
243
500
|
...(record.session ? { session: { ...record.session, parked: event.state === 'failed' ? runtime.snapshot(sessionId)?.parked : undefined } } : {}),
|
|
244
501
|
...(event.state === 'failed' ? { lastError: { message: event.error?.message ?? 'Turn failed' } } : {}) });
|
|
245
502
|
// The latest usage, for a closed session's summary; written with the record's next change.
|
|
246
503
|
else if (event.type === 'usage' && record.session) record.session = { ...record.session, usage: event.usage };
|
|
247
504
|
else if (event.type === 'session.failed') save(record, { status: 'error', lastError: event.error });
|
|
248
505
|
else if (event.type === 'session.closed') save(record, { status: record.status === 'error' ? 'error' : 'closed', activeTurnId: undefined });
|
|
249
|
-
else if (event.type === 'item' && sessionId === root && !record.title && event.item.kind === 'user_message' &&
|
|
506
|
+
else if (event.type === 'item' && sessionId === root && !record.title && event.item.kind === 'user_message' && fromUser(event.item)) {
|
|
250
507
|
// The user's first message names an unnamed root, as Paseo names an agent (ALPD §15).
|
|
251
508
|
const title = titleFromPrompt(event.item.text);
|
|
252
509
|
if (title) { save(record, { title }); return true; }
|
|
@@ -254,6 +511,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
254
511
|
return false;
|
|
255
512
|
}
|
|
256
513
|
|
|
514
|
+
/** What a root's ended turn asks of the user: a look when it completed, attention when it failed, nothing when canceled. */
|
|
515
|
+
function turnAttention(event: Extract<AlpEvent, { type: 'turn.ended' }>): TurnAttention | undefined {
|
|
516
|
+
if (event.state === 'canceled') return undefined;
|
|
517
|
+
const message = event.error?.message?.trim();
|
|
518
|
+
return { reason: event.state === 'completed' ? 'finished' : 'error', at: new Date().toISOString(), turnId: event.turnId, ...(event.state === 'failed' && message ? { message: event.error!.message } : {}) };
|
|
519
|
+
}
|
|
520
|
+
|
|
257
521
|
/**
|
|
258
522
|
* Tells the viewers of a live root its name, as a `session.updated` kept in its timeline, so a
|
|
259
523
|
* viewer attached later replays it. Nothing is sent for a root that is not open.
|
|
@@ -286,7 +550,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
286
550
|
log.push(envelope);
|
|
287
551
|
if (log.length > TREE_LOG_LIMIT) log.splice(0, log.length - TREE_LOG_LIMIT);
|
|
288
552
|
logs.set(root, log);
|
|
553
|
+
const before = records.get(root)?.attention;
|
|
289
554
|
named = track(sessionId, root, event);
|
|
555
|
+
const after = records.get(root)?.attention;
|
|
556
|
+
// A root's turn starting or ending decides its attention, even when it was already none.
|
|
557
|
+
if (sessionId === root && (event.type === 'turn.started' || event.type === 'turn.ended')) pendingAcks.delete(root);
|
|
558
|
+
if (after !== before) tellAttention(root, after);
|
|
290
559
|
}
|
|
291
560
|
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
292
561
|
if (event.type === 'question' || event.type === 'question.resolved') tellWatchers(root, envelope);
|
|
@@ -302,24 +571,32 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
302
571
|
|
|
303
572
|
/**
|
|
304
573
|
* Loads records, settles sessions a crash or a stop left working, and prunes expired
|
|
305
|
-
* trees. Trees with assignments the runtime can continue,
|
|
306
|
-
* are reopened afterwards (ALPD §31).
|
|
574
|
+
* trees. Trees with assignments the runtime can continue, whose root was working, or
|
|
575
|
+
* whose root a scheduled job waits for, are reopened afterwards (ALPD §31).
|
|
307
576
|
*/
|
|
308
577
|
async function restore() {
|
|
309
578
|
await store!.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: true });
|
|
579
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS, { temporaries: true }).catch(error => recoveryLog.warn('could not prune the lifecycle journal', { code: 'ALPD_LIFECYCLE_PRUNE_FAILED', error }));
|
|
310
580
|
const loaded = await store!.list();
|
|
311
581
|
await reconcileReceipts(loaded);
|
|
312
582
|
const now = Date.now();
|
|
313
583
|
const ended = { code: 'daemon_restarted', message: 'alpd stopped while this session was working' };
|
|
314
584
|
const epoch = `restart-${startedAt}`;
|
|
315
585
|
const continuing = new Set(runtime.recoverable().map(entry => entry.assignmentId));
|
|
586
|
+
// The roots a job waits for: they are reopened, so the job finds its session.
|
|
587
|
+
// Every project of the host is read here: the daemon serves them all.
|
|
588
|
+
const pending = await schedules?.all({ status: 'pending' }) ?? [];
|
|
589
|
+
for (const job of pending) scheduler?.hold(job);
|
|
590
|
+
const scheduled = new Set(pending.map(job => job.sessionId));
|
|
316
591
|
const reopen: Array<{ record: SessionRecord; working: boolean }> = [];
|
|
317
592
|
const byRoot = trees(loaded);
|
|
318
593
|
const removed = await expire(byRoot, now);
|
|
319
594
|
for (const [root, tree] of byRoot) {
|
|
320
595
|
const head = tree.find(record => record.id === root);
|
|
321
596
|
if (removed.has(root)) continue;
|
|
322
|
-
|
|
597
|
+
// A root that was closed is not opened again for a job: a job continues a session
|
|
598
|
+
// that is alive, and a closed one fails with the reason.
|
|
599
|
+
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' });
|
|
323
600
|
if (tree.some(record => LIVE.includes(record.status))) seen(root, await store!.timeline(root));
|
|
324
601
|
for (const record of tree as Array<SessionRecord & { activeTurnId?: string }>) {
|
|
325
602
|
records.set(record.id, record);
|
|
@@ -343,12 +620,20 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
343
620
|
}
|
|
344
621
|
}
|
|
345
622
|
}
|
|
623
|
+
// Forks and rewinds a crash cut off: finished from their journal, or settled unknown, before any tree reopens.
|
|
624
|
+
if (conversation) await conversation.recover().catch(error => recoveryLog.error('could not recover lifecycle operations', { code: 'ALPD_LIFECYCLE_RECOVERY_FAILED', error }));
|
|
346
625
|
// Assignments whose tree cannot be reopened end now, and their tasks go back to open.
|
|
347
626
|
const reopened = new Set(reopen.map(entry => entry.record.id));
|
|
348
627
|
for (const rootId of new Set(runtime.recoverable().map(entry => entry.rootId))) {
|
|
349
628
|
if (!reopened.has(rootId)) await runtime.abandon(rootId, 'its root session cannot be reopened').catch(() => {});
|
|
350
629
|
}
|
|
351
|
-
for (const { record, working } of reopen)
|
|
630
|
+
for (const { record, working } of reopen) {
|
|
631
|
+
// A root whose rewind could not be finished stays closed: it would reopen on the old conversation.
|
|
632
|
+
if (fencedRoot(record.id)) { recoveryLog.warn(`${record.id} is not reopened: a rewind of it is not finished`, { code: 'ALPD_REWIND_FENCED', sessionId: record.id }); continue; }
|
|
633
|
+
// The session is opened again: a job that waits for it waits, it does not fail.
|
|
634
|
+
markOpening(record.id);
|
|
635
|
+
recovering.set(record.id, recoverTree(record, working, () => { clearOpening(record.id); }));
|
|
636
|
+
}
|
|
352
637
|
}
|
|
353
638
|
|
|
354
639
|
function trees(list: Iterable<SessionRecord>) {
|
|
@@ -375,21 +660,31 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
375
660
|
}
|
|
376
661
|
const continuing = new Set(runtime.recoverable().map(entry => entry.rootId));
|
|
377
662
|
for (const [root, tree] of byRoot) {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
663
|
+
const remove = async () => {
|
|
664
|
+
if (!tree.some(record => record.id === root)) return;
|
|
665
|
+
if (tree.some(record => LIVE.includes(record.status))) return;
|
|
666
|
+
if (now - Math.max(...tree.map(record => Date.parse(record.updatedAt) || now)) <= RETENTION_MS) return;
|
|
667
|
+
if (tree.some(record => now - (receiptWritten.get(record.id) ?? 0) <= RECEIPT_RETENTION_MS)) return;
|
|
668
|
+
if (continuing.has(root) || rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
669
|
+
// A tree a job waits for stays: the job is to continue that very session.
|
|
670
|
+
if (scheduler?.holds(root)) return;
|
|
671
|
+
const ids = tree.map(record => record.id);
|
|
672
|
+
// A tree restored from a backup counts from its restore: its files were written then.
|
|
673
|
+
if (now - await store!.writtenAt(ids) <= RETENTION_MS) return;
|
|
674
|
+
if (rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
675
|
+
if (await conversation?.retainsFork(root)) return;
|
|
676
|
+
// Forgotten before the files go, so a resume arriving meanwhile finds nothing to reopen.
|
|
677
|
+
for (const id of ids) records.delete(id);
|
|
678
|
+
cursors.delete(root);
|
|
679
|
+
await store!.remove(root, ids);
|
|
680
|
+
// The history is gone: what its prompts pinned is released (kept releasedGraceMs more).
|
|
681
|
+
await attachments?.releaseSessions(ids).catch(error => recoveryLog.warn('could not release the attachments of removed sessions', { code: 'ALPD_ATTACHMENT_RELEASE_FAILED', error }));
|
|
682
|
+
if (runLogDir) await unlink(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`)).catch(() => {});
|
|
683
|
+
removed.add(root);
|
|
684
|
+
};
|
|
685
|
+
// A source cannot start a native fork between the dependency check and deletion.
|
|
686
|
+
if (conversation) await conversation.lifecycle.serial(root, remove);
|
|
687
|
+
else await remove();
|
|
393
688
|
}
|
|
394
689
|
if (removed.size) recoveryLog.info(`retention removed ${removed.size} session tree${removed.size > 1 ? 's' : ''} unused for ${RETENTION_MS / 86_400_000} days`, { code: 'ALP_RETENTION_REMOVED', trees: removed.size });
|
|
395
690
|
return removed;
|
|
@@ -401,6 +696,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
401
696
|
try {
|
|
402
697
|
await restored;
|
|
403
698
|
await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
|
|
699
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS);
|
|
404
700
|
await expire(trees(records.values()));
|
|
405
701
|
} catch (error) {
|
|
406
702
|
recoveryLog.warn('retention sweep failed', { code: 'ALP_RETENTION_FAILED', error });
|
|
@@ -409,6 +705,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
409
705
|
const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : undefined;
|
|
410
706
|
sweeper?.unref();
|
|
411
707
|
|
|
708
|
+
/**
|
|
709
|
+
* The scheduler's tick. It runs as long as alpd runs, so a job that comes due is
|
|
710
|
+
* delivered even when nobody is watching: the tick is not the runtime's watchdog,
|
|
711
|
+
* which stops as soon as no assignment is left.
|
|
712
|
+
*/
|
|
713
|
+
scheduler?.start(scheduleTickMs);
|
|
714
|
+
|
|
412
715
|
/**
|
|
413
716
|
* Completes receipts a crash left pending when the tree's timeline shows how the runtime
|
|
414
717
|
* answered; the rest stay pending, so their prompt answers outcome_unknown and is never
|
|
@@ -437,20 +740,31 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
437
740
|
}
|
|
438
741
|
|
|
439
742
|
/** Reopens a root nobody watches yet and continues what it and its assignments were doing. */
|
|
440
|
-
async function recoverTree(record: SessionRecord, working: boolean) {
|
|
743
|
+
async function recoverTree(record: SessionRecord, working: boolean, opened?: () => void) {
|
|
441
744
|
const session = record.session!;
|
|
745
|
+
// The open of this session is counted once: the flag is cleared when the open is
|
|
746
|
+
// over, whether it succeeded or not, and a second open of the same session keeps
|
|
747
|
+
// its own count.
|
|
748
|
+
let openedOnce = false;
|
|
749
|
+
const open = () => { if (openedOnce) return; openedOnce = true; opened?.(); };
|
|
442
750
|
try {
|
|
751
|
+
if (worktrees && record.spec?.cwd) await worktrees.assertAvailable(record.spec.cwd);
|
|
443
752
|
const stored = await treeLog(record.id);
|
|
444
753
|
seen(record.id, stored);
|
|
445
754
|
logs.set(record.id, [...stored]);
|
|
446
755
|
await runtime.open(record.id, {
|
|
447
756
|
...record.spec!,
|
|
448
757
|
persist: true,
|
|
449
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
|
|
758
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...(record.base ? { base: record.base } : {}) },
|
|
450
759
|
}, { history: 'skip', delegation: record.delegation ?? true });
|
|
760
|
+
// The session is open again: a job that waits for it may be delivered.
|
|
761
|
+
open();
|
|
451
762
|
const outcomes = await runtime.recover(record.id, { continueRoot: working, parkedRoot: session.parked });
|
|
452
763
|
recoveryLog.info(`recovered ${record.id}: ${outcomes.map(outcome => `${outcome.agent} ${outcome.outcome}`).join(', ') || 'root'}`, { event: 'recovered', sessionId: record.id, rootId: record.rootId });
|
|
453
764
|
} catch (error: any) {
|
|
765
|
+
// The session is not open: a job that waits for it fails with the reason.
|
|
766
|
+
open();
|
|
767
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
454
768
|
recoveryLog.error(`could not recover ${record.id}`, { code: 'ALP_RECOVERY_FAILED', sessionId: record.id, rootId: record.rootId, error });
|
|
455
769
|
await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {});
|
|
456
770
|
} finally {
|
|
@@ -466,7 +780,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
466
780
|
* the first delivery did, with other content a conflict; a receipt left pending by a
|
|
467
781
|
* crash, or a delivery the provider may or may not have received, is outcome_unknown.
|
|
468
782
|
*/
|
|
469
|
-
function deliverOnce(sessionId: string, clientMessageId: string, fingerprint: string, send: () => Promise<void
|
|
783
|
+
function deliverOnce(sessionId: string, clientMessageId: string, fingerprint: string, send: () => Promise<void>, { requireReceipt = false, prepare, abandon }: {
|
|
784
|
+
requireReceipt?: boolean;
|
|
785
|
+
/** Before the pending receipt, once no receipt answers: refusals here record nothing; attachments are pinned here. */
|
|
786
|
+
prepare?: (key: string) => Promise<void>;
|
|
787
|
+
/** The prompt certainly did not reach the runtime: what prepare pinned may go. */
|
|
788
|
+
abandon?: (key: string) => Promise<void>;
|
|
789
|
+
} = {}) {
|
|
470
790
|
const key = digest(['prompt', sessionId, clientMessageId]);
|
|
471
791
|
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' });
|
|
472
792
|
const answer = (receipt: Receipt, extra: object = {}) => ({ outcome: receipt.outcome ?? 'accepted', ...(receipt.error ? { error: receipt.error } : {}), ...extra });
|
|
@@ -482,12 +802,20 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
482
802
|
if (existing.state === 'pending' || existing.outcome === 'unknown') throw unknown();
|
|
483
803
|
return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
|
|
484
804
|
}
|
|
805
|
+
// Scheduler replays fail closed when a prior attempt's receipt was pruned,
|
|
806
|
+
// lost or never committed. Absence cannot prove that nothing was sent.
|
|
807
|
+
if (requireReceipt) throw unknown();
|
|
485
808
|
const receipt = (state: Receipt['state'], changes: Partial<Receipt> = {}): Receipt => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: new Date().toISOString() });
|
|
486
809
|
live(sessionId);
|
|
810
|
+
// Attachments are pinned before anything is sent: a crash from here on keeps them.
|
|
811
|
+
await prepare?.(key);
|
|
487
812
|
crashPoint('prompt.before-receipt');
|
|
488
813
|
// Nothing is sent unless the pending receipt is on disk: a crash from here on answers outcome_unknown.
|
|
489
814
|
try { await store!.putReceipt(key, receipt('pending')); }
|
|
490
|
-
catch (error) {
|
|
815
|
+
catch (error) {
|
|
816
|
+
await abandon?.(key).catch(() => {});
|
|
817
|
+
throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error);
|
|
818
|
+
}
|
|
491
819
|
crashPoint('prompt.after-receipt');
|
|
492
820
|
// The runtime reports how the provider answered as an event, before prompt() resolves.
|
|
493
821
|
let reply: { outcome: 'accepted' | 'failed' | 'unknown'; error?: { message: string; code?: string } } = { outcome: 'accepted' };
|
|
@@ -501,6 +829,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
501
829
|
} catch (error) {
|
|
502
830
|
// The runtime refused it before reaching the provider (the session closed meanwhile): not sent.
|
|
503
831
|
await store!.removeReceipt(key).catch(() => {});
|
|
832
|
+
await abandon?.(key).catch(() => {});
|
|
504
833
|
throw error;
|
|
505
834
|
} finally {
|
|
506
835
|
stop();
|
|
@@ -520,12 +849,26 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
520
849
|
return answer(done, { durable });
|
|
521
850
|
};
|
|
522
851
|
const previous = delivering.get(key) ?? Promise.resolve();
|
|
523
|
-
const result = previous.catch(() => {}).then(attempt);
|
|
852
|
+
const result = previous.catch(() => {}).then(() => gated(sessionId, attempt));
|
|
524
853
|
delivering.set(key, result);
|
|
525
854
|
void result.finally(() => { if (delivering.get(key) === result) delivering.delete(key); }).catch(() => {});
|
|
526
855
|
return result;
|
|
527
856
|
}
|
|
528
857
|
|
|
858
|
+
/**
|
|
859
|
+
* The delivery of a scheduled job: the prompt path a client uses, with a
|
|
860
|
+
* clientMessageId of the job's own. The receipt of that message is what keeps a job
|
|
861
|
+
* from running twice: a retry after a crash reads the receipt instead of sending.
|
|
862
|
+
*/
|
|
863
|
+
async function deliverJob(job: ScheduleJob, content: PromptContent, messageId: string, send: AlpRuntime['prompt'] = (id, input) => runtime.prompt(id, input)): Promise<ScheduleDelivery> {
|
|
864
|
+
// The id is the job's own, so it is the same in every attempt of this job.
|
|
865
|
+
const clientMessageId = messageId || scheduleMessageId(job);
|
|
866
|
+
return deliverOnce(job.sessionId, clientMessageId, digest({ delivery: 'auto', content }), async () => {
|
|
867
|
+
live(job.sessionId);
|
|
868
|
+
await send(job.sessionId, { clientMessageId, delivery: 'auto', content });
|
|
869
|
+
}, { requireReceipt: job.attempts > 1 });
|
|
870
|
+
}
|
|
871
|
+
|
|
529
872
|
/**
|
|
530
873
|
* Waits for an opened root's record and timeline (its native thread) to be written, so a
|
|
531
874
|
* crash after the answer can still resume it (ALPD §66); `durable: false` when they were not.
|
|
@@ -537,13 +880,16 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
537
880
|
|
|
538
881
|
function forget(root: string) {
|
|
539
882
|
if (runtime.snapshot(root)) return;
|
|
540
|
-
for (const [id, candidate] of rootOf) if (candidate === root) rootOf.delete(id);
|
|
883
|
+
for (const [id, candidate] of rootOf) if (candidate === root) { rootOf.delete(id); recoveryErrors.delete(id); }
|
|
884
|
+
recoveryErrors.delete(root);
|
|
541
885
|
logs.delete(root);
|
|
542
886
|
}
|
|
543
887
|
|
|
544
888
|
/** Closes an idle root that no client watches. */
|
|
545
889
|
async function reap(root: string) {
|
|
546
890
|
if (closing || attached.get(root)?.size || recovering.has(root)) return false;
|
|
891
|
+
// A root a job waits for stays open: the job is to continue that very session.
|
|
892
|
+
if (scheduler?.holds(root)) return false;
|
|
547
893
|
const session = runtime.snapshot(root);
|
|
548
894
|
if (!session || session.busy) return false;
|
|
549
895
|
await runtime.close(root).catch(() => {});
|
|
@@ -569,7 +915,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
569
915
|
const session = live ?? record?.session;
|
|
570
916
|
if (!session) return undefined;
|
|
571
917
|
const status: SessionStatus = live ? (live.activeTurnId ? 'running' : 'idle') : record?.status === 'error' ? 'error' : 'closed';
|
|
572
|
-
return { ...session, ...(live ? {} : { busy: false, activeTurnId: undefined }), status, title: record?.title, ...(record?.archived ? { archived: true } : {}), lastError: record?.lastError, createdAt: record?.createdAt, updatedAt: record?.updatedAt };
|
|
918
|
+
return { ...session, ...(live ? {} : { busy: false, activeTurnId: undefined }), 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) : {}) };
|
|
573
919
|
}
|
|
574
920
|
|
|
575
921
|
/** The record of a root the user acts on. */
|
|
@@ -649,27 +995,84 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
649
995
|
if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, 'This session cannot be resumed');
|
|
650
996
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
651
997
|
if (agent !== undefined && agent !== session.agent) throw new RpcError(ERROR.failed, 'Cannot resume a session as a different ALP agent');
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
998
|
+
// The session is opened again from the first moment: a job that waits for it waits
|
|
999
|
+
// for the open, it does not fail with 'the session is closed'.
|
|
1000
|
+
markOpening(record.id);
|
|
1001
|
+
// The reason of an earlier failure is not true while the session opens again.
|
|
1002
|
+
recoveryErrors.delete(record.id);
|
|
1003
|
+
let applied = false;
|
|
656
1004
|
try {
|
|
1005
|
+
if (worktrees) await worktrees.assertAvailable(record.spec.cwd);
|
|
1006
|
+
const stored = await treeLog(record.id);
|
|
1007
|
+
seen(record.id, stored);
|
|
1008
|
+
logs.set(record.id, [...stored]);
|
|
1009
|
+
attach(connection, record.id);
|
|
657
1010
|
const opened = await runtime.open(record.id, {
|
|
658
1011
|
...record.spec,
|
|
659
1012
|
...(spec.mode !== undefined ? { mode: spec.mode } : {}),
|
|
660
1013
|
...(spec.thinking !== undefined ? { thinking: spec.thinking } : {}),
|
|
661
1014
|
persist: true,
|
|
662
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
|
|
1015
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...(record.base ? { base: record.base } : {}) },
|
|
663
1016
|
}, { history: stored.length ? 'skip' : history, delegation: record.delegation ?? delegation });
|
|
1017
|
+
applied = true;
|
|
1018
|
+
await persistAcceptedSpec(record.id, opened, { mode: spec.mode !== undefined, thinking: spec.thinking !== undefined });
|
|
664
1019
|
if (history === 'replay') replayHistory(connection, record.id, stored);
|
|
665
1020
|
return opened;
|
|
666
|
-
} catch (error) {
|
|
1021
|
+
} catch (error: any) {
|
|
1022
|
+
// A durable-write failure does not undo a successful open or abandon its viewer.
|
|
1023
|
+
if (applied) throw error;
|
|
667
1024
|
detach(connection, record.id);
|
|
1025
|
+
// The session could not be opened: a job that waits for it says why.
|
|
1026
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
668
1027
|
throw error;
|
|
1028
|
+
} finally {
|
|
1029
|
+
clearOpening(record.id);
|
|
669
1030
|
}
|
|
670
1031
|
}
|
|
671
1032
|
|
|
1033
|
+
/** Causal successful apply/open only: never infer requested configuration from later events. */
|
|
1034
|
+
async function persistAcceptedSpec(id: string, accepted: SessionSnapshot, fields: { mode?: boolean; thinking?: boolean }) {
|
|
1035
|
+
const record = records.get(id);
|
|
1036
|
+
if (!record?.spec || (!fields.mode && !fields.thinking)) return;
|
|
1037
|
+
record.spec = {
|
|
1038
|
+
...record.spec,
|
|
1039
|
+
...(fields.mode ? { mode: accepted.mode } : {}),
|
|
1040
|
+
...(fields.thinking ? { thinking: accepted.thinking } : {}),
|
|
1041
|
+
};
|
|
1042
|
+
record.updatedAt = new Date().toISOString();
|
|
1043
|
+
try { await store?.put(record); }
|
|
1044
|
+
catch (error) { throw persistenceFailed(`the configuration of ${id}; the runtime already applied it`, error); }
|
|
1045
|
+
}
|
|
1046
|
+
|
|
672
1047
|
/** Projects, tasks, library and settings (docs/protocol/alp-json-rpc-v1.md §15); a team save syncs the projects sessions ran in. */
|
|
1048
|
+
const registry = home ? createRegistry(home) : undefined;
|
|
1049
|
+
const worktrees = home && registry && process.platform !== 'win32' ? createWorkspaceWorktrees(home, registry, async (directory, run) => {
|
|
1050
|
+
if (!runtime.withWorkspaceMutation) throw new RegistryError(1005, 'Runtime cannot prove safe worktree removal', { reason: 'guard_unavailable' });
|
|
1051
|
+
try { return await runtime.withWorkspaceMutation(directory, run); } catch (error: any) { if (error?.data?.reason) throw new RegistryError(1004, 'Workspace is in use or has retained assignment results', error.data); throw error; }
|
|
1052
|
+
}, async directory => { if (!runtime.registerWorkspace) throw new RegistryError(1005, 'Runtime cannot register safe workspace ownership', { reason: 'guard_unavailable' }); await runtime.registerWorkspace(directory); }) : undefined;
|
|
1053
|
+
const workspaceDescriptor = async (w: any) => worktrees ? worktrees.describe(w) : w;
|
|
1054
|
+
// workspace.git.status and workspace.git.diff (§12.5): read-only, by registry workspaceId.
|
|
1055
|
+
const gitReader = registry ? createGitReader({ registry, log: (message, fields) => log.warn(message, { code: 'ALPD_GIT_READ_FAILED', ...fields }) }) : undefined;
|
|
1056
|
+
// Terminals (§12.10): a real PTY shell as the daemon's account, only while the host opted in
|
|
1057
|
+
// (<ALP_HOME>/terminal.json); bound to the caller's principal and the workspace's directory.
|
|
1058
|
+
const terminals = home && registry ? createTerminalService({
|
|
1059
|
+
home,
|
|
1060
|
+
resolveWorkspace: workspaceId => registry.resolve(workspaceId),
|
|
1061
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
1062
|
+
...terminalOptions,
|
|
1063
|
+
}) : undefined;
|
|
1064
|
+
const terminalCall = <T>(run: (service: NonNullable<typeof terminals>) => Promise<T>) => {
|
|
1065
|
+
if (!terminals) throw new RpcError(ERROR.unavailable, 'This alpd has no home: it serves no terminals', { reason: 'terminal_unsupported' });
|
|
1066
|
+
return run(terminals);
|
|
1067
|
+
};
|
|
1068
|
+
const attachmentCall = <T>(run: (store: NonNullable<typeof attachments>) => Promise<T>) => {
|
|
1069
|
+
if (!attachments) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not store attachments (capability attachments is not listed)');
|
|
1070
|
+
return run(attachments);
|
|
1071
|
+
};
|
|
1072
|
+
const gitCall = <T>(run: (reader: NonNullable<typeof gitReader>) => Promise<T>) => {
|
|
1073
|
+
if (!gitReader) throw new RpcError(ERROR.unavailable, 'Registry needs ALP_HOME');
|
|
1074
|
+
return run(gitReader);
|
|
1075
|
+
};
|
|
673
1076
|
const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap(record => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
|
|
674
1077
|
const extensionOwners = new Map<string, Connection>();
|
|
675
1078
|
const handlers: Record<string, (connection: Connection, params: any) => Promise<unknown> | unknown> = {
|
|
@@ -732,12 +1135,44 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
732
1135
|
* The questions waiting now; from then on this connection is told of `question` and
|
|
733
1136
|
* `question.resolved` in every tree, or those of `projectRoot`, attached or not. Calling it
|
|
734
1137
|
* again replaces the filter; it lasts as long as the connection (ALPD §15). With `turns`, also
|
|
735
|
-
* of `turn.ended` of every root
|
|
1138
|
+
* of `turn.ended` of every root; with `attention`, also of each root's attention, now and as it
|
|
1139
|
+
* changes (docs/protocol/alp-json-rpc-v1.md §12.2).
|
|
736
1140
|
*/
|
|
737
|
-
'question.watch'(connection, { projectRoot, turns } = {}) {
|
|
1141
|
+
'question.watch'(connection, { projectRoot, turns, attention } = {}) {
|
|
738
1142
|
// No await between registering and listing: an event either is in the list or follows it.
|
|
739
|
-
watchers.set(connection, { projectRoot, turns: turns === true });
|
|
740
|
-
return {
|
|
1143
|
+
watchers.set(connection, { projectRoot, turns: turns === true, attention: attention === true });
|
|
1144
|
+
return {
|
|
1145
|
+
questions: runtime.questions().filter(question => projectRoot === undefined || projectOf(question.rootId) === projectRoot),
|
|
1146
|
+
...(attention === true ? { attention: attentionOf(projectRoot) } : {}),
|
|
1147
|
+
};
|
|
1148
|
+
},
|
|
1149
|
+
|
|
1150
|
+
/**
|
|
1151
|
+
* Acknowledges a root's attention for every client, as Paseo's clear_agent_attention; with `at`,
|
|
1152
|
+
* only the attention set then, so a look at an older turn end never hides a newer one (§12.2).
|
|
1153
|
+
*/
|
|
1154
|
+
async 'session.attention.clear'(_connection, { sessionId, at }) {
|
|
1155
|
+
if (typeof sessionId !== 'string') throw new RpcError(-32602, 'sessionId is required');
|
|
1156
|
+
if (at !== undefined && typeof at !== 'string') throw new RpcError(-32602, 'at must be a string');
|
|
1157
|
+
const record = records.get(sessionId);
|
|
1158
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
|
|
1159
|
+
const attention = record.attention;
|
|
1160
|
+
if (!attention || (at !== undefined && attention.at !== at)) return { cleared: false };
|
|
1161
|
+
// Not a change of the session: its place in session.list stays.
|
|
1162
|
+
const ack = {};
|
|
1163
|
+
pendingAcks.set(record.id, ack);
|
|
1164
|
+
record.attention = undefined;
|
|
1165
|
+
try { await store?.put(record); }
|
|
1166
|
+
catch (error) {
|
|
1167
|
+
// Brought back only if nothing decided its attention meanwhile: a turn that started since, or
|
|
1168
|
+
// archiving, ended it anyway. Nobody was told of the clear, so nobody is told of this.
|
|
1169
|
+
if (pendingAcks.get(record.id) === ack && !record.attention) record.attention = attention;
|
|
1170
|
+
throw persistenceFailed(`the attention of ${record.id}`, error);
|
|
1171
|
+
}
|
|
1172
|
+
finally { if (pendingAcks.get(record.id) === ack) pendingAcks.delete(record.id); }
|
|
1173
|
+
// What holds now: a turn that ended while the write was on its way set a newer one, which stays.
|
|
1174
|
+
tellAttention(record.id, record.attention);
|
|
1175
|
+
return { cleared: true };
|
|
741
1176
|
},
|
|
742
1177
|
|
|
743
1178
|
/**
|
|
@@ -815,20 +1250,84 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
815
1250
|
return {};
|
|
816
1251
|
},
|
|
817
1252
|
|
|
1253
|
+
'registry.owner': (_c, params) => registryCall(async () => {
|
|
1254
|
+
const result = params.operation ? await registry!.mutate(params.operation, params.args ?? {}, { requestId: params.requestId, ifRevision: params.ifRevision }) : undefined;
|
|
1255
|
+
const { receipts: _receipts, ...metadata } = await registry!.snapshot();
|
|
1256
|
+
return { ...(result ? { result } : {}), registry: metadata };
|
|
1257
|
+
}),
|
|
1258
|
+
'registry.worktree': (_c, p) => registryCall(() => worktrees!.grants(p)),
|
|
1259
|
+
'workspace.worktree.options': (_c, p) => registryCall(async () => { const w = (await registry!.snapshot()).workspaces.find(w => w.id === p.workspaceId); if (!w) throw new RegistryError(1001, 'No workspace', { reason: 'not_found' }); const grants = await worktrees!.grants(p); return { mappingIds: grants.mappings.filter(m => m.source === (w.canonical ?? w.directory)).map(m => m.id) }; }),
|
|
1260
|
+
'workspace.worktree.create': (_c, p) => registryCall(async () => { const result = await worktrees!.mutate('create', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
|
|
1261
|
+
'workspace.worktree.remove': (_c, p) => registryCall(async () => { const result = await worktrees!.mutate('remove', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
|
|
1262
|
+
'workspace.git.status': (_c, p) => gitCall(reader => reader.status(p.workspaceId)),
|
|
1263
|
+
'workspace.git.diff': (_c, p) => gitCall(reader => reader.diff({ workspaceId: p.workspaceId, compare: p.compare, path: p.path, cursor: p.cursor })),
|
|
1264
|
+
'project.list': (_c, p) => registryList('projects', p),
|
|
1265
|
+
'workspace.list': (_c, p) => registryList('workspaces', p),
|
|
1266
|
+
'workspace.get': (_c, p) => registryCall(async () => {
|
|
1267
|
+
await registry!.resolve(p.workspaceId, undefined, true);
|
|
1268
|
+
const r = await registry!.snapshot();
|
|
1269
|
+
return { workspace: { ...await workspaceDescriptor(r.workspaces.find(w => w.id === p.workspaceId)), revision: r.revision }, revision: r.revision };
|
|
1270
|
+
}),
|
|
1271
|
+
'project.register': (_c, p) => registryMutation('project.register', p),
|
|
1272
|
+
'project.remove': (_c, p) => registryMutation('project.remove', p),
|
|
1273
|
+
'workspace.update': (_c, p) => registryMutation('workspace.update', p),
|
|
818
1274
|
'catalog.get': () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
|
|
819
|
-
|
|
820
|
-
|
|
1275
|
+
// attachment.* (§12.6): each call acts for its principal context; without the store (no home or
|
|
1276
|
+
// store, or Windows) alpd does not serve them, as for any method it does not know.
|
|
1277
|
+
// terminal.* (§12.10): each call acts for its principal context; input, resize and the stream
|
|
1278
|
+
// belong to the connection that attached the terminal.
|
|
1279
|
+
'terminal.create': (_c, p) => terminalCall(service => service.create(principalOf(p), p)),
|
|
1280
|
+
'terminal.list': (_c, p) => terminalCall(service => service.list(principalOf(p), p)),
|
|
1281
|
+
'terminal.attach': (c, p) => terminalCall(service => service.attach(principalOf(p), c, p)),
|
|
1282
|
+
'terminal.input': (c, p) => terminalCall(service => service.input(principalOf(p), c, p)),
|
|
1283
|
+
'terminal.resize': (c, p) => terminalCall(service => service.resize(principalOf(p), c, p)),
|
|
1284
|
+
'terminal.close': (_c, p) => terminalCall(service => service.close(principalOf(p), p)),
|
|
1285
|
+
'terminal.revoke': (_c, p) => terminalCall(service => service.revoke(p.principalId)),
|
|
1286
|
+
'attachment.begin': (_c, p) => attachmentCall(store => store.begin(principalOf(p), p)),
|
|
1287
|
+
'attachment.chunk': (_c, p) => attachmentCall(store => store.chunk(principalOf(p), p)),
|
|
1288
|
+
'attachment.commit': (_c, p) => attachmentCall(store => store.commit(principalOf(p), p)),
|
|
1289
|
+
'attachment.abort': (_c, p) => attachmentCall(store => store.abort(principalOf(p), p)),
|
|
1290
|
+
'attachment.get': (_c, p) => attachmentCall(store => store.get(principalOf(p), p)),
|
|
1291
|
+
'attachment.delete': (_c, p) => attachmentCall(store => store.remove(principalOf(p), p)),
|
|
1292
|
+
|
|
1293
|
+
async 'session.create'(connection, { sessionId, workspaceId, spec, history = 'skip', delegation = true, resume: resuming = false }) {
|
|
1294
|
+
if (workspaceId !== undefined) {
|
|
1295
|
+
if (!registry || typeof workspaceId !== 'string') throw new RpcError(-32602, 'Invalid workspaceId');
|
|
1296
|
+
try { spec = { ...spec, cwd: await registry.resolve(workspaceId, spec?.cwd) }; } catch (e) { if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data); throw e; }
|
|
1297
|
+
const placements = (await registryCall(() => registry!.snapshot())).sessions;
|
|
1298
|
+
const prior = Object.hasOwn(placements, sessionId) ? placements[sessionId] : undefined;
|
|
1299
|
+
if (prior && prior !== workspaceId) throw new RpcError(ERROR.conflict, 'Session belongs to another workspace', { reason: 'workspace_mismatch' });
|
|
1300
|
+
}
|
|
821
1301
|
if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
|
|
1302
|
+
if (worktrees) await registryCall(() => worktrees.assertAvailable(spec.cwd));
|
|
822
1303
|
if (sessionId !== undefined && (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, 'Invalid session id');
|
|
823
1304
|
if (history !== 'replay' && history !== 'skip') throw new RpcError(-32602, 'history must be replay or skip');
|
|
824
1305
|
const id = sessionId ?? `ses_${randomBytes(8).toString('hex')}`;
|
|
825
1306
|
// A root alpd is reopening after a restart: attach once it is open, rather than open it twice.
|
|
826
1307
|
await recovering.get(id);
|
|
1308
|
+
// A root whose conversation is being rewound opens once the rewind is through, on its new conversation.
|
|
1309
|
+
while (holds.has(id)) await holds.get(id)!.open;
|
|
1310
|
+
refuseFenced(id);
|
|
1311
|
+
let reservedWorkspaceId: string | undefined;
|
|
1312
|
+
const reserve = async () => {
|
|
1313
|
+
if (!registry) return;
|
|
1314
|
+
const directory = runtime.snapshot(id)?.projectRoot ?? records.get(id)?.session?.projectRoot ?? records.get(id)?.spec?.cwd ?? spec.cwd;
|
|
1315
|
+
if (workspaceId) await registryCall(() => registry!.resolve(workspaceId, directory));
|
|
1316
|
+
if (Object.hasOwn((await registry.snapshot()).sessions, id)) return;
|
|
1317
|
+
if (workspaceId) await registryCall(() => registry!.mutate('placement.assign', { sessionId: id, workspaceId }, { requestId: `reserve:${randomBytes(12).toString('hex')}` }));
|
|
1318
|
+
else await registryCall(() => registry!.mutate('placement.prepare', { sessions: [{ id, projectRoot: directory }] }, { requestId: `prepare:${randomBytes(12).toString('hex')}` }));
|
|
1319
|
+
reservedWorkspaceId = (await registry.snapshot()).sessions[id];
|
|
1320
|
+
};
|
|
1321
|
+
const rollback = async () => {
|
|
1322
|
+
if (!registry || !reservedWorkspaceId) return;
|
|
1323
|
+
await registryCall(() => registry!.mutate('placement.remove', { sessionId: id, workspaceId: reservedWorkspaceId }, { requestId: `rollback:${randomBytes(12).toString('hex')}` }));
|
|
1324
|
+
};
|
|
827
1325
|
const existing = runtime.snapshot(id);
|
|
828
1326
|
if (existing) {
|
|
829
1327
|
// Reopening a root that kept working after its viewer left: attach to it.
|
|
830
1328
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
831
1329
|
if (existing.parentId || (agent !== undefined && agent !== existing.agent)) throw new RpcError(ERROR.failed, 'Session is already open');
|
|
1330
|
+
await reserve();
|
|
832
1331
|
attach(connection, id);
|
|
833
1332
|
announce(connection, id, history);
|
|
834
1333
|
return { session: existing, attached: true };
|
|
@@ -836,8 +1335,11 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
836
1335
|
const record = records.get(id);
|
|
837
1336
|
if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
|
|
838
1337
|
if (record) {
|
|
839
|
-
|
|
840
|
-
|
|
1338
|
+
await reserve();
|
|
1339
|
+
try {
|
|
1340
|
+
const session = await resume(connection, record, spec, history, delegation);
|
|
1341
|
+
return { session, attached: false, resumed: true, ...await persisted(id) };
|
|
1342
|
+
} catch (error) { if (!runtime.snapshot(id)) await rollback(); throw error; }
|
|
841
1343
|
}
|
|
842
1344
|
const { restore: _restore, ...kept } = spec;
|
|
843
1345
|
const now = new Date().toISOString();
|
|
@@ -849,14 +1351,16 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
849
1351
|
if (records.get(id) === created) records.delete(id);
|
|
850
1352
|
throw persistenceFailed(`session ${id}; it was not started`, error);
|
|
851
1353
|
}
|
|
852
|
-
attach(connection, id);
|
|
853
1354
|
try {
|
|
1355
|
+
await reserve();
|
|
1356
|
+
attach(connection, id);
|
|
854
1357
|
const session = await runtime.open(id, spec, { history, delegation });
|
|
855
1358
|
return { session, attached: false, ...await persisted(id) };
|
|
856
1359
|
} catch (error) {
|
|
857
1360
|
detach(connection, id);
|
|
858
1361
|
records.delete(id);
|
|
859
1362
|
await store?.remove(id, [id]);
|
|
1363
|
+
await rollback();
|
|
860
1364
|
throw error;
|
|
861
1365
|
}
|
|
862
1366
|
},
|
|
@@ -872,32 +1376,62 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
872
1376
|
* events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
|
|
873
1377
|
* with the whole timeline. The replay and the live events that follow are in cursor order.
|
|
874
1378
|
*/
|
|
875
|
-
async 'session.
|
|
876
|
-
|
|
877
|
-
|
|
1379
|
+
async 'session.history'(_connection, { sessionId, before, limit, maxBytes }) {
|
|
1380
|
+
known(sessionId);
|
|
1381
|
+
if (!store) throw new RpcError(1005, 'Durable history unavailable');
|
|
878
1382
|
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
879
|
-
|
|
880
|
-
if (
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
1383
|
+
try { return await store.history(root, sessionId, { before, limit, maxBytes }); }
|
|
1384
|
+
catch (error) { if (error instanceof HistoryError) throw new RpcError(error.reason === 'stale_cursor' ? 1004 : -32602, error.message, { reason: error.reason }); throw error; }
|
|
1385
|
+
},
|
|
1386
|
+
|
|
1387
|
+
async 'session.attach'(connection, { sessionId, replay = true, after, generation }) {
|
|
1388
|
+
if (after !== undefined && (!Number.isSafeInteger(after) || after < 0)) throw new RpcError(-32602, 'after must be a cursor');
|
|
1389
|
+
known(sessionId);
|
|
1390
|
+
const root = rootIdOf(sessionId);
|
|
1391
|
+
for (;;) {
|
|
1392
|
+
// A rewind reserves its marker cursor before publishing it. Wait through afterRewind,
|
|
1393
|
+
// including if it began while a history read awaited, so replay owns every cursor <= tip.
|
|
1394
|
+
while (holds.has(root)) await holds.get(root)!.open;
|
|
1395
|
+
refuseFenced(root);
|
|
1396
|
+
const revision = holdRevision;
|
|
1397
|
+
const found = known(sessionId);
|
|
1398
|
+
let stored: Envelope[] = [];
|
|
1399
|
+
if (replay || (store && !cursors.has(root))) {
|
|
1400
|
+
// The in-memory log keeps a live tree's latest events only; older ones come from the store.
|
|
1401
|
+
const memory = logs.get(root);
|
|
1402
|
+
const covered = !!memory?.length && (memory[0].cursor ?? 1) <= (after ?? 0) + 1;
|
|
1403
|
+
if (!covered) stored = store ? await store.timeline(root) : memory ?? [];
|
|
1404
|
+
}
|
|
1405
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1406
|
+
if (generation !== undefined) {
|
|
1407
|
+
const checkpoint = await store?.history(root, sessionId, { limit: 1 });
|
|
1408
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1409
|
+
if (checkpoint?.generation !== generation) throw new RpcError(1004, 'History generation changed', { reason: 'stale_cursor' });
|
|
1410
|
+
}
|
|
1411
|
+
// From here to the return nothing awaits, so no live event slips between replay and attach.
|
|
1412
|
+
const live = logs.get(root) ?? [];
|
|
1413
|
+
const tip = Math.max(cursors.get(root) ?? 0, stored.at(-1)?.cursor ?? 0, live.at(-1)?.cursor ?? 0);
|
|
1414
|
+
if (generation !== undefined && replay) {
|
|
1415
|
+
const covered = Math.max(after ?? 0, stored.at(-1)?.cursor ?? 0);
|
|
1416
|
+
const next = live.find(envelope => (envelope.cursor ?? 0) > covered)?.cursor;
|
|
1417
|
+
if ((next !== undefined && next > covered + 1) || (next === undefined && tip > covered)) {
|
|
1418
|
+
throw new RpcError(1005, 'History advanced beyond replay coverage; retry attach', { reason: 'history_gap' });
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
// Without a store the in-memory log keeps only the latest events: a cursor before them cannot continue either.
|
|
1422
|
+
const first = replay ? [...stored, ...live].find(envelope => envelope.cursor !== undefined)?.cursor : undefined;
|
|
1423
|
+
// A cursor in history a rewind set aside starts over too: what the client holds after it is not this conversation.
|
|
1424
|
+
const reset = after !== undefined && (after > tip || (replay && after < tip && (first === undefined || first > after + 1)) || !!conversation?.discarded(records.get(root), after));
|
|
1425
|
+
const from = reset ? 0 : after ?? 0;
|
|
1426
|
+
attach(connection, root);
|
|
1427
|
+
if (replay) {
|
|
1428
|
+
let last = from;
|
|
1429
|
+
for (const envelope of stored) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
|
|
1430
|
+
for (const envelope of live) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
|
|
1431
|
+
}
|
|
1432
|
+
announceQuestions(connection, root);
|
|
1433
|
+
return { session: root === found.id ? found : summary(root), cursor: tip, ...(reset ? { reset: true } : {}) };
|
|
898
1434
|
}
|
|
899
|
-
announceQuestions(connection, root);
|
|
900
|
-
return { session: root === found.id ? found : summary(root), cursor: tip, ...(reset ? { reset: true } : {}) };
|
|
901
1435
|
},
|
|
902
1436
|
|
|
903
1437
|
async 'session.release'(connection, { sessionId }) {
|
|
@@ -906,7 +1440,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
906
1440
|
return { closed: await reap(root) };
|
|
907
1441
|
},
|
|
908
1442
|
|
|
909
|
-
async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content }) {
|
|
1443
|
+
async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content, ...context }) {
|
|
910
1444
|
if (typeof clientMessageId !== 'string' || !Array.isArray(content)) throw new RpcError(-32602, 'clientMessageId and content are required');
|
|
911
1445
|
if (delivery !== 'auto' && delivery !== 'steer') throw new RpcError(-32602, 'delivery must be auto or steer');
|
|
912
1446
|
// Images are inline only (the schema refuses a path or URL); here their number and decoded size.
|
|
@@ -919,25 +1453,90 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
919
1453
|
if (bytes > PROMPT_IMAGES.maxBytes) throw new RpcError(-32602, `An image in a prompt is at most ${PROMPT_IMAGES.maxBytes} bytes`);
|
|
920
1454
|
if (total > PROMPT_IMAGES.maxTotalBytes) throw new RpcError(-32602, `The images of a prompt are at most ${PROMPT_IMAGES.maxTotalBytes} bytes together`);
|
|
921
1455
|
}
|
|
1456
|
+
// Attachments (§12.6): resolved for this principal, project and session, in order. The runtime
|
|
1457
|
+
// gets their descriptors (ids, names, digests), never a path; the fingerprint their digests.
|
|
1458
|
+
const attached = content.filter((part: { type?: string }) => part?.type === 'attachment');
|
|
1459
|
+
let resolved: RuntimeAttachment[] = [];
|
|
1460
|
+
if (attached.length) {
|
|
1461
|
+
if (!attachments || !store) throw new RpcError(ERROR.unavailable, 'This alpd does not store attachments', { reason: 'attachment_unsupported' });
|
|
1462
|
+
resolved = await attachments.resolve(principalOf(context), sessionId, attached.map((part: { attachmentId?: unknown }) => part.attachmentId));
|
|
1463
|
+
}
|
|
1464
|
+
let index = 0;
|
|
1465
|
+
const delivered: PromptContent = attached.length ? content.map((part: { type?: string }) => part?.type === 'attachment' ? resolved[index++] : part) : content;
|
|
1466
|
+
const fingerprinted = attached.length ? content.map((part: any) => part?.type === 'attachment' ? { type: 'attachment', attachmentId: part.attachmentId, sha256: resolved.find(entry => entry.attachmentId === part.attachmentId)!.sha256 } : part) : content;
|
|
922
1467
|
const send = async () => {
|
|
923
1468
|
// Failures of an open session arrive as prompt.failed events; an unknown session has no watcher.
|
|
924
1469
|
live(sessionId);
|
|
925
|
-
await runtime.prompt(sessionId, { clientMessageId, delivery, content });
|
|
1470
|
+
await runtime.prompt(sessionId, { clientMessageId, delivery, content: delivered });
|
|
926
1471
|
};
|
|
927
1472
|
if (!store) {
|
|
928
|
-
await send
|
|
1473
|
+
await gated(sessionId, send);
|
|
929
1474
|
return {};
|
|
930
1475
|
}
|
|
931
|
-
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
1476
|
+
if (!attached.length) return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
1477
|
+
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content: fingerprinted }), send, {
|
|
1478
|
+
prepare: async key => {
|
|
1479
|
+
// Never dropped, never turned into a path: a runtime that cannot read them refuses the prompt here.
|
|
1480
|
+
if (!(runtime as AlpRuntime & AttachmentRuntime).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' });
|
|
1481
|
+
await attachments!.pin(`prompt:${key}`, sessionId, resolved.map(entry => entry.attachmentId));
|
|
1482
|
+
},
|
|
1483
|
+
abandon: key => attachments!.release(`prompt:${key}`),
|
|
1484
|
+
});
|
|
1485
|
+
},
|
|
1486
|
+
|
|
1487
|
+
/** A new root from a root's conversation cut at a turn, or from a branch a rewind set aside (§12.7). */
|
|
1488
|
+
async 'session.fork'(_connection, params) {
|
|
1489
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not fork conversations (capability session.fork is not listed)');
|
|
1490
|
+
return conversation.fork({ ...params, principal: principalOf(params) });
|
|
1491
|
+
},
|
|
1492
|
+
|
|
1493
|
+
/** The root's conversation from before a turn on, same id; the later turns stay a recoverable branch, files untouched (§12.7). */
|
|
1494
|
+
async 'session.rewind'(_connection, params) {
|
|
1495
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not rewind conversations (capability session.rewind is not listed)');
|
|
1496
|
+
return conversation.rewind(params);
|
|
1497
|
+
},
|
|
1498
|
+
|
|
1499
|
+
/** Restarts a live root's native process on its own conversation at the idle barrier (§12.8). */
|
|
1500
|
+
async 'session.reload'(_connection, params) {
|
|
1501
|
+
if (!conversation?.reloads) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not reload sessions (capability session.reload is not listed)');
|
|
1502
|
+
return conversation.reload(params);
|
|
1503
|
+
},
|
|
1504
|
+
|
|
1505
|
+
/** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
|
|
1506
|
+
async 'session.resumeCommand'(_connection, { sessionId }) {
|
|
1507
|
+
if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd has no resume command (capability session.resumeCommand is not listed)');
|
|
1508
|
+
return conversation.resumeCommand(sessionId);
|
|
932
1509
|
},
|
|
933
1510
|
|
|
934
|
-
async 'session.interrupt'(_connection, { sessionId }) {
|
|
1511
|
+
async 'session.interrupt'(_connection, { sessionId, turnId }) {
|
|
1512
|
+
if (turnId !== undefined) {
|
|
1513
|
+
if (typeof turnId !== 'string' || !turnId) throw new RpcError(-32602, 'turnId must be a nonempty string');
|
|
1514
|
+
if (!runtime.interruptTurn) throw new RpcError(ERROR.unavailable, 'This runtime cannot interrupt a specific turn');
|
|
1515
|
+
return { interrupted: await runtime.interruptTurn(sessionId, turnId) };
|
|
1516
|
+
}
|
|
935
1517
|
await runtime.interrupt(sessionId);
|
|
936
1518
|
return {};
|
|
937
1519
|
},
|
|
938
1520
|
|
|
939
|
-
|
|
940
|
-
|
|
1521
|
+
/**
|
|
1522
|
+
* A session's permissions mode while idle; with model, thinking or team, a live root's configuration
|
|
1523
|
+
* at the idle barrier through a restart on the same conversation (§12.9, capability session.configure.live).
|
|
1524
|
+
*/
|
|
1525
|
+
async 'session.configure'(_connection, params) {
|
|
1526
|
+
const { sessionId, mode } = params;
|
|
1527
|
+
if (params.model !== undefined || params.thinking !== undefined || params.team !== undefined) {
|
|
1528
|
+
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' });
|
|
1529
|
+
return conversation.configure(params);
|
|
1530
|
+
}
|
|
1531
|
+
return { session: await runtime.configure(sessionId, { mode }, {
|
|
1532
|
+
onApplied: accepted => persistAcceptedSpec(sessionId, accepted, { mode: true }),
|
|
1533
|
+
}) };
|
|
1534
|
+
},
|
|
1535
|
+
|
|
1536
|
+
/** What a change of model, thinking, team or mode would run a live root with (§12.9). */
|
|
1537
|
+
async 'session.configure.preview'(_connection, params) {
|
|
1538
|
+
if (!conversation?.configures) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not preview configurations (capability session.configure.live is not listed)');
|
|
1539
|
+
return { preview: await conversation.configurePreview(params) };
|
|
941
1540
|
},
|
|
942
1541
|
|
|
943
1542
|
async 'session.close'(_connection, { sessionId }) {
|
|
@@ -962,10 +1561,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
962
1561
|
async 'session.archive'(_connection, { sessionId, archived = true }) {
|
|
963
1562
|
const record = rootRecord(sessionId);
|
|
964
1563
|
if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
|
|
965
|
-
const before = record.archived;
|
|
966
|
-
|
|
1564
|
+
const before = { archived: record.archived, attention: record.attention };
|
|
1565
|
+
// An archived root never asks for attention, nor does an acknowledgement on its way bring one back.
|
|
1566
|
+
Object.assign(record, { archived: archived === true ? true : undefined }, archived === true ? { attention: undefined } : {});
|
|
1567
|
+
if (archived === true) pendingAcks.delete(record.id);
|
|
967
1568
|
try { await store?.put(record); }
|
|
968
|
-
catch (error) { record
|
|
1569
|
+
catch (error) { Object.assign(record, before); throw persistenceFailed(`the archive state of ${record.id}`, error); }
|
|
1570
|
+
if (before.attention && !record.attention) tellAttention(record.id, undefined);
|
|
969
1571
|
return { session: summary(record.id) };
|
|
970
1572
|
},
|
|
971
1573
|
|
|
@@ -997,7 +1599,113 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
997
1599
|
const page = sessions.slice(0, limit);
|
|
998
1600
|
return { sessions: page, nextCursor: listCursor.encode(listCursor.key(page.at(-1)!)) };
|
|
999
1601
|
},
|
|
1602
|
+
|
|
1603
|
+
/**
|
|
1604
|
+
* A scheduled continuation of a root session: alpd opens the turn itself
|
|
1605
|
+
* when the time comes, without a user message. The target is a live root session of
|
|
1606
|
+
* the project; a session that is closed when the job is due fails the job, and the
|
|
1607
|
+
* reason is kept.
|
|
1608
|
+
*/
|
|
1609
|
+
async 'schedule.create'(_connection, { projectRoot, sessionId, dueAt, prompt } = {}) {
|
|
1610
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1611
|
+
if (typeof projectRoot !== 'string' || typeof sessionId !== 'string' || typeof dueAt !== 'string' || typeof prompt !== 'string') {
|
|
1612
|
+
throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot, sessionId, dueAt and prompt are required');
|
|
1613
|
+
}
|
|
1614
|
+
if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot must be an absolute path');
|
|
1615
|
+
const snapshot = runtime.snapshot(sessionId);
|
|
1616
|
+
if (!snapshot) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not open`);
|
|
1617
|
+
if (snapshot.parentId) throw new RpcError(RPC_ERROR.invalidParams, 'A scheduled job continues a root session');
|
|
1618
|
+
// The project is compared as a path, not as a spelling: a client that names the
|
|
1619
|
+
// same directory with a trailing slash means the same project.
|
|
1620
|
+
if (projectKey(snapshot.projectRoot) !== projectKey(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'That session does not belong to that project');
|
|
1621
|
+
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 });
|
|
1622
|
+
// The session waits for the job before the job is written, so it is not closed
|
|
1623
|
+
// in between; the job's own hold takes over once it exists.
|
|
1624
|
+
scheduler?.holdSession(sessionId);
|
|
1625
|
+
try {
|
|
1626
|
+
const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt });
|
|
1627
|
+
scheduler?.hold(job);
|
|
1628
|
+
return { job };
|
|
1629
|
+
} catch (error) {
|
|
1630
|
+
throw scheduleFailed(error);
|
|
1631
|
+
} finally {
|
|
1632
|
+
scheduler?.releaseSession(sessionId);
|
|
1633
|
+
}
|
|
1634
|
+
},
|
|
1635
|
+
|
|
1636
|
+
/** The jobs of this project, oldest first by the time they are due. */
|
|
1637
|
+
async 'schedule.list'(_connection, { projectRoot, status } = {}) {
|
|
1638
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1639
|
+
// The jobs of every project live in one directory: the project is the boundary.
|
|
1640
|
+
requestedProject(projectRoot);
|
|
1641
|
+
try {
|
|
1642
|
+
return { jobs: await schedules.list({ projectRoot, status }) };
|
|
1643
|
+
} catch (error) {
|
|
1644
|
+
throw scheduleFailed(error);
|
|
1645
|
+
}
|
|
1646
|
+
},
|
|
1647
|
+
|
|
1648
|
+
/** One job, with what became of it. */
|
|
1649
|
+
async 'schedule.get'(_connection, { id, projectRoot } = {}) {
|
|
1650
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1651
|
+
if (typeof id !== 'string') throw new RpcError(RPC_ERROR.invalidParams, 'id is required');
|
|
1652
|
+
requestedProject(projectRoot);
|
|
1653
|
+
// The store keeps the project boundary itself: a job of another project is not
|
|
1654
|
+
// there for this one, whatever the caller asked for.
|
|
1655
|
+
const job = await storeJob(id, projectRoot);
|
|
1656
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1657
|
+
return { job };
|
|
1658
|
+
},
|
|
1659
|
+
|
|
1660
|
+
/** A job that will not run: cancelled before its time. */
|
|
1661
|
+
async 'schedule.cancel'(_connection, { id, projectRoot } = {}) {
|
|
1662
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1663
|
+
if (typeof id !== 'string') throw new RpcError(RPC_ERROR.invalidParams, 'id is required');
|
|
1664
|
+
requestedProject(projectRoot);
|
|
1665
|
+
const job = await storeJob(id, projectRoot);
|
|
1666
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1667
|
+
// A job that is being delivered now is not cancelled: the delivery is under way.
|
|
1668
|
+
if (scheduler?.delivering(id)) throw new RpcError(ERROR.conflict, `Job ${id} is being delivered now`, { reason: 'key_conflict' });
|
|
1669
|
+
try {
|
|
1670
|
+
const cancelled = await schedules.cancel(id, { projectRoot });
|
|
1671
|
+
scheduler?.release(cancelled);
|
|
1672
|
+
return { job: cancelled };
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
throw scheduleFailed(error);
|
|
1675
|
+
}
|
|
1676
|
+
},
|
|
1000
1677
|
};
|
|
1678
|
+
const registryCall = async (run: () => Promise<any>) => {
|
|
1679
|
+
if (!registry) throw new RpcError(ERROR.unavailable, 'Registry needs ALP_HOME');
|
|
1680
|
+
try { return await run(); } catch (e) {
|
|
1681
|
+
if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data);
|
|
1682
|
+
throw new RpcError(ERROR.failed, e instanceof Error ? e.message : String(e), { reason: 'persistence_failed' });
|
|
1683
|
+
}
|
|
1684
|
+
};
|
|
1685
|
+
const registryList = async (kind: 'projects' | 'workspaces', params: any = {}) => registryCall(async () => {
|
|
1686
|
+
const r = await registry!.snapshot();
|
|
1687
|
+
const allowed = params.projectRoots;
|
|
1688
|
+
let entries: any[] = r[kind].filter((e: any) => kind === 'projects' ? params.includeRemoved || !e.removedAt : params.includeArchived || (!e.archivedAt && !r.projects.find(p => p.id === e.projectId)?.removedAt));
|
|
1689
|
+
if (allowed !== undefined) {
|
|
1690
|
+
entries = (await Promise.all(entries.map(async e => {
|
|
1691
|
+
const directory = kind === 'projects' ? e.root : e.directory;
|
|
1692
|
+
const canonical = await fsRealpath(directory).catch(() => undefined);
|
|
1693
|
+
return canonical && (!e.canonical || canonical === e.canonical) && allowed.includes(canonical) ? e : undefined;
|
|
1694
|
+
}))).filter(Boolean);
|
|
1695
|
+
}
|
|
1696
|
+
const offset = params.cursor === undefined ? 0 : Number(params.cursor);
|
|
1697
|
+
if (!Number.isSafeInteger(offset) || offset < 0) throw new RpcError(-32602, 'Invalid registry cursor');
|
|
1698
|
+
const limit = params.limit ?? 100;
|
|
1699
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new RpcError(-32602, 'Invalid registry limit');
|
|
1700
|
+
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 };
|
|
1701
|
+
});
|
|
1702
|
+
const registryMutation = (method: string, p: any) => registryCall(async () => {
|
|
1703
|
+
if (!Number.isSafeInteger(p.ifRevision) || p.ifRevision < 0) throw new RpcError(-32602, 'ifRevision is required');
|
|
1704
|
+
const { requestId, ifRevision, authorizedRoots, ...args } = p;
|
|
1705
|
+
const result = await registry!.mutate(method, args, { requestId, ifRevision, allowedRoots: authorizedRoots });
|
|
1706
|
+
return result.workspace ? { ...result, workspace: await workspaceDescriptor(result.workspace) } : result;
|
|
1707
|
+
});
|
|
1708
|
+
runtime.bindSchedules?.(async (action, params) => handlers[`schedule.${action}`](undefined as any, params));
|
|
1001
1709
|
for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
|
|
1002
1710
|
Object.setPrototypeOf(handlers, null);
|
|
1003
1711
|
// Every v1 method name stays the daemon's, served here or not, so no extension takes one.
|
|
@@ -1056,7 +1764,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1056
1764
|
}
|
|
1057
1765
|
|
|
1058
1766
|
/** What this daemon lists in daemon.hello: only features it serves now (docs/protocol/alp-json-rpc-v1.md §6). */
|
|
1059
|
-
const capabilities = [CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...(store ? [CAPABILITY.promptReceipts] : []), ...operations.capabilities];
|
|
1767
|
+
const capabilities = [...(runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : []), CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...(store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : []), ...(schedules ? [CAPABILITY.schedule] : []), ...(registry ? ['workspace.registry', CAPABILITY.workspaceGit] : []), ...(worktrees ? ['workspace.worktree'] : []), ...(attachments ? [CAPABILITY.attachments] : []), ...(conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : []), ...(conversation?.reloads ? [CAPABILITY.sessionReload] : []), ...(conversation?.configures ? [CAPABILITY.sessionConfigureLive] : []), ...(conversation ? [CAPABILITY.sessionResumeCommand] : []), ...operations.capabilities];
|
|
1060
1768
|
|
|
1061
1769
|
/** A response too large for the wire becomes an error the client can read. */
|
|
1062
1770
|
function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
|
|
@@ -1107,7 +1815,9 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1107
1815
|
const issues = validateParams(method, params)!;
|
|
1108
1816
|
if (issues.length) throw invalidParams(issues);
|
|
1109
1817
|
connection.helloed = true;
|
|
1110
|
-
|
|
1818
|
+
// Terminals are listed only while the host's switch is on (and the PTY module loads).
|
|
1819
|
+
const terminalLimits = await terminals?.advertised();
|
|
1820
|
+
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities: terminalLimits ? [...capabilities, CAPABILITY.terminal] : capabilities, ...(attachments ? { attachmentLimits: attachments.limits } : {}), ...(terminalLimits ? { terminalLimits } : {}) } });
|
|
1111
1821
|
return;
|
|
1112
1822
|
}
|
|
1113
1823
|
if (!connection.helloed) throw new RpcError(ERROR.protocol, 'daemon.hello is required first', { reason: 'hello_required' });
|
|
@@ -1144,6 +1854,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1144
1854
|
}
|
|
1145
1855
|
connections.delete(connection);
|
|
1146
1856
|
watchers.delete(connection);
|
|
1857
|
+
terminals?.disconnect(connection);
|
|
1147
1858
|
for (const root of [...connection.roots]) {
|
|
1148
1859
|
detach(connection, root);
|
|
1149
1860
|
void reap(root);
|
|
@@ -1254,6 +1965,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1254
1965
|
|
|
1255
1966
|
local() {
|
|
1256
1967
|
const events = new Set<(envelope: Envelope) => void>();
|
|
1968
|
+
const notifications = new Set<(method: string, params: any) => void>();
|
|
1257
1969
|
const closes = new Set<(error: Error) => void>();
|
|
1258
1970
|
const pending = new Map<number, { resolve: (value: any) => void; reject: (error: Error) => void }>();
|
|
1259
1971
|
let sequence = 0;
|
|
@@ -1268,6 +1980,11 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1268
1980
|
for (const listener of events) listener(message.params);
|
|
1269
1981
|
return;
|
|
1270
1982
|
}
|
|
1983
|
+
// Other notifications (terminal.event, §12.10) carry a method and no id.
|
|
1984
|
+
if (typeof message.method === 'string' && message.id === undefined) {
|
|
1985
|
+
for (const listener of notifications) listener(message.method, message.params);
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1271
1988
|
const waiter = pending.get(message.id);
|
|
1272
1989
|
if (!waiter) return;
|
|
1273
1990
|
pending.delete(message.id);
|
|
@@ -1286,6 +2003,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1286
2003
|
});
|
|
1287
2004
|
},
|
|
1288
2005
|
onEvent(listener) { events.add(listener); return () => events.delete(listener); },
|
|
2006
|
+
onNotification(listener) { notifications.add(listener); return () => notifications.delete(listener); },
|
|
1289
2007
|
onClose(listener) { closes.add(listener); return () => closes.delete(listener); },
|
|
1290
2008
|
close() {
|
|
1291
2009
|
if (ended) return;
|
|
@@ -1318,6 +2036,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1318
2036
|
async close() {
|
|
1319
2037
|
closing = true;
|
|
1320
2038
|
if (sweeper) clearInterval(sweeper);
|
|
2039
|
+
attachments?.close();
|
|
2040
|
+
// Every terminal ends with alpd, its whole process tree killed.
|
|
2041
|
+
await terminals?.shutdown();
|
|
2042
|
+
// The tick that runs now is waited for: a delivery under way finishes, so its
|
|
2043
|
+
// receipt is written and the job is not left half delivered.
|
|
2044
|
+
await scheduler?.stop();
|
|
1321
2045
|
const stopped = new Promise<void>(resolve => server.close(() => resolve()));
|
|
1322
2046
|
for (const connection of connections) connection.socket?.destroy();
|
|
1323
2047
|
await stopped;
|