@anhlp/alp-daemon 0.0.1-beta.3 → 0.0.1-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/THIRD-PARTY-NOTICES.txt +26 -1
- package/dist/alpd.js +29928 -14898
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +34 -1
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +688 -0
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +154 -2
- package/dist/files.js +392 -68
- package/dist/git.d.ts +93 -0
- package/dist/git.js +1192 -0
- package/dist/gitignore.d.ts +5 -0
- package/dist/gitignore.js +7 -1
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +21 -1
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/main.js +43 -11
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +198 -0
- package/dist/operations.d.ts +8 -2
- package/dist/operations.js +20 -10
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +296 -0
- package/dist/schedules.d.ts +70 -0
- package/dist/schedules.js +246 -0
- package/dist/server.d.ts +14 -2
- package/dist/server.js +836 -90
- package/dist/store.d.ts +72 -2
- package/dist/store.js +111 -4
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal-screen.d.ts +24 -0
- package/dist/terminal-screen.js +99 -0
- package/dist/terminals.d.ts +193 -0
- package/dist/terminals.js +570 -0
- package/dist/windows-terminal.d.ts +29 -0
- package/dist/windows-terminal.js +122 -0
- package/dist/worktrees.d.ts +65 -0
- package/dist/worktrees.js +318 -0
- package/native/README.md +201 -0
- package/native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/native/prebuilt/darwin-x64/manifest.json +11 -0
- package/native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/native/terminal-owner.c +389 -0
- package/package.json +70 -7
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +528 -82
- package/src/git.ts +1140 -0
- package/src/gitignore.ts +10 -0
- package/src/history.ts +118 -0
- package/src/index.ts +7 -0
- package/src/lifecycle.ts +283 -0
- package/src/main.ts +37 -12
- package/src/native-terminal.ts +122 -0
- package/src/operations.ts +27 -11
- package/src/registry.ts +238 -0
- package/src/scheduler.ts +432 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +948 -102
- package/src/store.ts +117 -4
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +641 -0
- package/src/windows-terminal.ts +123 -0
- package/src/worktrees.ts +382 -0
package/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';
|
|
@@ -8,12 +12,21 @@ import { createLogger } from '@anhlp/alp-core/log';
|
|
|
8
12
|
import { AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from '@anhlp/alp-protocol';
|
|
9
13
|
import { validateParams } from '@anhlp/alp-protocol/contract';
|
|
10
14
|
export { ERROR } from '@anhlp/alp-protocol';
|
|
11
|
-
import { DEFAULT_MODEL, models, modes, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
|
|
15
|
+
import { DEFAULT_MODEL, models, modes, type ModelCatalog, 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
|
-
import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from './files.js';
|
|
21
|
+
import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, 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) =>
|
|
@@ -67,6 +117,10 @@ function digest(value: unknown) {
|
|
|
67
117
|
type Connection = {
|
|
68
118
|
socket?: net.Socket;
|
|
69
119
|
helloed: boolean;
|
|
120
|
+
/** It said in daemon.hello that an ALP agent started it (t-ca1f): refused what only the user may do. */
|
|
121
|
+
agent?: boolean;
|
|
122
|
+
/** The client name daemon.hello gave: a gate card answered from alp-paseo* is recorded as paseo, else web. */
|
|
123
|
+
client?: string;
|
|
70
124
|
roots: Set<string>;
|
|
71
125
|
send(message: unknown): void;
|
|
72
126
|
nextId: number;
|
|
@@ -75,6 +129,13 @@ type Connection = {
|
|
|
75
129
|
|
|
76
130
|
/** Retained events per live tree, for attach and replay. */
|
|
77
131
|
const TREE_LOG_LIMIT = 20_000;
|
|
132
|
+
/** The daemon.hello capability a process an ALP agent started announces (t-ca1f; the client's handshake sends it). */
|
|
133
|
+
const AGENT_CAPABILITY = 'principal.agent';
|
|
134
|
+
/** A shell alpd opens carries no ALP_AGENT_SESSION, so an agent's connection may not open, attach to or type into one (t-ca1f). */
|
|
135
|
+
const agentRefused = (connection: { agent?: boolean }, method: string): undefined => {
|
|
136
|
+
if (connection.agent) throw new RpcError(ERROR.forbidden, `${method} is the user's; this connection was opened by an ALP agent`, { reason: 'user_only' });
|
|
137
|
+
return undefined;
|
|
138
|
+
};
|
|
78
139
|
const SESSION_ID = /^[\w.:-]{1,128}$/;
|
|
79
140
|
const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
80
141
|
const RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
@@ -93,6 +154,17 @@ function titleFromPrompt(text: string): string | undefined {
|
|
|
93
154
|
return line ? [...line].slice(0, PROMPT_TITLE_CHARS).join('').trim() || undefined : undefined;
|
|
94
155
|
}
|
|
95
156
|
|
|
157
|
+
/**
|
|
158
|
+
* Whether a message is the user's own words, which alone may name a root: ALP's mail, briefs,
|
|
159
|
+
* resumes and scheduled jobs (`alp-` ids) never do. A runtime says who wrote it in `origin`;
|
|
160
|
+
* without it, only a message a client sent (its clientMessageId) counts, so a replayed message
|
|
161
|
+
* nobody can place does not.
|
|
162
|
+
*/
|
|
163
|
+
function fromUser(item: { origin?: string; clientMessageId?: string }) {
|
|
164
|
+
if (item.clientMessageId?.startsWith('alp-')) return false;
|
|
165
|
+
return item.origin !== undefined ? item.origin === 'user' : item.clientMessageId !== undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
96
168
|
/**
|
|
97
169
|
* session.list's order and its keyset cursor: roots before children, the latest `updatedAt`
|
|
98
170
|
* first, then by id, so a page continues after the last session it holds, as Paseo's history pages
|
|
@@ -137,7 +209,9 @@ export type DaemonServer = {
|
|
|
137
209
|
* shape so every viewer agrees; re-exported here to keep `@anhlp/alp-daemon/server`'s API. */
|
|
138
210
|
export type { SessionSummary };
|
|
139
211
|
|
|
140
|
-
export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates }: {
|
|
212
|
+
export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions, modelCatalog }: {
|
|
213
|
+
/** The live model catalog (t-e5ee); without it catalog.get answers the static rows and catalog.refresh is unavailable. */
|
|
214
|
+
modelCatalog?: ModelCatalog;
|
|
141
215
|
runtime: AlpRuntime;
|
|
142
216
|
socketPath: string;
|
|
143
217
|
version: string;
|
|
@@ -154,8 +228,25 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
154
228
|
home?: OperationsOptions['home'];
|
|
155
229
|
/** ALP's built-in agents and teams, for the library and team methods. */
|
|
156
230
|
templates?: OperationsOptions['templates'];
|
|
231
|
+
/** How often the scheduler looks for jobs whose time has come; tests shorten it. */
|
|
232
|
+
scheduleTickMs?: number;
|
|
233
|
+
/** How long a job's delivery may take; tests shorten it. */
|
|
234
|
+
scheduleDeliveryTimeoutMs?: number;
|
|
235
|
+
/** Lower attachment limits (an operator's, never higher than ATTACHMENTS) and test hooks. */
|
|
236
|
+
attachmentOptions?: Partial<Pick<AttachmentStoreOptions, 'limits' | 'now' | 'io' | 'sweepMs'>>;
|
|
237
|
+
/** Lower terminal limits (never higher than TERMINAL or the operator's) and test hooks. */
|
|
238
|
+
terminalOptions?: Partial<Pick<TerminalServiceOptions, 'limits' | 'now' | 'spawn' | 'processes' | 'sweepMs' | 'killGraceMs' | 'maxBufferedBytes' | 'platform'>>;
|
|
157
239
|
}): DaemonServer {
|
|
158
240
|
const connections = new Set<Connection>();
|
|
241
|
+
const catalogResult = () => {
|
|
242
|
+
const state = modelCatalog?.state();
|
|
243
|
+
return { models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}`,
|
|
244
|
+
...(state ? { fetchedAt: state.fetchedAt, providers: Object.fromEntries(Object.entries(state.providers).map(([runtime, provider]) => [runtime, { status: provider!.status, fetchedAt: provider!.fetchedAt, ...(provider!.error ? { error: provider!.error } : {}) }])) } : {}) };
|
|
245
|
+
};
|
|
246
|
+
// Every helloed connection learns that the catalog changed, and re-reads it (catalog.updated).
|
|
247
|
+
const unsubscribeCatalog = modelCatalog?.onUpdated(snapshot => {
|
|
248
|
+
for (const connection of connections) if (connection.helloed) { try { connection.send({ jsonrpc: '2.0', method: 'catalog.updated', params: { fetchedAt: snapshot.fetchedAt } }); } catch { /* a gone connection */ } }
|
|
249
|
+
});
|
|
159
250
|
/** Root of every live session. */
|
|
160
251
|
const rootOf = new Map<string, string>();
|
|
161
252
|
const attached = new Map<string, Set<Connection>>();
|
|
@@ -172,17 +263,173 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
172
263
|
/** Roots alpd reopens after a restart; they stay open until their recovery has started. */
|
|
173
264
|
const recovering = new Map<string, Promise<void>>();
|
|
174
265
|
const startedAt = new Date().toISOString();
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
266
|
+
/** The clock of this daemon: the job store and the scheduler share it. */
|
|
267
|
+
const clock = () => Date.now();
|
|
268
|
+
/**
|
|
269
|
+
* The scheduled continuations of this host; their own directory, beside the state.
|
|
270
|
+
* They need the prompt receipt (the store) to deliver a job at most once, so a
|
|
271
|
+
* daemon without a store serves no jobs at all.
|
|
272
|
+
*/
|
|
273
|
+
const schedules = home && store ? createScheduleStore(path.join(home, 'schedules'), { now: clock }) : undefined;
|
|
274
|
+
/**
|
|
275
|
+
* The job of that id in that project: the store keeps the project boundary, and a
|
|
276
|
+
* refusal of the store is answered like one of the daemon's own.
|
|
277
|
+
*/
|
|
278
|
+
const storeJob = async (id: string, projectRoot: string) => {
|
|
279
|
+
if (!schedules) return undefined;
|
|
280
|
+
try { return await schedules.get(id, { projectRoot }); }
|
|
281
|
+
catch (error) { throw scheduleFailed(error); }
|
|
282
|
+
};
|
|
283
|
+
/**
|
|
284
|
+
* Non-image attachments (§12.6): with a home and a store (prompt receipts pin their references),
|
|
285
|
+
* never on Windows (no O_NOFOLLOW, no POSIX modes: not a supported platform for them).
|
|
286
|
+
*/
|
|
287
|
+
const attachments = home && store && process.platform !== 'win32' ? createAttachmentStore({
|
|
288
|
+
root: path.join(home, 'state', 'attachments'),
|
|
289
|
+
sessionProject: sessionId => runtime.snapshot(sessionId)?.projectRoot ?? records.get(sessionId)?.session?.projectRoot,
|
|
290
|
+
crashPoint,
|
|
291
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
292
|
+
// A collected object's staged copy goes with it.
|
|
293
|
+
onDiscard: attachmentId => (runtime as AlpRuntime & AttachmentRuntime).dropAttachment?.(attachmentId),
|
|
294
|
+
...attachmentOptions,
|
|
295
|
+
}) : undefined;
|
|
296
|
+
// The runtime side of the seam (issue #121 branch J): a runtime that takes attachment parts reads them through this.
|
|
297
|
+
(runtime as AlpRuntime & AttachmentRuntime).bindAttachments?.(attachments?.reader);
|
|
298
|
+
/**
|
|
299
|
+
* Gates of roots whose conversation a lifecycle operation changes (a rewind): prompts, scheduled
|
|
300
|
+
* deliveries and reopens of the root wait until it is through (§12.7).
|
|
301
|
+
*/
|
|
302
|
+
const holds = new Map<string, { count: number; open: Promise<void>; release: () => void }>();
|
|
303
|
+
// Conservatively invalidate in-flight attach reads even when a lifecycle hold ends during I/O.
|
|
304
|
+
let holdRevision = 0;
|
|
305
|
+
function holdPrompts(root: string) {
|
|
306
|
+
holdRevision++;
|
|
307
|
+
let gate = holds.get(root);
|
|
308
|
+
if (!gate) {
|
|
309
|
+
let release!: () => void;
|
|
310
|
+
const open = new Promise<void>(resolve => { release = resolve; });
|
|
311
|
+
gate = { count: 0, open, release };
|
|
312
|
+
holds.set(root, gate);
|
|
313
|
+
}
|
|
314
|
+
gate.count++;
|
|
315
|
+
const held = gate;
|
|
316
|
+
let released = false;
|
|
317
|
+
return () => {
|
|
318
|
+
if (released) return;
|
|
319
|
+
released = true;
|
|
320
|
+
if (--held.count === 0) { if (holds.get(root) === held) holds.delete(root); held.release(); }
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
/** Prompt deliveries in flight per root: a rewind refuses while one is on its way. */
|
|
324
|
+
const promptsInFlight = new Map<string, number>();
|
|
325
|
+
const rootIdOf = (sessionId: string) => rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
326
|
+
/** Waits while the root's conversation is being changed, then counts a delivery in flight until `run` settles. */
|
|
327
|
+
async function gated<T>(sessionId: string, run: () => Promise<T>): Promise<T> {
|
|
328
|
+
const root = rootIdOf(sessionId);
|
|
329
|
+
while (holds.has(root)) await holds.get(root)!.open;
|
|
330
|
+
refuseFenced(root);
|
|
331
|
+
promptsInFlight.set(root, (promptsInFlight.get(root) ?? 0) + 1);
|
|
332
|
+
try { return await run(); }
|
|
333
|
+
finally {
|
|
334
|
+
const left = (promptsInFlight.get(root) ?? 1) - 1;
|
|
335
|
+
if (left > 0) promptsInFlight.set(root, left); else promptsInFlight.delete(root);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
/** A root whose rewind is applied but not committed takes no prompt or reopen until that rewind is sent again. */
|
|
339
|
+
function fencedRoot(root: string): string | undefined { return conversation?.fenced(root); }
|
|
340
|
+
function refuseFenced(root: string) {
|
|
341
|
+
const requestId = fencedRoot(root);
|
|
342
|
+
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' });
|
|
343
|
+
}
|
|
344
|
+
/** Forks and rewinds of Codex and Claude conversations (§12.7): with a store, through the lifecycle journal. */
|
|
345
|
+
const journal = store ? createLifecycleJournal(path.join(store.root, 'lifecycle')) : undefined;
|
|
346
|
+
const conversation: ReturnType<typeof createConversation> | undefined = store && journal ? createConversation({
|
|
347
|
+
runtime, store, journal, records, cursors, logs, treeLogLimit: TREE_LOG_LIMIT,
|
|
348
|
+
summary: id => summary(id), digest,
|
|
349
|
+
unsettled: (root): string | undefined => fencedRoot(root) ? 'a rewind of it is not finished; send that rewind again'
|
|
350
|
+
: recovering.has(root) ? 'it is being reopened after a restart'
|
|
351
|
+
: openingSessions.has(root) ? 'it is opening'
|
|
352
|
+
: promptsInFlight.get(root) ? 'a prompt is being delivered' : undefined,
|
|
353
|
+
holdPrompts,
|
|
354
|
+
broadcast: (root, envelope) => { for (const connection of attached.get(root) ?? []) deliver(connection, envelope); },
|
|
355
|
+
get registry() { return registry; },
|
|
356
|
+
get worktrees() { return worktrees; },
|
|
357
|
+
attachments,
|
|
358
|
+
crashPoint,
|
|
359
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
360
|
+
startedAt,
|
|
361
|
+
}) : undefined;
|
|
362
|
+
/** The daemon's own start-up; the scheduler waits for it before it delivers. */
|
|
363
|
+
let restored: Promise<unknown> = Promise.resolve();
|
|
364
|
+
/**
|
|
365
|
+
* The sessions the recovery is opening again, and the ones it could not open. A job
|
|
366
|
+
* that waits for such a session waits for it, and a session that could not be opened
|
|
367
|
+
* fails the job with the reason.
|
|
368
|
+
*/
|
|
369
|
+
const openingSessions = new Map<string, number>();
|
|
370
|
+
const recoveryErrors = new Map<string, string>();
|
|
371
|
+
/** A session is being opened again; two opens at once are counted, not overwritten. */
|
|
372
|
+
const markOpening = (sessionId: string) => openingSessions.set(sessionId, (openingSessions.get(sessionId) ?? 0) + 1);
|
|
373
|
+
/** The session is open again (or was never open): the next open is counted anew. */
|
|
374
|
+
const clearOpening = (sessionId: string) => {
|
|
375
|
+
const count = (openingSessions.get(sessionId) ?? 0) - 1;
|
|
376
|
+
if (count > 0) openingSessions.set(sessionId, count);
|
|
377
|
+
else openingSessions.delete(sessionId);
|
|
378
|
+
};
|
|
379
|
+
/**
|
|
380
|
+
* The reason a session could not be opened again belongs to the jobs that wait for
|
|
381
|
+
* that session: a reason no job needs is no reason at all, and the map of them must
|
|
382
|
+
* not grow with the number of sessions.
|
|
383
|
+
*/
|
|
384
|
+
function keepRecoveryError(sessionId: string, message: string) {
|
|
385
|
+
if (scheduler?.holds(sessionId)) recoveryErrors.set(sessionId, message);
|
|
386
|
+
}
|
|
387
|
+
/** The reason is dropped when the last job that needed it is through. */
|
|
388
|
+
function dropRecoveryError(sessionId: string) {
|
|
389
|
+
if (!scheduler?.holds(sessionId)) recoveryErrors.delete(sessionId);
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* The tick that delivers the jobs whose time has come.
|
|
393
|
+
*/
|
|
394
|
+
const scheduler = schedules ? createScheduler({
|
|
395
|
+
store: schedules,
|
|
396
|
+
runtime,
|
|
397
|
+
deliver: deliverJob,
|
|
398
|
+
ready: () => restored,
|
|
399
|
+
session: sessionId => openingSessions.has(sessionId)
|
|
400
|
+
? { opening: true }
|
|
401
|
+
: recoveryErrors.has(sessionId)
|
|
402
|
+
? { error: { message: `The session this job continues could not be opened again: ${recoveryErrors.get(sessionId)}`, code: 'session_open_failed' } }
|
|
403
|
+
: undefined,
|
|
404
|
+
settled: sessionId => dropRecoveryError(sessionId),
|
|
405
|
+
stopping: () => closing,
|
|
406
|
+
now: clock,
|
|
407
|
+
...(scheduleDeliveryTimeoutMs === undefined ? {} : { deliveryTimeoutMs: scheduleDeliveryTimeoutMs }),
|
|
408
|
+
}) : undefined;
|
|
409
|
+
restored = store ? restore() : Promise.resolve();
|
|
410
|
+
|
|
411
|
+
const deliver = (connection: Connection, envelope: Envelope) => {
|
|
412
|
+
const message = { jsonrpc: '2.0', method: 'event', params: envelope };
|
|
413
|
+
// Stable events too large for transport still advance the replay position explicitly.
|
|
414
|
+
const bytes = frameBytes(message);
|
|
415
|
+
if (bytes > 512 * 1024 && envelope.cursor !== undefined) message.params = {
|
|
416
|
+
...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).` } },
|
|
417
|
+
};
|
|
418
|
+
connection.send(message);
|
|
419
|
+
};
|
|
420
|
+
/** Connections that called question.watch, with the projectRoot they asked for and whether they want roots' turn ends and attention. */
|
|
421
|
+
const watchers = new Map<Connection, { projectRoot?: string; turns: boolean; attention: boolean }>();
|
|
180
422
|
|
|
181
423
|
/** The project of a tree, live or recorded. */
|
|
182
424
|
function projectOf(root: string) {
|
|
183
425
|
return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
|
|
184
426
|
}
|
|
185
427
|
|
|
428
|
+
const sameProject = (a?: string, b?: string) => {
|
|
429
|
+
if (a === undefined || b === undefined) return a === b;
|
|
430
|
+
return a === b || projectKey(a) === projectKey(b);
|
|
431
|
+
};
|
|
432
|
+
|
|
186
433
|
/**
|
|
187
434
|
* Tells watchers not attached to the tree of a question asked or resolved there, or, for those
|
|
188
435
|
* that asked for `turns`, of the end of a root's turn. Their copy has no `cursor`: it is not part
|
|
@@ -195,11 +442,45 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
195
442
|
for (const [connection, { projectRoot, turns }] of watchers) {
|
|
196
443
|
if (turn && !turns) continue;
|
|
197
444
|
if (attached.get(root)?.has(connection)) continue;
|
|
198
|
-
if (projectRoot !== undefined && project
|
|
445
|
+
if (projectRoot !== undefined && !sameProject(project, projectRoot)) continue;
|
|
199
446
|
deliver(connection, announced);
|
|
200
447
|
}
|
|
201
448
|
}
|
|
202
449
|
|
|
450
|
+
/**
|
|
451
|
+
* Tells the connections watching attention that a root's changed: `attention` when set, none when
|
|
452
|
+
* cleared. Never kept: a client reads the current ones from question.watch (§12.2), so a change
|
|
453
|
+
* missed while it was away is not lost.
|
|
454
|
+
*/
|
|
455
|
+
function tellAttention(root: string, attention: TurnAttention | undefined) {
|
|
456
|
+
if (!watchers.size) return;
|
|
457
|
+
const project = projectOf(root);
|
|
458
|
+
const envelope: Envelope = { sessionId: root, epoch: `attention-${startedAt}`, seq: 0, ts: new Date().toISOString(), event: { type: 'attention', ...(attention ? { attention } : {}) } };
|
|
459
|
+
for (const [connection, watch] of watchers) {
|
|
460
|
+
if (!watch.attention) continue;
|
|
461
|
+
if (watch.projectRoot !== undefined && !sameProject(project, watch.projectRoot)) continue;
|
|
462
|
+
deliver(connection, envelope);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* The acknowledgement of each root whose write is on its way. Whatever else can change a root's
|
|
468
|
+
* attention (a turn of the root starting or ending, archiving) drops it, so a failed write brings
|
|
469
|
+
* the attention back only when nothing changed it meanwhile; it lives no longer than the write.
|
|
470
|
+
*/
|
|
471
|
+
const pendingAcks = new Map<string, object>();
|
|
472
|
+
|
|
473
|
+
/** The attention of the roots of `projectRoot` (every project when absent): archived roots never ask. */
|
|
474
|
+
function attentionOf(projectRoot?: string) {
|
|
475
|
+
const found: Array<{ sessionId: string; attention: TurnAttention }> = [];
|
|
476
|
+
for (const record of records.values()) {
|
|
477
|
+
if (record.id !== record.rootId || !record.attention || record.archived) continue;
|
|
478
|
+
if (projectRoot !== undefined && !sameProject(projectOf(record.id), projectRoot)) continue;
|
|
479
|
+
found.push({ sessionId: record.id, attention: record.attention });
|
|
480
|
+
}
|
|
481
|
+
return found;
|
|
482
|
+
}
|
|
483
|
+
|
|
203
484
|
/** Records a change; the write is queued, and a failure is logged and counted in daemon.status. */
|
|
204
485
|
function save(record: SessionRecord & { activeTurnId?: string }, changes: Partial<SessionRecord & { activeTurnId?: string }> = {}) {
|
|
205
486
|
Object.assign(record, changes, { updatedAt: new Date().toISOString() });
|
|
@@ -238,15 +519,18 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
238
519
|
if (!record) return false;
|
|
239
520
|
if (event.type === 'session.updated') save(record, { session: { ...record.session, ...event.session, ...(event.session.parked ? {} : { parked: undefined }) } });
|
|
240
521
|
// Work on an archived session brings it back.
|
|
241
|
-
|
|
522
|
+
// A root's new turn ends the attention of its last one, as Paseo clears it then.
|
|
523
|
+
else if (event.type === 'turn.started') save(record, { status: 'running', activeTurnId: event.turnId, archived: undefined, ...(sessionId === root ? { attention: undefined } : {}) });
|
|
242
524
|
else if (event.type === 'turn.ended') save(record, { status: 'idle', activeTurnId: undefined,
|
|
525
|
+
// A root's turn that completed or failed asks every client for a look until one acknowledges it (Paseo's checkAndSetAttention).
|
|
526
|
+
...(sessionId === root ? { attention: turnAttention(event) } : {}),
|
|
243
527
|
...(record.session ? { session: { ...record.session, parked: event.state === 'failed' ? runtime.snapshot(sessionId)?.parked : undefined } } : {}),
|
|
244
528
|
...(event.state === 'failed' ? { lastError: { message: event.error?.message ?? 'Turn failed' } } : {}) });
|
|
245
529
|
// The latest usage, for a closed session's summary; written with the record's next change.
|
|
246
530
|
else if (event.type === 'usage' && record.session) record.session = { ...record.session, usage: event.usage };
|
|
247
531
|
else if (event.type === 'session.failed') save(record, { status: 'error', lastError: event.error });
|
|
248
532
|
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' &&
|
|
533
|
+
else if (event.type === 'item' && sessionId === root && !record.title && event.item.kind === 'user_message' && fromUser(event.item)) {
|
|
250
534
|
// The user's first message names an unnamed root, as Paseo names an agent (ALPD §15).
|
|
251
535
|
const title = titleFromPrompt(event.item.text);
|
|
252
536
|
if (title) { save(record, { title }); return true; }
|
|
@@ -254,6 +538,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
254
538
|
return false;
|
|
255
539
|
}
|
|
256
540
|
|
|
541
|
+
/** What a root's ended turn asks of the user: a look when it completed, attention when it failed, nothing when canceled. */
|
|
542
|
+
function turnAttention(event: Extract<AlpEvent, { type: 'turn.ended' }>): TurnAttention | undefined {
|
|
543
|
+
if (event.state === 'canceled') return undefined;
|
|
544
|
+
const message = event.error?.message?.trim();
|
|
545
|
+
return { reason: event.state === 'completed' ? 'finished' : 'error', at: new Date().toISOString(), turnId: event.turnId, ...(event.state === 'failed' && message ? { message: event.error!.message } : {}) };
|
|
546
|
+
}
|
|
547
|
+
|
|
257
548
|
/**
|
|
258
549
|
* Tells the viewers of a live root its name, as a `session.updated` kept in its timeline, so a
|
|
259
550
|
* viewer attached later replays it. Nothing is sent for a root that is not open.
|
|
@@ -286,7 +577,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
286
577
|
log.push(envelope);
|
|
287
578
|
if (log.length > TREE_LOG_LIMIT) log.splice(0, log.length - TREE_LOG_LIMIT);
|
|
288
579
|
logs.set(root, log);
|
|
580
|
+
const before = records.get(root)?.attention;
|
|
289
581
|
named = track(sessionId, root, event);
|
|
582
|
+
const after = records.get(root)?.attention;
|
|
583
|
+
// A root's turn starting or ending decides its attention, even when it was already none.
|
|
584
|
+
if (sessionId === root && (event.type === 'turn.started' || event.type === 'turn.ended')) pendingAcks.delete(root);
|
|
585
|
+
if (after !== before) tellAttention(root, after);
|
|
290
586
|
}
|
|
291
587
|
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
292
588
|
if (event.type === 'question' || event.type === 'question.resolved') tellWatchers(root, envelope);
|
|
@@ -302,24 +598,32 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
302
598
|
|
|
303
599
|
/**
|
|
304
600
|
* 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).
|
|
601
|
+
* trees. Trees with assignments the runtime can continue, whose root was working, or
|
|
602
|
+
* whose root a scheduled job waits for, are reopened afterwards (ALPD §31).
|
|
307
603
|
*/
|
|
308
604
|
async function restore() {
|
|
309
605
|
await store!.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: true });
|
|
606
|
+
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
607
|
const loaded = await store!.list();
|
|
311
608
|
await reconcileReceipts(loaded);
|
|
312
609
|
const now = Date.now();
|
|
313
610
|
const ended = { code: 'daemon_restarted', message: 'alpd stopped while this session was working' };
|
|
314
611
|
const epoch = `restart-${startedAt}`;
|
|
315
612
|
const continuing = new Set(runtime.recoverable().map(entry => entry.assignmentId));
|
|
613
|
+
// The roots a job waits for: they are reopened, so the job finds its session.
|
|
614
|
+
// Every project of the host is read here: the daemon serves them all.
|
|
615
|
+
const pending = await schedules?.all({ status: 'pending' }) ?? [];
|
|
616
|
+
for (const job of pending) scheduler?.hold(job);
|
|
617
|
+
const scheduled = new Set(pending.map(job => job.sessionId));
|
|
316
618
|
const reopen: Array<{ record: SessionRecord; working: boolean }> = [];
|
|
317
619
|
const byRoot = trees(loaded);
|
|
318
620
|
const removed = await expire(byRoot, now);
|
|
319
621
|
for (const [root, tree] of byRoot) {
|
|
320
622
|
const head = tree.find(record => record.id === root);
|
|
321
623
|
if (removed.has(root)) continue;
|
|
322
|
-
|
|
624
|
+
// A root that was closed is not opened again for a job: a job continues a session
|
|
625
|
+
// that is alive, and a closed one fails with the reason.
|
|
626
|
+
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
627
|
if (tree.some(record => LIVE.includes(record.status))) seen(root, await store!.timeline(root));
|
|
324
628
|
for (const record of tree as Array<SessionRecord & { activeTurnId?: string }>) {
|
|
325
629
|
records.set(record.id, record);
|
|
@@ -343,12 +647,20 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
343
647
|
}
|
|
344
648
|
}
|
|
345
649
|
}
|
|
650
|
+
// Forks and rewinds a crash cut off: finished from their journal, or settled unknown, before any tree reopens.
|
|
651
|
+
if (conversation) await conversation.recover().catch(error => recoveryLog.error('could not recover lifecycle operations', { code: 'ALPD_LIFECYCLE_RECOVERY_FAILED', error }));
|
|
346
652
|
// Assignments whose tree cannot be reopened end now, and their tasks go back to open.
|
|
347
653
|
const reopened = new Set(reopen.map(entry => entry.record.id));
|
|
348
654
|
for (const rootId of new Set(runtime.recoverable().map(entry => entry.rootId))) {
|
|
349
655
|
if (!reopened.has(rootId)) await runtime.abandon(rootId, 'its root session cannot be reopened').catch(() => {});
|
|
350
656
|
}
|
|
351
|
-
for (const { record, working } of reopen)
|
|
657
|
+
for (const { record, working } of reopen) {
|
|
658
|
+
// A root whose rewind could not be finished stays closed: it would reopen on the old conversation.
|
|
659
|
+
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; }
|
|
660
|
+
// The session is opened again: a job that waits for it waits, it does not fail.
|
|
661
|
+
markOpening(record.id);
|
|
662
|
+
recovering.set(record.id, recoverTree(record, working, () => { clearOpening(record.id); }));
|
|
663
|
+
}
|
|
352
664
|
}
|
|
353
665
|
|
|
354
666
|
function trees(list: Iterable<SessionRecord>) {
|
|
@@ -375,40 +687,62 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
375
687
|
}
|
|
376
688
|
const continuing = new Set(runtime.recoverable().map(entry => entry.rootId));
|
|
377
689
|
for (const [root, tree] of byRoot) {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
690
|
+
const remove = async () => {
|
|
691
|
+
if (!tree.some(record => record.id === root)) return;
|
|
692
|
+
if (tree.some(record => LIVE.includes(record.status))) return;
|
|
693
|
+
if (now - Math.max(...tree.map(record => Date.parse(record.updatedAt) || now)) <= RETENTION_MS) return;
|
|
694
|
+
if (tree.some(record => now - (receiptWritten.get(record.id) ?? 0) <= RECEIPT_RETENTION_MS)) return;
|
|
695
|
+
if (continuing.has(root) || rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
696
|
+
// A tree a job waits for stays: the job is to continue that very session.
|
|
697
|
+
if (scheduler?.holds(root)) return;
|
|
698
|
+
const ids = tree.map(record => record.id);
|
|
699
|
+
// A tree restored from a backup counts from its restore: its files were written then.
|
|
700
|
+
if (now - await store!.writtenAt(ids) <= RETENTION_MS) return;
|
|
701
|
+
if (rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
702
|
+
if (await conversation?.retainsFork(root)) return;
|
|
703
|
+
// Forgotten before the files go, so a resume arriving meanwhile finds nothing to reopen.
|
|
704
|
+
for (const id of ids) records.delete(id);
|
|
705
|
+
cursors.delete(root);
|
|
706
|
+
await store!.remove(root, ids);
|
|
707
|
+
// The history is gone: what its prompts pinned is released (kept releasedGraceMs more).
|
|
708
|
+
await attachments?.releaseSessions(ids).catch(error => recoveryLog.warn('could not release the attachments of removed sessions', { code: 'ALPD_ATTACHMENT_RELEASE_FAILED', error }));
|
|
709
|
+
if (runLogDir) await unlink(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`)).catch(() => {});
|
|
710
|
+
removed.add(root);
|
|
711
|
+
};
|
|
712
|
+
// A source cannot start a native fork between the dependency check and deletion.
|
|
713
|
+
if (conversation) await conversation.lifecycle.serial(root, remove);
|
|
714
|
+
else await remove();
|
|
393
715
|
}
|
|
394
716
|
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
717
|
return removed;
|
|
396
718
|
}
|
|
397
719
|
|
|
398
720
|
/** Retention while alpd runs: receipts past their window, then expired trees; temporary files stay, as writes may be under way. */
|
|
721
|
+
let sweeping = false;
|
|
399
722
|
async function sweep() {
|
|
400
|
-
if (closing || !store) return;
|
|
723
|
+
if (closing || !store || sweeping) return;
|
|
724
|
+
sweeping = true;
|
|
401
725
|
try {
|
|
402
726
|
await restored;
|
|
403
727
|
await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
|
|
728
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS);
|
|
404
729
|
await expire(trees(records.values()));
|
|
405
730
|
} catch (error) {
|
|
406
731
|
recoveryLog.warn('retention sweep failed', { code: 'ALP_RETENTION_FAILED', error });
|
|
732
|
+
} finally {
|
|
733
|
+
sweeping = false;
|
|
407
734
|
}
|
|
408
735
|
}
|
|
409
736
|
const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : undefined;
|
|
410
737
|
sweeper?.unref();
|
|
411
738
|
|
|
739
|
+
/**
|
|
740
|
+
* The scheduler's tick. It runs as long as alpd runs, so a job that comes due is
|
|
741
|
+
* delivered even when nobody is watching: the tick is not the runtime's watchdog,
|
|
742
|
+
* which stops as soon as no assignment is left.
|
|
743
|
+
*/
|
|
744
|
+
scheduler?.start(scheduleTickMs);
|
|
745
|
+
|
|
412
746
|
/**
|
|
413
747
|
* Completes receipts a crash left pending when the tree's timeline shows how the runtime
|
|
414
748
|
* answered; the rest stay pending, so their prompt answers outcome_unknown and is never
|
|
@@ -437,20 +771,31 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
437
771
|
}
|
|
438
772
|
|
|
439
773
|
/** Reopens a root nobody watches yet and continues what it and its assignments were doing. */
|
|
440
|
-
async function recoverTree(record: SessionRecord, working: boolean) {
|
|
774
|
+
async function recoverTree(record: SessionRecord, working: boolean, opened?: () => void) {
|
|
441
775
|
const session = record.session!;
|
|
776
|
+
// The open of this session is counted once: the flag is cleared when the open is
|
|
777
|
+
// over, whether it succeeded or not, and a second open of the same session keeps
|
|
778
|
+
// its own count.
|
|
779
|
+
let openedOnce = false;
|
|
780
|
+
const open = () => { if (openedOnce) return; openedOnce = true; opened?.(); };
|
|
442
781
|
try {
|
|
782
|
+
if (worktrees && record.spec?.cwd) await worktrees.assertAvailable(record.spec.cwd);
|
|
443
783
|
const stored = await treeLog(record.id);
|
|
444
784
|
seen(record.id, stored);
|
|
445
785
|
logs.set(record.id, [...stored]);
|
|
446
786
|
await runtime.open(record.id, {
|
|
447
787
|
...record.spec!,
|
|
448
788
|
persist: true,
|
|
449
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
|
|
789
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...(record.base ? { base: record.base } : {}) },
|
|
450
790
|
}, { history: 'skip', delegation: record.delegation ?? true });
|
|
791
|
+
// The session is open again: a job that waits for it may be delivered.
|
|
792
|
+
open();
|
|
451
793
|
const outcomes = await runtime.recover(record.id, { continueRoot: working, parkedRoot: session.parked });
|
|
452
794
|
recoveryLog.info(`recovered ${record.id}: ${outcomes.map(outcome => `${outcome.agent} ${outcome.outcome}`).join(', ') || 'root'}`, { event: 'recovered', sessionId: record.id, rootId: record.rootId });
|
|
453
795
|
} catch (error: any) {
|
|
796
|
+
// The session is not open: a job that waits for it fails with the reason.
|
|
797
|
+
open();
|
|
798
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
454
799
|
recoveryLog.error(`could not recover ${record.id}`, { code: 'ALP_RECOVERY_FAILED', sessionId: record.id, rootId: record.rootId, error });
|
|
455
800
|
await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {});
|
|
456
801
|
} finally {
|
|
@@ -466,7 +811,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
466
811
|
* the first delivery did, with other content a conflict; a receipt left pending by a
|
|
467
812
|
* crash, or a delivery the provider may or may not have received, is outcome_unknown.
|
|
468
813
|
*/
|
|
469
|
-
function deliverOnce(sessionId: string, clientMessageId: string, fingerprint: string, send: () => Promise<void
|
|
814
|
+
function deliverOnce(sessionId: string, clientMessageId: string, fingerprint: string, send: () => Promise<void>, { requireReceipt = false, prepare, abandon }: {
|
|
815
|
+
requireReceipt?: boolean;
|
|
816
|
+
/** Before the pending receipt, once no receipt answers: refusals here record nothing; attachments are pinned here. */
|
|
817
|
+
prepare?: (key: string) => Promise<void>;
|
|
818
|
+
/** The prompt certainly did not reach the runtime: what prepare pinned may go. */
|
|
819
|
+
abandon?: (key: string) => Promise<void>;
|
|
820
|
+
} = {}) {
|
|
470
821
|
const key = digest(['prompt', sessionId, clientMessageId]);
|
|
471
822
|
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
823
|
const answer = (receipt: Receipt, extra: object = {}) => ({ outcome: receipt.outcome ?? 'accepted', ...(receipt.error ? { error: receipt.error } : {}), ...extra });
|
|
@@ -482,12 +833,20 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
482
833
|
if (existing.state === 'pending' || existing.outcome === 'unknown') throw unknown();
|
|
483
834
|
return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
|
|
484
835
|
}
|
|
836
|
+
// Scheduler replays fail closed when a prior attempt's receipt was pruned,
|
|
837
|
+
// lost or never committed. Absence cannot prove that nothing was sent.
|
|
838
|
+
if (requireReceipt) throw unknown();
|
|
485
839
|
const receipt = (state: Receipt['state'], changes: Partial<Receipt> = {}): Receipt => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: new Date().toISOString() });
|
|
486
840
|
live(sessionId);
|
|
841
|
+
// Attachments are pinned before anything is sent: a crash from here on keeps them.
|
|
842
|
+
await prepare?.(key);
|
|
487
843
|
crashPoint('prompt.before-receipt');
|
|
488
844
|
// Nothing is sent unless the pending receipt is on disk: a crash from here on answers outcome_unknown.
|
|
489
845
|
try { await store!.putReceipt(key, receipt('pending')); }
|
|
490
|
-
catch (error) {
|
|
846
|
+
catch (error) {
|
|
847
|
+
await abandon?.(key).catch(() => {});
|
|
848
|
+
throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error);
|
|
849
|
+
}
|
|
491
850
|
crashPoint('prompt.after-receipt');
|
|
492
851
|
// The runtime reports how the provider answered as an event, before prompt() resolves.
|
|
493
852
|
let reply: { outcome: 'accepted' | 'failed' | 'unknown'; error?: { message: string; code?: string } } = { outcome: 'accepted' };
|
|
@@ -501,6 +860,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
501
860
|
} catch (error) {
|
|
502
861
|
// The runtime refused it before reaching the provider (the session closed meanwhile): not sent.
|
|
503
862
|
await store!.removeReceipt(key).catch(() => {});
|
|
863
|
+
await abandon?.(key).catch(() => {});
|
|
504
864
|
throw error;
|
|
505
865
|
} finally {
|
|
506
866
|
stop();
|
|
@@ -520,12 +880,26 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
520
880
|
return answer(done, { durable });
|
|
521
881
|
};
|
|
522
882
|
const previous = delivering.get(key) ?? Promise.resolve();
|
|
523
|
-
const result = previous.catch(() => {}).then(attempt);
|
|
883
|
+
const result = previous.catch(() => {}).then(() => gated(sessionId, attempt));
|
|
524
884
|
delivering.set(key, result);
|
|
525
885
|
void result.finally(() => { if (delivering.get(key) === result) delivering.delete(key); }).catch(() => {});
|
|
526
886
|
return result;
|
|
527
887
|
}
|
|
528
888
|
|
|
889
|
+
/**
|
|
890
|
+
* The delivery of a scheduled job: the prompt path a client uses, with a
|
|
891
|
+
* clientMessageId of the job's own. The receipt of that message is what keeps a job
|
|
892
|
+
* from running twice: a retry after a crash reads the receipt instead of sending.
|
|
893
|
+
*/
|
|
894
|
+
async function deliverJob(job: ScheduleJob, content: PromptContent, messageId: string, send: AlpRuntime['prompt'] = (id, input) => runtime.prompt(id, input)): Promise<ScheduleDelivery> {
|
|
895
|
+
// The id is the job's own, so it is the same in every attempt of this job.
|
|
896
|
+
const clientMessageId = messageId || scheduleMessageId(job);
|
|
897
|
+
return deliverOnce(job.sessionId, clientMessageId, digest({ delivery: 'auto', content }), async () => {
|
|
898
|
+
live(job.sessionId);
|
|
899
|
+
await send(job.sessionId, { clientMessageId, delivery: 'auto', content });
|
|
900
|
+
}, { requireReceipt: job.attempts > 1 });
|
|
901
|
+
}
|
|
902
|
+
|
|
529
903
|
/**
|
|
530
904
|
* Waits for an opened root's record and timeline (its native thread) to be written, so a
|
|
531
905
|
* crash after the answer can still resume it (ALPD §66); `durable: false` when they were not.
|
|
@@ -537,13 +911,16 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
537
911
|
|
|
538
912
|
function forget(root: string) {
|
|
539
913
|
if (runtime.snapshot(root)) return;
|
|
540
|
-
for (const [id, candidate] of rootOf) if (candidate === root) rootOf.delete(id);
|
|
914
|
+
for (const [id, candidate] of rootOf) if (candidate === root) { rootOf.delete(id); recoveryErrors.delete(id); }
|
|
915
|
+
recoveryErrors.delete(root);
|
|
541
916
|
logs.delete(root);
|
|
542
917
|
}
|
|
543
918
|
|
|
544
919
|
/** Closes an idle root that no client watches. */
|
|
545
920
|
async function reap(root: string) {
|
|
546
921
|
if (closing || attached.get(root)?.size || recovering.has(root)) return false;
|
|
922
|
+
// A root a job waits for stays open: the job is to continue that very session.
|
|
923
|
+
if (scheduler?.holds(root)) return false;
|
|
547
924
|
const session = runtime.snapshot(root);
|
|
548
925
|
if (!session || session.busy) return false;
|
|
549
926
|
await runtime.close(root).catch(() => {});
|
|
@@ -569,7 +946,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
569
946
|
const session = live ?? record?.session;
|
|
570
947
|
if (!session) return undefined;
|
|
571
948
|
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 };
|
|
949
|
+
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
950
|
}
|
|
574
951
|
|
|
575
952
|
/** The record of a root the user acts on. */
|
|
@@ -649,29 +1026,101 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
649
1026
|
if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, 'This session cannot be resumed');
|
|
650
1027
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
651
1028
|
if (agent !== undefined && agent !== session.agent) throw new RpcError(ERROR.failed, 'Cannot resume a session as a different ALP agent');
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
1029
|
+
// The session is opened again from the first moment: a job that waits for it waits
|
|
1030
|
+
// for the open, it does not fail with 'the session is closed'.
|
|
1031
|
+
markOpening(record.id);
|
|
1032
|
+
// The reason of an earlier failure is not true while the session opens again.
|
|
1033
|
+
recoveryErrors.delete(record.id);
|
|
1034
|
+
let applied = false;
|
|
656
1035
|
try {
|
|
1036
|
+
if (worktrees) await worktrees.assertAvailable(record.spec.cwd);
|
|
1037
|
+
const stored = await treeLog(record.id);
|
|
1038
|
+
seen(record.id, stored);
|
|
1039
|
+
logs.set(record.id, [...stored]);
|
|
1040
|
+
attach(connection, record.id);
|
|
657
1041
|
const opened = await runtime.open(record.id, {
|
|
658
1042
|
...record.spec,
|
|
659
1043
|
...(spec.mode !== undefined ? { mode: spec.mode } : {}),
|
|
660
1044
|
...(spec.thinking !== undefined ? { thinking: spec.thinking } : {}),
|
|
661
1045
|
persist: true,
|
|
662
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
|
|
1046
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...(record.base ? { base: record.base } : {}) },
|
|
663
1047
|
}, { history: stored.length ? 'skip' : history, delegation: record.delegation ?? delegation });
|
|
1048
|
+
applied = true;
|
|
1049
|
+
await persistAcceptedSpec(record.id, opened, { mode: spec.mode !== undefined, thinking: spec.thinking !== undefined });
|
|
664
1050
|
if (history === 'replay') replayHistory(connection, record.id, stored);
|
|
665
1051
|
return opened;
|
|
666
|
-
} catch (error) {
|
|
1052
|
+
} catch (error: any) {
|
|
1053
|
+
// A durable-write failure does not undo a successful open or abandon its viewer.
|
|
1054
|
+
if (applied) throw error;
|
|
667
1055
|
detach(connection, record.id);
|
|
1056
|
+
// The session could not be opened: a job that waits for it says why.
|
|
1057
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
668
1058
|
throw error;
|
|
1059
|
+
} finally {
|
|
1060
|
+
clearOpening(record.id);
|
|
669
1061
|
}
|
|
670
1062
|
}
|
|
671
1063
|
|
|
1064
|
+
/** Causal successful apply/open only: never infer requested configuration from later events. */
|
|
1065
|
+
async function persistAcceptedSpec(id: string, accepted: SessionSnapshot, fields: { mode?: boolean; thinking?: boolean }) {
|
|
1066
|
+
const record = records.get(id);
|
|
1067
|
+
if (!record?.spec || (!fields.mode && !fields.thinking)) return;
|
|
1068
|
+
record.spec = {
|
|
1069
|
+
...record.spec,
|
|
1070
|
+
...(fields.mode ? { mode: accepted.mode } : {}),
|
|
1071
|
+
...(fields.thinking ? { thinking: accepted.thinking } : {}),
|
|
1072
|
+
};
|
|
1073
|
+
record.updatedAt = new Date().toISOString();
|
|
1074
|
+
try { await store?.put(record); }
|
|
1075
|
+
catch (error) { throw persistenceFailed(`the configuration of ${id}; the runtime already applied it`, error); }
|
|
1076
|
+
}
|
|
1077
|
+
|
|
672
1078
|
/** Projects, tasks, library and settings (docs/protocol/alp-json-rpc-v1.md §15); a team save syncs the projects sessions ran in. */
|
|
673
|
-
const
|
|
1079
|
+
const registry = home ? createRegistry(home) : undefined;
|
|
1080
|
+
const worktrees = home && registry && process.platform !== 'win32' ? createWorkspaceWorktrees(home, registry, async (directory, run) => {
|
|
1081
|
+
if (!runtime.withWorkspaceMutation) throw new RegistryError(1005, 'Runtime cannot prove safe worktree removal', { reason: 'guard_unavailable' });
|
|
1082
|
+
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; }
|
|
1083
|
+
}, async directory => { if (!runtime.registerWorkspace) throw new RegistryError(1005, 'Runtime cannot register safe workspace ownership', { reason: 'guard_unavailable' }); await runtime.registerWorkspace(directory); },
|
|
1084
|
+
// Owner-audited adoption (t-c1ba); no RPC exposes it yet, so the default stays refusal.
|
|
1085
|
+
runtime.adoptWorkspace ? async (directory, verify) => {
|
|
1086
|
+
try { await runtime.adoptWorkspace!(directory, verify); } catch (error: any) { if (error?.data?.reason && !(error instanceof RegistryError)) throw new RegistryError(1004, 'Workspace is in use, has retained assignment results or changed identity', error.data); throw error; }
|
|
1087
|
+
} : undefined) : undefined;
|
|
1088
|
+
const workspaceDescriptor = async (w: any) => worktrees ? worktrees.describe(w) : w;
|
|
1089
|
+
// workspace.git.status and workspace.git.diff (§12.5): read-only, by registry workspaceId.
|
|
1090
|
+
const gitReader = registry ? createGitReader({ registry, log: (message, fields) => log.warn(message, { code: 'ALPD_GIT_READ_FAILED', ...fields }) }) : undefined;
|
|
1091
|
+
// workspace.git.facts (§12.5): the owner's host directory, registered or not; no registry, so
|
|
1092
|
+
// never a gateway's (prohibited there) nor an agent's connection's.
|
|
1093
|
+
const gitFacts = createGitReader({ log: (message, fields) => log.warn(message, { code: 'ALPD_GIT_READ_FAILED', ...fields }) });
|
|
1094
|
+
// Terminals (§12.10): a real PTY shell as the daemon's account, only while the host opted in
|
|
1095
|
+
// (<ALP_HOME>/terminal.json); bound to the caller's principal and the workspace's directory.
|
|
1096
|
+
const terminals = home && registry ? createTerminalService({
|
|
1097
|
+
home,
|
|
1098
|
+
resolveWorkspace: workspaceId => registry.resolve(workspaceId),
|
|
1099
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
1100
|
+
...terminalOptions,
|
|
1101
|
+
}) : undefined;
|
|
1102
|
+
const terminalCall = <T>(run: (service: NonNullable<typeof terminals>) => Promise<T>) => {
|
|
1103
|
+
if (!terminals) throw new RpcError(ERROR.unavailable, 'This alpd has no home: it serves no terminals', { reason: 'terminal_unsupported' });
|
|
1104
|
+
return run(terminals);
|
|
1105
|
+
};
|
|
1106
|
+
const attachmentCall = async <T>(run: (store: NonNullable<typeof attachments>) => Promise<T>) => {
|
|
1107
|
+
if (!attachments) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not store attachments (capability attachments is not listed)');
|
|
1108
|
+
try {
|
|
1109
|
+
return await run(attachments);
|
|
1110
|
+
} catch (error) {
|
|
1111
|
+
if (error instanceof RpcError) throw error;
|
|
1112
|
+
log.warn('attachment call failed', { code: 'ALPD_ATTACHMENT_FAILED', error });
|
|
1113
|
+
throw new RpcError(ERROR.failed, 'alpd could not store the attachment; the upload was aborted', { reason: 'persistence_failed' });
|
|
1114
|
+
}
|
|
1115
|
+
};
|
|
1116
|
+
const gitCall = <T>(run: (reader: NonNullable<typeof gitReader>) => Promise<T>) => {
|
|
1117
|
+
if (!gitReader) throw new RpcError(ERROR.unavailable, 'Registry needs ALP_HOME');
|
|
1118
|
+
return run(gitReader);
|
|
1119
|
+
};
|
|
1120
|
+
const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap(record => record.session?.projectRoot ? [record.session.projectRoot] : [])), onGateChange: root => runtime.syncGates?.(root) });
|
|
674
1121
|
const extensionOwners = new Map<string, Connection>();
|
|
1122
|
+
/** workspace.files.find's snapshots, each for the connection that asked. */
|
|
1123
|
+
const findPages = createFindPages();
|
|
675
1124
|
const handlers: Record<string, (connection: Connection, params: any) => Promise<unknown> | unknown> = {
|
|
676
1125
|
'extension.register': async (connection, params) => {
|
|
677
1126
|
const method = params?.method;
|
|
@@ -725,19 +1174,51 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
725
1174
|
},
|
|
726
1175
|
|
|
727
1176
|
'question.list'(_connection, { projectRoot } = {}) {
|
|
728
|
-
return { questions: runtime.questions().filter(question => projectRoot === undefined || projectOf(question.rootId)
|
|
1177
|
+
return { questions: runtime.questions().filter(question => projectRoot === undefined || sameProject(projectOf(question.rootId), projectRoot)) };
|
|
729
1178
|
},
|
|
730
1179
|
|
|
731
1180
|
/**
|
|
732
1181
|
* The questions waiting now; from then on this connection is told of `question` and
|
|
733
1182
|
* `question.resolved` in every tree, or those of `projectRoot`, attached or not. Calling it
|
|
734
1183
|
* again replaces the filter; it lasts as long as the connection (ALPD §15). With `turns`, also
|
|
735
|
-
* of `turn.ended` of every root
|
|
1184
|
+
* of `turn.ended` of every root; with `attention`, also of each root's attention, now and as it
|
|
1185
|
+
* changes (docs/protocol/alp-json-rpc-v1.md §12.2).
|
|
736
1186
|
*/
|
|
737
|
-
'question.watch'(connection, { projectRoot, turns } = {}) {
|
|
1187
|
+
'question.watch'(connection, { projectRoot, turns, attention } = {}) {
|
|
738
1188
|
// 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 {
|
|
1189
|
+
watchers.set(connection, { projectRoot, turns: turns === true, attention: attention === true });
|
|
1190
|
+
return {
|
|
1191
|
+
questions: runtime.questions().filter(question => projectRoot === undefined || sameProject(projectOf(question.rootId), projectRoot)),
|
|
1192
|
+
...(attention === true ? { attention: attentionOf(projectRoot) } : {}),
|
|
1193
|
+
};
|
|
1194
|
+
},
|
|
1195
|
+
|
|
1196
|
+
/**
|
|
1197
|
+
* Acknowledges a root's attention for every client, as Paseo's clear_agent_attention; with `at`,
|
|
1198
|
+
* only the attention set then, so a look at an older turn end never hides a newer one (§12.2).
|
|
1199
|
+
*/
|
|
1200
|
+
async 'session.attention.clear'(_connection, { sessionId, at }) {
|
|
1201
|
+
if (typeof sessionId !== 'string') throw new RpcError(-32602, 'sessionId is required');
|
|
1202
|
+
if (at !== undefined && typeof at !== 'string') throw new RpcError(-32602, 'at must be a string');
|
|
1203
|
+
const record = records.get(sessionId);
|
|
1204
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
|
|
1205
|
+
const attention = record.attention;
|
|
1206
|
+
if (!attention || (at !== undefined && attention.at !== at)) return { cleared: false };
|
|
1207
|
+
// Not a change of the session: its place in session.list stays.
|
|
1208
|
+
const ack = {};
|
|
1209
|
+
pendingAcks.set(record.id, ack);
|
|
1210
|
+
record.attention = undefined;
|
|
1211
|
+
try { await store?.put(record); }
|
|
1212
|
+
catch (error) {
|
|
1213
|
+
// Brought back only if nothing decided its attention meanwhile: a turn that started since, or
|
|
1214
|
+
// archiving, ended it anyway. Nobody was told of the clear, so nobody is told of this.
|
|
1215
|
+
if (pendingAcks.get(record.id) === ack && !record.attention) record.attention = attention;
|
|
1216
|
+
throw persistenceFailed(`the attention of ${record.id}`, error);
|
|
1217
|
+
}
|
|
1218
|
+
finally { if (pendingAcks.get(record.id) === ack) pendingAcks.delete(record.id); }
|
|
1219
|
+
// What holds now: a turn that ended while the write was on its way set a newer one, which stays.
|
|
1220
|
+
tellAttention(record.id, record.attention);
|
|
1221
|
+
return { cleared: true };
|
|
741
1222
|
},
|
|
742
1223
|
|
|
743
1224
|
/**
|
|
@@ -761,13 +1242,30 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
761
1242
|
* read-only, confined to it, no link followed, blocked paths always refused, .gitignore'd ones
|
|
762
1243
|
* unless includeIgnored (docs/protocol/alp-json-rpc-v1.md §12.4, ALPD §15).
|
|
763
1244
|
*/
|
|
764
|
-
async 'workspace.files.list'(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
765
|
-
return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
1245
|
+
async 'workspace.files.list'(_connection, { projectRoot, path: relative, includeIgnored, cursor, internalLinks } = {}) {
|
|
1246
|
+
return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true, cursor, internalLinks: internalLinks === true }));
|
|
766
1247
|
},
|
|
767
1248
|
async 'workspace.files.read'(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
768
1249
|
return filesCall(projectRoot, () => readWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
769
1250
|
},
|
|
770
1251
|
|
|
1252
|
+
/**
|
|
1253
|
+
* Every name under projectRoot in pages of a snapshot kept for this connection, and a file's
|
|
1254
|
+
* preview in chunks (docs/protocol/alp-json-rpc-v1.md §12.11): what the Paseo bridge's Files
|
|
1255
|
+
* panel and suggestions read, confined as workspace.files.read is. The gateway exposes neither.
|
|
1256
|
+
*/
|
|
1257
|
+
async 'workspace.files.find'(connection, { projectRoot, query, kinds, matchMode, limit, cursor } = {}) {
|
|
1258
|
+
return filesCall(projectRoot, () => findPages(connection, projectRoot, { query, kinds, matchMode, limit, cursor }));
|
|
1259
|
+
},
|
|
1260
|
+
async 'workspace.files.preview'(_connection, { projectRoot, path: relative, includeIgnored, internalLinks, maxBytes, offset, revision } = {}) {
|
|
1261
|
+
return filesCall(projectRoot, () => previewWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true, internalLinks: internalLinks === true, maxBytes, offset, revision }));
|
|
1262
|
+
},
|
|
1263
|
+
|
|
1264
|
+
/** The host's directories for the folder to add as a project (§12.11): the owner's own names, never remote. */
|
|
1265
|
+
async 'host.directories.search'(_connection, { query, limit } = {}) {
|
|
1266
|
+
return searchHostDirectories(query, { limit });
|
|
1267
|
+
},
|
|
1268
|
+
|
|
771
1269
|
/** The project board: live claims, decisions and findings (ALPD §18). */
|
|
772
1270
|
async 'board.list'(_connection, { projectRoot } = {}) {
|
|
773
1271
|
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, 'An absolute projectRoot is required');
|
|
@@ -800,13 +1298,16 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
800
1298
|
}
|
|
801
1299
|
},
|
|
802
1300
|
|
|
803
|
-
'question.answer'(
|
|
1301
|
+
'question.answer'(connection, { questionId, text, dismiss = false, reason }) {
|
|
1302
|
+
// An answer speaks for the user (a gate card's answer decides the gate): never from a connection an ALP agent opened (t-ca1f).
|
|
1303
|
+
if (connection.agent) throw new RpcError(ERROR.forbidden, 'Only the user answers a question; this connection was opened by an ALP agent', { reason: 'user_only' });
|
|
804
1304
|
if (typeof questionId !== 'string') throw new RpcError(-32602, 'questionId is required');
|
|
805
1305
|
if (dismiss !== true && typeof text !== 'string') throw new RpcError(-32602, 'text or dismiss is required');
|
|
806
1306
|
// A unique prefix is enough, as in the CLI.
|
|
807
1307
|
const matches = runtime.questions().filter(question => question.id === questionId || question.id.startsWith(questionId));
|
|
808
1308
|
if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
|
|
809
|
-
|
|
1309
|
+
const channel = connection.client?.startsWith('alp-paseo') ? 'paseo' as const : 'web' as const;
|
|
1310
|
+
runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
|
|
810
1311
|
return { questionId: matches[0].id };
|
|
811
1312
|
},
|
|
812
1313
|
|
|
@@ -815,20 +1316,99 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
815
1316
|
return {};
|
|
816
1317
|
},
|
|
817
1318
|
|
|
818
|
-
'
|
|
819
|
-
|
|
820
|
-
|
|
1319
|
+
'registry.owner': (_c, params) => registryCall(async () => {
|
|
1320
|
+
const result = params.operation ? await registry!.mutate(params.operation, params.args ?? {}, { requestId: params.requestId, ifRevision: params.ifRevision }) : undefined;
|
|
1321
|
+
const { receipts: _receipts, ...metadata } = await registry!.snapshot();
|
|
1322
|
+
return { ...(result ? { result } : {}), registry: metadata };
|
|
1323
|
+
}),
|
|
1324
|
+
'registry.worktree': (_c, p) => registryCall(async () => worktrees ? worktrees.grants(p) : { mappings: [], workspaces: [] }),
|
|
1325
|
+
'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 = worktrees ? await worktrees.grants(p) : { mappings: [], workspaces: [] }; return { mappingIds: grants.mappings.filter(m => m.source === (w.canonical ?? w.directory)).map(m => m.id) }; }),
|
|
1326
|
+
'workspace.worktree.create': (_c, p) => registryCall(async () => { if (!worktrees) throw new RegistryError(1005, 'Worktrees are unavailable on this platform', { reason: 'worktrees_unsupported' }); const result = await worktrees.mutate('create', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
|
|
1327
|
+
'workspace.worktree.remove': (_c, p) => registryCall(async () => { if (!worktrees) throw new RegistryError(1005, 'Worktrees are unavailable on this platform', { reason: 'worktrees_unsupported' }); const result = await worktrees.mutate('remove', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
|
|
1328
|
+
'workspace.git.status': (_c, p) => gitCall(reader => reader.status(p.workspaceId)),
|
|
1329
|
+
'workspace.git.diff': (_c, p) => gitCall(reader => reader.diff({ workspaceId: p.workspaceId, compare: p.compare, path: p.path, cursor: p.cursor })),
|
|
1330
|
+
'workspace.git.facts': (c, p) => agentRefused(c, 'workspace.git.facts') ?? gitFacts.facts(p.directory),
|
|
1331
|
+
'project.list': (_c, p) => registryList('projects', p),
|
|
1332
|
+
'workspace.list': (_c, p) => registryList('workspaces', p),
|
|
1333
|
+
'workspace.get': (_c, p) => registryCall(async () => {
|
|
1334
|
+
await registry!.resolve(p.workspaceId, undefined, true);
|
|
1335
|
+
const r = await registry!.snapshot();
|
|
1336
|
+
return { workspace: { ...await workspaceDescriptor(r.workspaces.find(w => w.id === p.workspaceId)), revision: r.revision }, revision: r.revision };
|
|
1337
|
+
}),
|
|
1338
|
+
'project.register': (_c, p) => registryMutation('project.register', p),
|
|
1339
|
+
'project.remove': (_c, p) => registryMutation('project.remove', p),
|
|
1340
|
+
'workspace.update': (_c, p) => registryMutation('workspace.update', p),
|
|
1341
|
+
'catalog.get': () => catalogResult(),
|
|
1342
|
+
'catalog.refresh': async () => {
|
|
1343
|
+
if (!modelCatalog) throw new RpcError(ERROR.unavailable, 'The live model catalog is not available');
|
|
1344
|
+
await modelCatalog.refresh();
|
|
1345
|
+
return catalogResult();
|
|
1346
|
+
},
|
|
1347
|
+
// attachment.* (§12.6): each call acts for its principal context; without the store (no home or
|
|
1348
|
+
// store, or Windows) alpd does not serve them, as for any method it does not know.
|
|
1349
|
+
// terminal.* (§12.10): each call acts for its principal context; input, resize and the stream
|
|
1350
|
+
// belong to the connection that attached the terminal.
|
|
1351
|
+
'terminal.create': (c, p) => agentRefused(c, 'terminal.create') ?? terminalCall(service => service.create(principalOf(p), p)),
|
|
1352
|
+
'terminal.watch': (c, p) => terminalCall(service => service.watch(principalOf(p), c, p)),
|
|
1353
|
+
'terminal.unwatch': (c) => terminalCall(service => service.unwatch(c)),
|
|
1354
|
+
'terminal.capture': (_c, p) => terminalCall(service => service.capture(principalOf(p), p)),
|
|
1355
|
+
'terminal.list': (_c, p) => terminalCall(service => service.list(principalOf(p), p)),
|
|
1356
|
+
'terminal.attach': (c, p) => agentRefused(c, 'terminal.attach') ?? terminalCall(service => service.attach(principalOf(p), c, p)),
|
|
1357
|
+
'terminal.input': (c, p) => agentRefused(c, 'terminal.input') ?? terminalCall(service => service.input(principalOf(p), c, p)),
|
|
1358
|
+
'terminal.resize': (c, p) => terminalCall(service => service.resize(principalOf(p), c, p)),
|
|
1359
|
+
'terminal.close': (_c, p) => terminalCall(service => service.close(principalOf(p), p)),
|
|
1360
|
+
'terminal.revoke': (_c, p) => terminalCall(service => service.revoke(p.principalId)),
|
|
1361
|
+
'attachment.begin': (_c, p) => attachmentCall(store => store.begin(principalOf(p), p)),
|
|
1362
|
+
'attachment.chunk': (_c, p) => attachmentCall(store => store.chunk(principalOf(p), p)),
|
|
1363
|
+
'attachment.commit': (_c, p) => attachmentCall(store => store.commit(principalOf(p), p)),
|
|
1364
|
+
'attachment.abort': (_c, p) => attachmentCall(store => store.abort(principalOf(p), p)),
|
|
1365
|
+
'attachment.get': (_c, p) => attachmentCall(store => store.get(principalOf(p), p)),
|
|
1366
|
+
'attachment.delete': (_c, p) => attachmentCall(store => store.remove(principalOf(p), p)),
|
|
1367
|
+
|
|
1368
|
+
async 'session.create'(connection, { sessionId, workspaceId, spec, history = 'skip', delegation = true, resume: resuming = false }) {
|
|
1369
|
+
if (workspaceId !== undefined) {
|
|
1370
|
+
if (!registry || typeof workspaceId !== 'string') throw new RpcError(-32602, 'Invalid workspaceId');
|
|
1371
|
+
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; }
|
|
1372
|
+
const placements = (await registryCall(() => registry!.snapshot())).sessions;
|
|
1373
|
+
const prior = Object.hasOwn(placements, sessionId) ? placements[sessionId] : undefined;
|
|
1374
|
+
if (prior && prior !== workspaceId) throw new RpcError(ERROR.conflict, 'Session belongs to another workspace', { reason: 'workspace_mismatch' });
|
|
1375
|
+
}
|
|
821
1376
|
if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
|
|
1377
|
+
// spec.restore opens a named native thread (or a Claude base) as this root's conversation: the
|
|
1378
|
+
// owner's alone. A connection an ALP agent opened never passes it on (a gateway refuses it).
|
|
1379
|
+
if (connection.agent && spec.restore !== undefined) {
|
|
1380
|
+
const { restore: _restore, ...owned } = spec;
|
|
1381
|
+
spec = owned;
|
|
1382
|
+
}
|
|
1383
|
+
if (worktrees) await registryCall(() => worktrees.assertAvailable(spec.cwd));
|
|
822
1384
|
if (sessionId !== undefined && (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, 'Invalid session id');
|
|
823
1385
|
if (history !== 'replay' && history !== 'skip') throw new RpcError(-32602, 'history must be replay or skip');
|
|
824
1386
|
const id = sessionId ?? `ses_${randomBytes(8).toString('hex')}`;
|
|
825
1387
|
// A root alpd is reopening after a restart: attach once it is open, rather than open it twice.
|
|
826
1388
|
await recovering.get(id);
|
|
1389
|
+
// A root whose conversation is being rewound opens once the rewind is through, on its new conversation.
|
|
1390
|
+
while (holds.has(id)) await holds.get(id)!.open;
|
|
1391
|
+
refuseFenced(id);
|
|
1392
|
+
let reservedWorkspaceId: string | undefined;
|
|
1393
|
+
const reserve = async () => {
|
|
1394
|
+
if (!registry) return;
|
|
1395
|
+
const directory = runtime.snapshot(id)?.projectRoot ?? records.get(id)?.session?.projectRoot ?? records.get(id)?.spec?.cwd ?? spec.cwd;
|
|
1396
|
+
if (workspaceId) await registryCall(() => registry!.resolve(workspaceId, directory));
|
|
1397
|
+
if (Object.hasOwn((await registry.snapshot()).sessions, id)) return;
|
|
1398
|
+
if (workspaceId) await registryCall(() => registry!.mutate('placement.assign', { sessionId: id, workspaceId }, { requestId: `reserve:${randomBytes(12).toString('hex')}` }));
|
|
1399
|
+
else await registryCall(() => registry!.mutate('placement.prepare', { sessions: [{ id, projectRoot: directory }] }, { requestId: `prepare:${randomBytes(12).toString('hex')}` }));
|
|
1400
|
+
reservedWorkspaceId = (await registry.snapshot()).sessions[id];
|
|
1401
|
+
};
|
|
1402
|
+
const rollback = async () => {
|
|
1403
|
+
if (!registry || !reservedWorkspaceId) return;
|
|
1404
|
+
await registryCall(() => registry!.mutate('placement.remove', { sessionId: id, workspaceId: reservedWorkspaceId }, { requestId: `rollback:${randomBytes(12).toString('hex')}` }));
|
|
1405
|
+
};
|
|
827
1406
|
const existing = runtime.snapshot(id);
|
|
828
1407
|
if (existing) {
|
|
829
1408
|
// Reopening a root that kept working after its viewer left: attach to it.
|
|
830
1409
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
831
1410
|
if (existing.parentId || (agent !== undefined && agent !== existing.agent)) throw new RpcError(ERROR.failed, 'Session is already open');
|
|
1411
|
+
await reserve();
|
|
832
1412
|
attach(connection, id);
|
|
833
1413
|
announce(connection, id, history);
|
|
834
1414
|
return { session: existing, attached: true };
|
|
@@ -836,8 +1416,11 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
836
1416
|
const record = records.get(id);
|
|
837
1417
|
if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
|
|
838
1418
|
if (record) {
|
|
839
|
-
|
|
840
|
-
|
|
1419
|
+
await reserve();
|
|
1420
|
+
try {
|
|
1421
|
+
const session = await resume(connection, record, spec, history, delegation);
|
|
1422
|
+
return { session, attached: false, resumed: true, ...await persisted(id) };
|
|
1423
|
+
} catch (error) { if (!runtime.snapshot(id)) await rollback(); throw error; }
|
|
841
1424
|
}
|
|
842
1425
|
const { restore: _restore, ...kept } = spec;
|
|
843
1426
|
const now = new Date().toISOString();
|
|
@@ -849,14 +1432,16 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
849
1432
|
if (records.get(id) === created) records.delete(id);
|
|
850
1433
|
throw persistenceFailed(`session ${id}; it was not started`, error);
|
|
851
1434
|
}
|
|
852
|
-
attach(connection, id);
|
|
853
1435
|
try {
|
|
1436
|
+
await reserve();
|
|
1437
|
+
attach(connection, id);
|
|
854
1438
|
const session = await runtime.open(id, spec, { history, delegation });
|
|
855
1439
|
return { session, attached: false, ...await persisted(id) };
|
|
856
1440
|
} catch (error) {
|
|
857
1441
|
detach(connection, id);
|
|
858
1442
|
records.delete(id);
|
|
859
1443
|
await store?.remove(id, [id]);
|
|
1444
|
+
await rollback();
|
|
860
1445
|
throw error;
|
|
861
1446
|
}
|
|
862
1447
|
},
|
|
@@ -872,32 +1457,65 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
872
1457
|
* events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
|
|
873
1458
|
* with the whole timeline. The replay and the live events that follow are in cursor order.
|
|
874
1459
|
*/
|
|
875
|
-
async 'session.
|
|
876
|
-
|
|
877
|
-
|
|
1460
|
+
async 'session.history'(_connection, { sessionId, before, limit, maxBytes }) {
|
|
1461
|
+
known(sessionId);
|
|
1462
|
+
if (!store) throw new RpcError(1005, 'Durable history unavailable');
|
|
878
1463
|
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
|
-
|
|
1464
|
+
try { return await store.history(root, sessionId, { before, limit, maxBytes }); }
|
|
1465
|
+
catch (error) { if (error instanceof HistoryError) throw new RpcError(error.reason === 'stale_cursor' ? 1004 : -32602, error.message, { reason: error.reason }); throw error; }
|
|
1466
|
+
},
|
|
1467
|
+
|
|
1468
|
+
async 'session.attach'(connection, { sessionId, replay = true, after, generation }) {
|
|
1469
|
+
if (after !== undefined && (!Number.isSafeInteger(after) || after < 0)) throw new RpcError(-32602, 'after must be a cursor');
|
|
1470
|
+
known(sessionId);
|
|
1471
|
+
const root = rootIdOf(sessionId);
|
|
1472
|
+
for (;;) {
|
|
1473
|
+
// A rewind reserves its marker cursor before publishing it. Wait through afterRewind,
|
|
1474
|
+
// including if it began while a history read awaited, so replay owns every cursor <= tip.
|
|
1475
|
+
while (holds.has(root)) await holds.get(root)!.open;
|
|
1476
|
+
refuseFenced(root);
|
|
1477
|
+
const revision = holdRevision;
|
|
1478
|
+
const found = known(sessionId);
|
|
1479
|
+
let stored: Envelope[] = [];
|
|
1480
|
+
if (replay || (store && !cursors.has(root))) {
|
|
1481
|
+
// The in-memory log keeps a live tree's latest events only; older ones come from the store.
|
|
1482
|
+
const memory = logs.get(root);
|
|
1483
|
+
const covered = !!memory?.length && (memory[0].cursor ?? 1) <= (after ?? 0) + 1;
|
|
1484
|
+
if (!covered) stored = store ? await store.timeline(root) : memory ?? [];
|
|
1485
|
+
}
|
|
1486
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1487
|
+
if (generation !== undefined) {
|
|
1488
|
+
const checkpoint = await store?.history(root, sessionId, { limit: 1 });
|
|
1489
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1490
|
+
if (checkpoint?.generation !== generation) throw new RpcError(1004, 'History generation changed', { reason: 'stale_cursor' });
|
|
1491
|
+
}
|
|
1492
|
+
// From here to the return nothing awaits, so no live event slips between replay and attach.
|
|
1493
|
+
const live = logs.get(root) ?? [];
|
|
1494
|
+
const tip = Math.max(cursors.get(root) ?? 0, stored.at(-1)?.cursor ?? 0, live.at(-1)?.cursor ?? 0);
|
|
1495
|
+
if (generation !== undefined && replay) {
|
|
1496
|
+
const covered = Math.max(after ?? 0, stored.at(-1)?.cursor ?? 0);
|
|
1497
|
+
const next = live.find(envelope => (envelope.cursor ?? 0) > covered)?.cursor;
|
|
1498
|
+
if ((next !== undefined && next > covered + 1) || (next === undefined && tip > covered)) {
|
|
1499
|
+
throw new RpcError(1005, 'History advanced beyond replay coverage; retry attach', { reason: 'history_gap' });
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
// Without a store the in-memory log keeps only the latest events: a cursor before them cannot continue either.
|
|
1503
|
+
const first = replay ? [...stored, ...live].find(envelope => envelope.cursor !== undefined)?.cursor : undefined;
|
|
1504
|
+
// A cursor in history a rewind set aside starts over too: what the client holds after it is not this conversation.
|
|
1505
|
+
const reset = after !== undefined && (after > tip || (replay && after < tip && (first === undefined || first > after + 1)) || !!conversation?.discarded(records.get(root), after));
|
|
1506
|
+
const from = reset ? 0 : after ?? 0;
|
|
1507
|
+
attach(connection, root);
|
|
1508
|
+
if (replay) {
|
|
1509
|
+
let last = from;
|
|
1510
|
+
for (const envelope of stored) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
|
|
1511
|
+
for (const envelope of live) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
|
|
1512
|
+
}
|
|
1513
|
+
announceQuestions(connection, root);
|
|
1514
|
+
// Gate cards are rebuilt from the project's tasks: one changed while nobody watched shows or settles now.
|
|
1515
|
+
const gateProject = runtime.snapshot(root)?.projectRoot;
|
|
1516
|
+
if (gateProject) void runtime.syncGates?.(gateProject)?.catch(() => {});
|
|
1517
|
+
return { session: root === found.id ? found : summary(root), cursor: tip, ...(reset ? { reset: true } : {}) };
|
|
898
1518
|
}
|
|
899
|
-
announceQuestions(connection, root);
|
|
900
|
-
return { session: root === found.id ? found : summary(root), cursor: tip, ...(reset ? { reset: true } : {}) };
|
|
901
1519
|
},
|
|
902
1520
|
|
|
903
1521
|
async 'session.release'(connection, { sessionId }) {
|
|
@@ -906,7 +1524,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
906
1524
|
return { closed: await reap(root) };
|
|
907
1525
|
},
|
|
908
1526
|
|
|
909
|
-
async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content }) {
|
|
1527
|
+
async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content, ...context }) {
|
|
910
1528
|
if (typeof clientMessageId !== 'string' || !Array.isArray(content)) throw new RpcError(-32602, 'clientMessageId and content are required');
|
|
911
1529
|
if (delivery !== 'auto' && delivery !== 'steer') throw new RpcError(-32602, 'delivery must be auto or steer');
|
|
912
1530
|
// Images are inline only (the schema refuses a path or URL); here their number and decoded size.
|
|
@@ -919,25 +1537,98 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
919
1537
|
if (bytes > PROMPT_IMAGES.maxBytes) throw new RpcError(-32602, `An image in a prompt is at most ${PROMPT_IMAGES.maxBytes} bytes`);
|
|
920
1538
|
if (total > PROMPT_IMAGES.maxTotalBytes) throw new RpcError(-32602, `The images of a prompt are at most ${PROMPT_IMAGES.maxTotalBytes} bytes together`);
|
|
921
1539
|
}
|
|
1540
|
+
// Attachments (§12.6): resolved for this principal, project and session, in order. The runtime
|
|
1541
|
+
// gets their descriptors (ids, names, digests), never a path; the fingerprint their digests.
|
|
1542
|
+
const attached = content.filter((part: { type?: string }) => part?.type === 'attachment');
|
|
1543
|
+
let resolved: RuntimeAttachment[] = [];
|
|
1544
|
+
if (attached.length) {
|
|
1545
|
+
if (!attachments || !store) throw new RpcError(ERROR.unavailable, 'This alpd does not store attachments', { reason: 'attachment_unsupported' });
|
|
1546
|
+
resolved = await attachments.resolve(principalOf(context), sessionId, attached.map((part: { attachmentId?: unknown }) => part.attachmentId));
|
|
1547
|
+
}
|
|
1548
|
+
let index = 0;
|
|
1549
|
+
const delivered: PromptContent = attached.length ? content.map((part: { type?: string }) => part?.type === 'attachment' ? resolved[index++] : part) : content;
|
|
1550
|
+
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
1551
|
const send = async () => {
|
|
923
1552
|
// Failures of an open session arrive as prompt.failed events; an unknown session has no watcher.
|
|
924
1553
|
live(sessionId);
|
|
925
|
-
await runtime.prompt(sessionId, { clientMessageId, delivery, content });
|
|
1554
|
+
await runtime.prompt(sessionId, { clientMessageId, delivery, content: delivered });
|
|
926
1555
|
};
|
|
927
1556
|
if (!store) {
|
|
928
|
-
await send
|
|
1557
|
+
await gated(sessionId, send);
|
|
929
1558
|
return {};
|
|
930
1559
|
}
|
|
931
|
-
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
1560
|
+
if (!attached.length) return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
1561
|
+
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content: fingerprinted }), send, {
|
|
1562
|
+
prepare: async key => {
|
|
1563
|
+
// Never dropped, never turned into a path: a runtime that cannot read them refuses the prompt here.
|
|
1564
|
+
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' });
|
|
1565
|
+
await attachments!.pin(`prompt:${key}`, sessionId, resolved.map(entry => entry.attachmentId));
|
|
1566
|
+
},
|
|
1567
|
+
abandon: key => attachments!.release(`prompt:${key}`),
|
|
1568
|
+
});
|
|
1569
|
+
},
|
|
1570
|
+
|
|
1571
|
+
/** A new root from a root's conversation cut at a turn, or from a branch a rewind set aside (§12.7). */
|
|
1572
|
+
async 'session.fork'(_connection, params) {
|
|
1573
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not fork conversations (capability session.fork is not listed)');
|
|
1574
|
+
return conversation.fork({ ...params, principal: principalOf(params) });
|
|
1575
|
+
},
|
|
1576
|
+
|
|
1577
|
+
/** The root's conversation from before a turn on, same id; the later turns stay a recoverable branch, files untouched (§12.7). */
|
|
1578
|
+
async 'session.rewind'(_connection, params) {
|
|
1579
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not rewind conversations (capability session.rewind is not listed)');
|
|
1580
|
+
return conversation.rewind(params);
|
|
932
1581
|
},
|
|
933
1582
|
|
|
934
|
-
|
|
1583
|
+
/** Restarts a live root's native process on its own conversation at the idle barrier (§12.8). */
|
|
1584
|
+
async 'session.reload'(_connection, params) {
|
|
1585
|
+
if (!conversation?.reloads) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not reload sessions (capability session.reload is not listed)');
|
|
1586
|
+
return conversation.reload(params);
|
|
1587
|
+
},
|
|
1588
|
+
|
|
1589
|
+
/** Compacts a live root's context now or at its next turn boundary (t-0e56). */
|
|
1590
|
+
async 'session.compact'(_connection, { sessionId }) {
|
|
1591
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new RpcError(-32602, 'sessionId is required');
|
|
1592
|
+
if (!runtime.compact) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not compact sessions');
|
|
1593
|
+
try { return runtime.compact(sessionId); }
|
|
1594
|
+
catch (error) { throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error)); }
|
|
1595
|
+
},
|
|
1596
|
+
|
|
1597
|
+
/** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
|
|
1598
|
+
async 'session.resumeCommand'(_connection, { sessionId }) {
|
|
1599
|
+
if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd has no resume command (capability session.resumeCommand is not listed)');
|
|
1600
|
+
return conversation.resumeCommand(sessionId);
|
|
1601
|
+
},
|
|
1602
|
+
|
|
1603
|
+
async 'session.interrupt'(_connection, { sessionId, turnId }) {
|
|
1604
|
+
if (turnId !== undefined) {
|
|
1605
|
+
if (typeof turnId !== 'string' || !turnId) throw new RpcError(-32602, 'turnId must be a nonempty string');
|
|
1606
|
+
if (!runtime.interruptTurn) throw new RpcError(ERROR.unavailable, 'This runtime cannot interrupt a specific turn');
|
|
1607
|
+
return { interrupted: await runtime.interruptTurn(sessionId, turnId) };
|
|
1608
|
+
}
|
|
935
1609
|
await runtime.interrupt(sessionId);
|
|
936
1610
|
return {};
|
|
937
1611
|
},
|
|
938
1612
|
|
|
939
|
-
|
|
940
|
-
|
|
1613
|
+
/**
|
|
1614
|
+
* A session's permissions mode while idle; with model, thinking or team, a live root's configuration
|
|
1615
|
+
* at the idle barrier through a restart on the same conversation (§12.9, capability session.configure.live).
|
|
1616
|
+
*/
|
|
1617
|
+
async 'session.configure'(_connection, params) {
|
|
1618
|
+
const { sessionId, mode } = params;
|
|
1619
|
+
if (params.model !== undefined || params.thinking !== undefined || params.team !== undefined) {
|
|
1620
|
+
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' });
|
|
1621
|
+
return conversation.configure(params);
|
|
1622
|
+
}
|
|
1623
|
+
return { session: await runtime.configure(sessionId, { mode }, {
|
|
1624
|
+
onApplied: accepted => persistAcceptedSpec(sessionId, accepted, { mode: true }),
|
|
1625
|
+
}) };
|
|
1626
|
+
},
|
|
1627
|
+
|
|
1628
|
+
/** What a change of model, thinking, team or mode would run a live root with (§12.9). */
|
|
1629
|
+
async 'session.configure.preview'(_connection, params) {
|
|
1630
|
+
if (!conversation?.configures) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not preview configurations (capability session.configure.live is not listed)');
|
|
1631
|
+
return { preview: await conversation.configurePreview(params) };
|
|
941
1632
|
},
|
|
942
1633
|
|
|
943
1634
|
async 'session.close'(_connection, { sessionId }) {
|
|
@@ -962,10 +1653,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
962
1653
|
async 'session.archive'(_connection, { sessionId, archived = true }) {
|
|
963
1654
|
const record = rootRecord(sessionId);
|
|
964
1655
|
if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
|
|
965
|
-
const before = record.archived;
|
|
966
|
-
|
|
1656
|
+
const before = { archived: record.archived, attention: record.attention };
|
|
1657
|
+
// An archived root never asks for attention, nor does an acknowledgement on its way bring one back.
|
|
1658
|
+
Object.assign(record, { archived: archived === true ? true : undefined }, archived === true ? { attention: undefined } : {});
|
|
1659
|
+
if (archived === true) pendingAcks.delete(record.id);
|
|
967
1660
|
try { await store?.put(record); }
|
|
968
|
-
catch (error) { record
|
|
1661
|
+
catch (error) { Object.assign(record, before); throw persistenceFailed(`the archive state of ${record.id}`, error); }
|
|
1662
|
+
if (before.attention && !record.attention) tellAttention(record.id, undefined);
|
|
969
1663
|
return { session: summary(record.id) };
|
|
970
1664
|
},
|
|
971
1665
|
|
|
@@ -980,16 +1674,41 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
980
1674
|
* a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
|
|
981
1675
|
*/
|
|
982
1676
|
'session.list'(_connection, { projectRoot, projectRoots, rootsOnly = false, includeClosed = false, includeArchived = false, limit, cursor, query } = {}): { sessions: SessionSummary[]; nextCursor?: string } {
|
|
983
|
-
const
|
|
1677
|
+
const cache = new Map<string, string>();
|
|
1678
|
+
const keyOf = (root: string) => {
|
|
1679
|
+
let key = cache.get(root);
|
|
1680
|
+
if (key === undefined) {
|
|
1681
|
+
key = projectKey(root);
|
|
1682
|
+
cache.set(root, key);
|
|
1683
|
+
}
|
|
1684
|
+
return key;
|
|
1685
|
+
};
|
|
1686
|
+
// Projects are matched by their canonical identity (projectKey), so sessions created
|
|
1687
|
+
// under a symlink (or /var -> /private/var on macOS) are listed when queried by their
|
|
1688
|
+
// canonical path, and vice versa.
|
|
1689
|
+
const wantedKey = projectRoot === undefined ? undefined : keyOf(projectRoot);
|
|
1690
|
+
const allowedKeys = Array.isArray(projectRoots) ? new Set<string>(projectRoots.map(keyOf)) : undefined;
|
|
984
1691
|
const after = cursor === undefined ? undefined : listCursor.decode(cursor);
|
|
985
1692
|
const words = typeof query === 'string' ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
|
|
986
|
-
const
|
|
1693
|
+
const live = runtime.list();
|
|
1694
|
+
const liveChildren = rootsOnly ? new Set(live.filter(session => !!session.parentId).map(session => session.id)) : undefined;
|
|
1695
|
+
const ids = new Set<string>();
|
|
1696
|
+
for (const session of live) {
|
|
1697
|
+
if (!rootsOnly || !session.parentId) ids.add(session.id);
|
|
1698
|
+
}
|
|
1699
|
+
for (const [id, record] of records) {
|
|
1700
|
+
if (!rootsOnly) {
|
|
1701
|
+
ids.add(id);
|
|
1702
|
+
} else if (record.id === record.rootId && !record.session?.parentId && !liveChildren!.has(id)) {
|
|
1703
|
+
ids.add(id);
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
987
1706
|
const sessions = [...ids].map(summary).filter((session): session is SessionSummary => !!session)
|
|
988
1707
|
.filter(session => includeClosed || session.status === 'idle' || session.status === 'running')
|
|
989
1708
|
.filter(session => includeArchived || !session.archived)
|
|
990
1709
|
.filter(session => !rootsOnly || !session.parentId)
|
|
991
|
-
.filter(session =>
|
|
992
|
-
.filter(session => !
|
|
1710
|
+
.filter(session => wantedKey === undefined || keyOf(session.projectRoot) === wantedKey)
|
|
1711
|
+
.filter(session => !allowedKeys || allowedKeys.has(keyOf(session.projectRoot)))
|
|
993
1712
|
.filter(session => !words.length || words.every(word => `${session.title ?? ''}\n${session.id}`.toLowerCase().includes(word)))
|
|
994
1713
|
.sort((a, b) => listCursor.compare(listCursor.key(a), listCursor.key(b)))
|
|
995
1714
|
.filter(session => !after || listCursor.compare(listCursor.key(session), after) > 0);
|
|
@@ -997,8 +1716,115 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
997
1716
|
const page = sessions.slice(0, limit);
|
|
998
1717
|
return { sessions: page, nextCursor: listCursor.encode(listCursor.key(page.at(-1)!)) };
|
|
999
1718
|
},
|
|
1719
|
+
|
|
1720
|
+
/**
|
|
1721
|
+
* A scheduled continuation of a root session: alpd opens the turn itself
|
|
1722
|
+
* when the time comes, without a user message. The target is a live root session of
|
|
1723
|
+
* the project; a session that is closed when the job is due fails the job, and the
|
|
1724
|
+
* reason is kept.
|
|
1725
|
+
*/
|
|
1726
|
+
async 'schedule.create'(_connection, { projectRoot, sessionId, dueAt, prompt, keepsSession } = {}) {
|
|
1727
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1728
|
+
if (typeof projectRoot !== 'string' || typeof sessionId !== 'string' || typeof dueAt !== 'string' || typeof prompt !== 'string') {
|
|
1729
|
+
throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot, sessionId, dueAt and prompt are required');
|
|
1730
|
+
}
|
|
1731
|
+
if (keepsSession !== undefined && typeof keepsSession !== 'boolean') throw new RpcError(RPC_ERROR.invalidParams, 'keepsSession must be true or false');
|
|
1732
|
+
if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot must be an absolute path');
|
|
1733
|
+
const snapshot = runtime.snapshot(sessionId);
|
|
1734
|
+
if (!snapshot) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not open`);
|
|
1735
|
+
if (snapshot.parentId) throw new RpcError(RPC_ERROR.invalidParams, 'A scheduled job continues a root session');
|
|
1736
|
+
// The project is compared as a path, not as a spelling: a client that names the
|
|
1737
|
+
// same directory with a trailing slash means the same project.
|
|
1738
|
+
if (projectKey(snapshot.projectRoot) !== projectKey(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'That session does not belong to that project');
|
|
1739
|
+
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 });
|
|
1740
|
+
// The session waits for the job before the job is written, so it is not closed
|
|
1741
|
+
// in between; the job's own hold takes over once it exists.
|
|
1742
|
+
scheduler?.holdSession(sessionId);
|
|
1743
|
+
try {
|
|
1744
|
+
const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt, keepsSession });
|
|
1745
|
+
scheduler?.hold(job);
|
|
1746
|
+
return { job };
|
|
1747
|
+
} catch (error) {
|
|
1748
|
+
throw scheduleFailed(error);
|
|
1749
|
+
} finally {
|
|
1750
|
+
scheduler?.releaseSession(sessionId);
|
|
1751
|
+
}
|
|
1752
|
+
},
|
|
1753
|
+
|
|
1754
|
+
/** The jobs of this project, oldest first by the time they are due. */
|
|
1755
|
+
async 'schedule.list'(_connection, { projectRoot, status } = {}) {
|
|
1756
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1757
|
+
// The jobs of every project live in one directory: the project is the boundary.
|
|
1758
|
+
requestedProject(projectRoot);
|
|
1759
|
+
try {
|
|
1760
|
+
return { jobs: await schedules.list({ projectRoot, status }) };
|
|
1761
|
+
} catch (error) {
|
|
1762
|
+
throw scheduleFailed(error);
|
|
1763
|
+
}
|
|
1764
|
+
},
|
|
1765
|
+
|
|
1766
|
+
/** One job, with what became of it. */
|
|
1767
|
+
async 'schedule.get'(_connection, { id, projectRoot } = {}) {
|
|
1768
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1769
|
+
if (typeof id !== 'string') throw new RpcError(RPC_ERROR.invalidParams, 'id is required');
|
|
1770
|
+
requestedProject(projectRoot);
|
|
1771
|
+
// The store keeps the project boundary itself: a job of another project is not
|
|
1772
|
+
// there for this one, whatever the caller asked for.
|
|
1773
|
+
const job = await storeJob(id, projectRoot);
|
|
1774
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1775
|
+
return { job };
|
|
1776
|
+
},
|
|
1777
|
+
|
|
1778
|
+
/** A job that will not run: cancelled before its time. */
|
|
1779
|
+
async 'schedule.cancel'(_connection, { id, projectRoot } = {}) {
|
|
1780
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1781
|
+
if (typeof id !== 'string') throw new RpcError(RPC_ERROR.invalidParams, 'id is required');
|
|
1782
|
+
requestedProject(projectRoot);
|
|
1783
|
+
const job = await storeJob(id, projectRoot);
|
|
1784
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1785
|
+
// A job that is being delivered now is not cancelled: the delivery is under way.
|
|
1786
|
+
if (scheduler?.delivering(id)) throw new RpcError(ERROR.conflict, `Job ${id} is being delivered now`, { reason: 'key_conflict' });
|
|
1787
|
+
try {
|
|
1788
|
+
const cancelled = await schedules.cancel(id, { projectRoot });
|
|
1789
|
+
scheduler?.release(cancelled);
|
|
1790
|
+
return { job: cancelled };
|
|
1791
|
+
} catch (error) {
|
|
1792
|
+
throw scheduleFailed(error);
|
|
1793
|
+
}
|
|
1794
|
+
},
|
|
1795
|
+
};
|
|
1796
|
+
const registryCall = async (run: () => Promise<any>) => {
|
|
1797
|
+
if (!registry) throw new RpcError(ERROR.unavailable, 'Registry needs ALP_HOME');
|
|
1798
|
+
try { return await run(); } catch (e) {
|
|
1799
|
+
if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data);
|
|
1800
|
+
throw new RpcError(ERROR.failed, e instanceof Error ? e.message : String(e), { reason: 'persistence_failed' });
|
|
1801
|
+
}
|
|
1000
1802
|
};
|
|
1001
|
-
|
|
1803
|
+
const registryList = async (kind: 'projects' | 'workspaces', params: any = {}) => registryCall(async () => {
|
|
1804
|
+
const r = await registry!.snapshot();
|
|
1805
|
+
const allowed = params.projectRoots;
|
|
1806
|
+
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));
|
|
1807
|
+
if (allowed !== undefined) {
|
|
1808
|
+
entries = (await Promise.all(entries.map(async e => {
|
|
1809
|
+
const directory = kind === 'projects' ? e.root : e.directory;
|
|
1810
|
+
const canonical = await fsRealpath(directory).catch(() => undefined);
|
|
1811
|
+
return canonical && (!e.canonical || canonical === e.canonical) && allowed.includes(canonical) ? e : undefined;
|
|
1812
|
+
}))).filter(Boolean);
|
|
1813
|
+
}
|
|
1814
|
+
const offset = params.cursor === undefined ? 0 : Number(params.cursor);
|
|
1815
|
+
if (!Number.isSafeInteger(offset) || offset < 0) throw new RpcError(-32602, 'Invalid registry cursor');
|
|
1816
|
+
const limit = params.limit ?? 100;
|
|
1817
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new RpcError(-32602, 'Invalid registry limit');
|
|
1818
|
+
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 };
|
|
1819
|
+
});
|
|
1820
|
+
const registryMutation = (method: string, p: any) => registryCall(async () => {
|
|
1821
|
+
if (!Number.isSafeInteger(p.ifRevision) || p.ifRevision < 0) throw new RpcError(-32602, 'ifRevision is required');
|
|
1822
|
+
const { requestId, ifRevision, authorizedRoots, ...args } = p;
|
|
1823
|
+
const result = await registry!.mutate(method, args, { requestId, ifRevision, allowedRoots: authorizedRoots });
|
|
1824
|
+
return result.workspace ? { ...result, workspace: await workspaceDescriptor(result.workspace) } : result;
|
|
1825
|
+
});
|
|
1826
|
+
runtime.bindSchedules?.(async (action, params) => handlers[`schedule.${action}`](undefined as any, params));
|
|
1827
|
+
for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (connection, params) => handler(params, { agent: connection.agent === true });
|
|
1002
1828
|
Object.setPrototypeOf(handlers, null);
|
|
1003
1829
|
// Every v1 method name stays the daemon's, served here or not, so no extension takes one.
|
|
1004
1830
|
const originalMethods = new Set([...Object.keys(handlers), ...RPC_METHODS]);
|
|
@@ -1056,7 +1882,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1056
1882
|
}
|
|
1057
1883
|
|
|
1058
1884
|
/** 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];
|
|
1885
|
+
const capabilities = [...(runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : []), CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.workspaceFilesBrowse, CAPABILITY.hostDirectories, CAPABILITY.promptImages, ...(store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : []), ...(schedules ? [CAPABILITY.schedule] : []), ...(registry ? ['workspace.registry', CAPABILITY.workspaceGit] : []), CAPABILITY.workspaceGitFacts, ...(worktrees ? ['workspace.worktree'] : []), ...(attachments ? [CAPABILITY.attachments] : []), ...(conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : []), ...(conversation?.reloads ? [CAPABILITY.sessionReload] : []), ...(conversation?.configures ? [CAPABILITY.sessionConfigureLive] : []), ...(conversation ? [CAPABILITY.sessionResumeCommand] : []), ...(modelCatalog ? [CAPABILITY.catalogLive] : []), ...operations.capabilities];
|
|
1060
1886
|
|
|
1061
1887
|
/** A response too large for the wire becomes an error the client can read. */
|
|
1062
1888
|
function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
|
|
@@ -1107,7 +1933,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1107
1933
|
const issues = validateParams(method, params)!;
|
|
1108
1934
|
if (issues.length) throw invalidParams(issues);
|
|
1109
1935
|
connection.helloed = true;
|
|
1110
|
-
|
|
1936
|
+
// Sticky: a later hello never sheds it.
|
|
1937
|
+
connection.agent = connection.agent === true || (Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY));
|
|
1938
|
+
if (typeof params?.client?.name === 'string') connection.client = params.client.name;
|
|
1939
|
+
// Terminals are listed only while the host's switch is on (and the PTY module loads).
|
|
1940
|
+
const terminalLimits = await terminals?.advertised();
|
|
1941
|
+
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities: terminalLimits ? [...capabilities, CAPABILITY.terminal, CAPABILITY.terminalCapture, CAPABILITY.terminalWatch] : capabilities, ...(attachments ? { attachmentLimits: attachments.limits } : {}), ...(terminalLimits ? { terminalLimits } : {}) } });
|
|
1111
1942
|
return;
|
|
1112
1943
|
}
|
|
1113
1944
|
if (!connection.helloed) throw new RpcError(ERROR.protocol, 'daemon.hello is required first', { reason: 'hello_required' });
|
|
@@ -1144,6 +1975,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1144
1975
|
}
|
|
1145
1976
|
connections.delete(connection);
|
|
1146
1977
|
watchers.delete(connection);
|
|
1978
|
+
terminals?.disconnect(connection);
|
|
1147
1979
|
for (const root of [...connection.roots]) {
|
|
1148
1980
|
detach(connection, root);
|
|
1149
1981
|
void reap(root);
|
|
@@ -1254,6 +2086,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1254
2086
|
|
|
1255
2087
|
local() {
|
|
1256
2088
|
const events = new Set<(envelope: Envelope) => void>();
|
|
2089
|
+
const notifications = new Set<(method: string, params: any) => void>();
|
|
1257
2090
|
const closes = new Set<(error: Error) => void>();
|
|
1258
2091
|
const pending = new Map<number, { resolve: (value: any) => void; reject: (error: Error) => void }>();
|
|
1259
2092
|
let sequence = 0;
|
|
@@ -1268,6 +2101,11 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1268
2101
|
for (const listener of events) listener(message.params);
|
|
1269
2102
|
return;
|
|
1270
2103
|
}
|
|
2104
|
+
// Other notifications (terminal.event, §12.10) carry a method and no id.
|
|
2105
|
+
if (typeof message.method === 'string' && message.id === undefined) {
|
|
2106
|
+
for (const listener of notifications) listener(message.method, message.params);
|
|
2107
|
+
return;
|
|
2108
|
+
}
|
|
1271
2109
|
const waiter = pending.get(message.id);
|
|
1272
2110
|
if (!waiter) return;
|
|
1273
2111
|
pending.delete(message.id);
|
|
@@ -1286,6 +2124,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1286
2124
|
});
|
|
1287
2125
|
},
|
|
1288
2126
|
onEvent(listener) { events.add(listener); return () => events.delete(listener); },
|
|
2127
|
+
onNotification(listener) { notifications.add(listener); return () => notifications.delete(listener); },
|
|
1289
2128
|
onClose(listener) { closes.add(listener); return () => closes.delete(listener); },
|
|
1290
2129
|
close() {
|
|
1291
2130
|
if (ended) return;
|
|
@@ -1316,8 +2155,15 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1316
2155
|
},
|
|
1317
2156
|
|
|
1318
2157
|
async close() {
|
|
2158
|
+
unsubscribeCatalog?.();
|
|
1319
2159
|
closing = true;
|
|
1320
2160
|
if (sweeper) clearInterval(sweeper);
|
|
2161
|
+
await attachments?.close();
|
|
2162
|
+
// Every terminal ends with alpd, its whole process tree killed.
|
|
2163
|
+
await terminals?.shutdown();
|
|
2164
|
+
// The tick that runs now is waited for: a delivery under way finishes, so its
|
|
2165
|
+
// receipt is written and the job is not left half delivered.
|
|
2166
|
+
await scheduler?.stop();
|
|
1321
2167
|
const stopped = new Promise<void>(resolve => server.close(() => resolve()));
|
|
1322
2168
|
for (const connection of connections) connection.socket?.destroy();
|
|
1323
2169
|
await stopped;
|