@anhlp/alp-daemon 0.0.0-stage → 0.0.1-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +14 -2
- package/dist/THIRD-PARTY-NOTICES.txt +431 -0
- package/dist/alp-templates.d.ts +5 -0
- package/dist/alpd.js +49562 -0
- package/dist/attachments.d.ts +211 -0
- package/dist/attachments.js +819 -0
- package/dist/build-manifest.json +131 -0
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +672 -0
- package/dist/files.d.ts +123 -0
- package/dist/files.js +365 -0
- package/dist/git.d.ts +87 -0
- package/dist/git.js +1093 -0
- package/dist/gitignore.d.ts +62 -0
- package/dist/gitignore.js +254 -0
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +25 -0
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/lock.d.ts +21 -0
- package/dist/lock.js +42 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +277 -0
- package/dist/operations.d.ts +23 -0
- package/dist/operations.js +275 -0
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/rpc-error.d.ts +6 -0
- package/dist/rpc-error.js +11 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +290 -0
- package/dist/schedules.d.ts +69 -0
- package/dist/schedules.js +244 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +1780 -0
- package/dist/store.d.ts +176 -0
- package/dist/store.js +385 -0
- package/dist/terminals.d.ts +157 -0
- package/dist/terminals.js +487 -0
- package/dist/worktrees.d.ts +41 -0
- package/dist/worktrees.js +246 -0
- package/package.json +159 -4
- package/src/alp-templates.d.ts +5 -0
- package/src/attachments.ts +870 -0
- package/src/conversation.ts +837 -0
- package/src/files.ts +459 -0
- package/src/git.ts +1045 -0
- package/src/gitignore.ts +277 -0
- package/src/history.ts +118 -0
- package/src/index.ts +11 -0
- package/src/lifecycle.ts +283 -0
- package/src/lock.ts +53 -0
- package/src/main.ts +292 -0
- package/src/operations.ts +300 -0
- package/src/registry.ts +238 -0
- package/src/rpc-error.ts +4 -0
- package/src/scheduler.ts +422 -0
- package/src/schedules.ts +294 -0
- package/src/server.ts +2056 -0
- package/src/store.ts +448 -0
- package/src/terminals.ts +591 -0
- package/src/worktrees.ts +287 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,2056 @@
|
|
|
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';
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
6
|
+
import { appendFile, chmod, mkdir, readFile, unlink, lstat, rename } from 'node:fs/promises';
|
|
7
|
+
import net from 'node:net';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import { assertPrivateDirectory, assertPrivateSocket } from '@anhlp/alp-client/index';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { createLogger } from '@anhlp/alp-core/log';
|
|
12
|
+
import { AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from '@anhlp/alp-protocol';
|
|
13
|
+
import { validateParams } from '@anhlp/alp-protocol/contract';
|
|
14
|
+
export { ERROR } from '@anhlp/alp-protocol';
|
|
15
|
+
import { DEFAULT_MODEL, models, modes, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
|
|
16
|
+
import type { Receipt, SessionRecord, SessionStatus, Store, UnreadableReceipt } from './store.js';
|
|
17
|
+
import type { PromptContent, SessionSummary } from '@anhlp/alp-protocol/session';
|
|
18
|
+
import type { ScheduleJob, TurnAttention } from '@anhlp/alp-protocol/index';
|
|
19
|
+
import { RpcError } from './rpc-error.js';
|
|
20
|
+
import { createOperations, type OperationsOptions } from './operations.js';
|
|
21
|
+
import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from './files.js';
|
|
22
|
+
import { createGitReader } from './git.js';
|
|
23
|
+
import { createScheduleStore, projectKey } from './schedules.js';
|
|
24
|
+
import { createAttachmentStore, type AttachmentRuntime, type AttachmentStoreOptions, type Principal } from './attachments.js';
|
|
25
|
+
import type { RuntimeAttachment } from '@anhlp/alp-protocol/session';
|
|
26
|
+
import { clientMessageId as scheduleMessageId, createScheduler, SCHEDULE_TICK_MS, type ScheduleDelivery } from './scheduler.js';
|
|
27
|
+
import { createLifecycleJournal, LIFECYCLE_RETENTION_MS } from './lifecycle.js';
|
|
28
|
+
import { createConversation } from './conversation.js';
|
|
29
|
+
import { createTerminalService, type TerminalServiceOptions } from './terminals.js';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* alpd's JSON-RPC surface over one shared runtime (plans/reference/ALPD.md §3, §6, §14).
|
|
33
|
+
* Clients attach to root sessions to receive the events of the whole tree. A root
|
|
34
|
+
* with no attached client is closed as soon as it is idle, so work started by a
|
|
35
|
+
* viewer finishes even after the viewer goes away. With a store, every session is
|
|
36
|
+
* recorded and every tree's events are kept, so a closed root can be resumed later.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
const log = createLogger({ component: 'alpd.ipc' });
|
|
42
|
+
const recoveryLog = createLogger({ component: 'alpd.recovery' });
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
/** A request id v1 accepts: a string of at most 128 characters or a safe integer (docs/protocol/alp-json-rpc-v1.md §3). */
|
|
46
|
+
function validId(id: unknown): id is string | number {
|
|
47
|
+
if (typeof id !== 'string') return Number.isSafeInteger(id);
|
|
48
|
+
let length = 0;
|
|
49
|
+
for (const _point of id) if (++length > 128) return false;
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The bytes a frame takes on a newline-delimited stream, its newline included. */
|
|
54
|
+
const frameBytes = (message: unknown) => Buffer.byteLength(encodeFrame(message), 'utf8');
|
|
55
|
+
|
|
56
|
+
const invalidParams = (issues: Array<{ path: string; message: string }>) =>
|
|
57
|
+
new RpcError(RPC_ERROR.invalidParams, `Invalid params: ${issues.map(issue => `${issue.path || 'params'} ${issue.message}`).join('; ')}`, { reason: 'invalid_params', issues });
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Crash points for the crash-recovery tests (ALPD §66): with ALP_TEST_CRASH_AT naming one,
|
|
61
|
+
* alpd kills itself there as a crash would. Unset, they do nothing.
|
|
62
|
+
*/
|
|
63
|
+
function crashPoint(name: string) {
|
|
64
|
+
if (process.env.ALP_TEST_CRASH_AT !== name) return;
|
|
65
|
+
createLogger({ component: 'alpd' }).error(`ALP_TEST_CRASH_AT=${name}: killing alpd`, { code: 'ALP_TEST_CRASH' });
|
|
66
|
+
process.kill(process.pid, 'SIGKILL');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const persistenceFailed = (what: string, error: unknown) =>
|
|
70
|
+
new RpcError(ERROR.failed, `alpd could not record ${what}: ${error instanceof Error ? error.message : String(error)}`, { reason: 'persistence_failed' });
|
|
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
|
+
|
|
109
|
+
/** A stable hash of JSON data, independent of key order (as Paseo's receipts). */
|
|
110
|
+
function digest(value: unknown) {
|
|
111
|
+
return createHash('sha256').update(JSON.stringify(value, (_key, candidate) =>
|
|
112
|
+
candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)
|
|
113
|
+
? Object.fromEntries(Object.entries(candidate).sort(([a], [b]) => a.localeCompare(b)))
|
|
114
|
+
: candidate)).digest('hex');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
type Connection = {
|
|
118
|
+
socket?: net.Socket;
|
|
119
|
+
helloed: boolean;
|
|
120
|
+
roots: Set<string>;
|
|
121
|
+
send(message: unknown): void;
|
|
122
|
+
nextId: number;
|
|
123
|
+
pending: Map<number, { resolve(value: unknown): void; reject(error: Error): void; timer: NodeJS.Timeout; caller: Connection }>;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** Retained events per live tree, for attach and replay. */
|
|
127
|
+
const TREE_LOG_LIMIT = 20_000;
|
|
128
|
+
const SESSION_ID = /^[\w.:-]{1,128}$/;
|
|
129
|
+
const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
130
|
+
const RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
131
|
+
/** How often a running alpd applies retention, besides at start (ALPD §68). */
|
|
132
|
+
const RETENTION_SWEEP_MS = 6 * 60 * 60 * 1000;
|
|
133
|
+
const LIVE: SessionStatus[] = ['initializing', 'idle', 'running'];
|
|
134
|
+
const PROMPT_TITLE_CHARS = 60;
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* A root's name from its first prompt, as Paseo names an agent (server/agent/create-agent-title.ts
|
|
138
|
+
* at b63a325): the first non-blank line, whitespace folded, at most 60 characters, no ellipsis.
|
|
139
|
+
* Counted in code points, where Paseo counts UTF-16 units, so a cut never splits a character.
|
|
140
|
+
*/
|
|
141
|
+
function titleFromPrompt(text: string): string | undefined {
|
|
142
|
+
const line = text.split(/\r?\n/).map(entry => entry.replace(/\s+/g, ' ').trim()).find(Boolean);
|
|
143
|
+
return line ? [...line].slice(0, PROMPT_TITLE_CHARS).join('').trim() || undefined : undefined;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Whether a message is the user's own words, which alone may name a root: ALP's mail, briefs,
|
|
148
|
+
* resumes and scheduled jobs (`alp-` ids) never do. A runtime says who wrote it in `origin`;
|
|
149
|
+
* without it, only a message a client sent (its clientMessageId) counts, so a replayed message
|
|
150
|
+
* nobody can place does not.
|
|
151
|
+
*/
|
|
152
|
+
function fromUser(item: { origin?: string; clientMessageId?: string }) {
|
|
153
|
+
if (item.clientMessageId?.startsWith('alp-')) return false;
|
|
154
|
+
return item.origin !== undefined ? item.origin === 'user' : item.clientMessageId !== undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* session.list's order and its keyset cursor: roots before children, the latest `updatedAt`
|
|
159
|
+
* first, then by id, so a page continues after the last session it holds, as Paseo's history pages
|
|
160
|
+
* (server/pagination/sortable-pager.ts at b63a325). The cursor is opaque to clients.
|
|
161
|
+
*/
|
|
162
|
+
type ListKey = [child: 0 | 1, updatedAt: string, id: string];
|
|
163
|
+
const listCursor = {
|
|
164
|
+
key: (session: SessionSummary): ListKey => [session.parentId ? 1 : 0, session.updatedAt ?? '', session.id],
|
|
165
|
+
compare([childA, updatedA, idA]: ListKey, [childB, updatedB, idB]: ListKey) {
|
|
166
|
+
return childA - childB || (updatedA === updatedB ? 0 : updatedA < updatedB ? 1 : -1) || (idA === idB ? 0 : idA < idB ? -1 : 1);
|
|
167
|
+
},
|
|
168
|
+
encode: (key: ListKey) => Buffer.from(JSON.stringify(key), 'utf8').toString('base64url'),
|
|
169
|
+
decode(cursor: string): ListKey {
|
|
170
|
+
let key: unknown;
|
|
171
|
+
try { key = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')); } catch {}
|
|
172
|
+
if (!Array.isArray(key) || key.length !== 3 || (key[0] !== 0 && key[0] !== 1) || typeof key[1] !== 'string' || typeof key[2] !== 'string') {
|
|
173
|
+
throw new RpcError(RPC_ERROR.invalidParams, 'cursor is not one session.list answered', { reason: 'invalid_params' });
|
|
174
|
+
}
|
|
175
|
+
return key as ListKey;
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/** What clients need from a daemon connection; AlpClient implements it over the socket. */
|
|
180
|
+
import type { DaemonConnection } from '@anhlp/alp-protocol/connection';
|
|
181
|
+
export type { DaemonConnection } from '@anhlp/alp-protocol/connection';
|
|
182
|
+
|
|
183
|
+
export type DaemonServer = {
|
|
184
|
+
listen(): Promise<void>;
|
|
185
|
+
/** An in-process connection that delivers events synchronously, for embedding. */
|
|
186
|
+
local(): DaemonConnection;
|
|
187
|
+
/**
|
|
188
|
+
* A connection over another transport, such as the web app's WebSocket (ALPD §61):
|
|
189
|
+
* it says daemon.hello first, as a socket client does, and gets JSON-RPC messages back through `send`.
|
|
190
|
+
*/
|
|
191
|
+
accept(send: (message: unknown) => void): { receive(message: unknown): void; close(): void };
|
|
192
|
+
/** Adds a method that lives outside the runtime, such as the web app's pairing link (ALPD §64). */
|
|
193
|
+
extend(method: string, handler: (params: any) => Promise<unknown> | unknown): void;
|
|
194
|
+
close(): Promise<void>;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
/** A session as clients list it: its last snapshot plus lifecycle (ALPD §18). The protocol owns the
|
|
198
|
+
* shape so every viewer agrees; re-exported here to keep `@anhlp/alp-daemon/server`'s API. */
|
|
199
|
+
export type { SessionSummary };
|
|
200
|
+
|
|
201
|
+
export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions }: {
|
|
202
|
+
runtime: AlpRuntime;
|
|
203
|
+
socketPath: string;
|
|
204
|
+
version: string;
|
|
205
|
+
onShutdown?: () => void;
|
|
206
|
+
/** Durable records and timelines; without it sessions live only in memory. */
|
|
207
|
+
store?: Store;
|
|
208
|
+
/** Where crash reconciliation reports assignments it ends, as the runtime does. */
|
|
209
|
+
runLogDir?: string;
|
|
210
|
+
/** How the previous alpd ended, for daemon.status. */
|
|
211
|
+
previousExit?: { kind: 'clean' | 'crash'; at?: string };
|
|
212
|
+
/** How often retention runs while alpd runs (ALPD §68); tests shorten it. */
|
|
213
|
+
retentionSweepMs?: number;
|
|
214
|
+
/** The daemon user's ALP_HOME, for the library, team and settings methods; without it alpd does not serve them. */
|
|
215
|
+
home?: OperationsOptions['home'];
|
|
216
|
+
/** ALP's built-in agents and teams, for the library and team methods. */
|
|
217
|
+
templates?: OperationsOptions['templates'];
|
|
218
|
+
/** How often the scheduler looks for jobs whose time has come; tests shorten it. */
|
|
219
|
+
scheduleTickMs?: number;
|
|
220
|
+
/** How long a job's delivery may take; tests shorten it. */
|
|
221
|
+
scheduleDeliveryTimeoutMs?: number;
|
|
222
|
+
/** Lower attachment limits (an operator's, never higher than ATTACHMENTS) and test hooks. */
|
|
223
|
+
attachmentOptions?: Partial<Pick<AttachmentStoreOptions, 'limits' | 'now' | 'io' | 'sweepMs'>>;
|
|
224
|
+
/** Lower terminal limits (never higher than TERMINAL or the operator's) and test hooks. */
|
|
225
|
+
terminalOptions?: Partial<Pick<TerminalServiceOptions, 'limits' | 'now' | 'spawn' | 'processes' | 'sweepMs' | 'killGraceMs' | 'maxBufferedBytes' | 'platform'>>;
|
|
226
|
+
}): DaemonServer {
|
|
227
|
+
const connections = new Set<Connection>();
|
|
228
|
+
/** Root of every live session. */
|
|
229
|
+
const rootOf = new Map<string, string>();
|
|
230
|
+
const attached = new Map<string, Set<Connection>>();
|
|
231
|
+
const logs = new Map<string, Envelope[]>();
|
|
232
|
+
const records = new Map<string, SessionRecord & { activeTurnId?: string }>();
|
|
233
|
+
/** Prompt deliveries in flight, so a repeated clientMessageId waits for the first. */
|
|
234
|
+
const delivering = new Map<string, Promise<object>>();
|
|
235
|
+
/** Completed deliveries whose receipt could not be written; this process still answers them. */
|
|
236
|
+
const unsaved = new Map<string, Receipt>();
|
|
237
|
+
/** The last timeline cursor of each tree (ALPD §66). */
|
|
238
|
+
const cursors = new Map<string, number>();
|
|
239
|
+
let closing = false;
|
|
240
|
+
let socketIdentity: { dev: number; ino: number } | undefined;
|
|
241
|
+
/** Roots alpd reopens after a restart; they stay open until their recovery has started. */
|
|
242
|
+
const recovering = new Map<string, Promise<void>>();
|
|
243
|
+
const startedAt = new Date().toISOString();
|
|
244
|
+
/** The clock of this daemon: the job store and the scheduler share it. */
|
|
245
|
+
const clock = () => Date.now();
|
|
246
|
+
/**
|
|
247
|
+
* The scheduled continuations of this host; their own directory, beside the state.
|
|
248
|
+
* They need the prompt receipt (the store) to deliver a job at most once, so a
|
|
249
|
+
* daemon without a store serves no jobs at all.
|
|
250
|
+
*/
|
|
251
|
+
const schedules = home && store ? createScheduleStore(path.join(home, 'schedules'), { now: clock }) : undefined;
|
|
252
|
+
/**
|
|
253
|
+
* The job of that id in that project: the store keeps the project boundary, and a
|
|
254
|
+
* refusal of the store is answered like one of the daemon's own.
|
|
255
|
+
*/
|
|
256
|
+
const storeJob = async (id: string, projectRoot: string) => {
|
|
257
|
+
if (!schedules) return undefined;
|
|
258
|
+
try { return await schedules.get(id, { projectRoot }); }
|
|
259
|
+
catch (error) { throw scheduleFailed(error); }
|
|
260
|
+
};
|
|
261
|
+
/**
|
|
262
|
+
* Non-image attachments (§12.6): with a home and a store (prompt receipts pin their references),
|
|
263
|
+
* never on Windows (no O_NOFOLLOW, no POSIX modes: not a supported platform for them).
|
|
264
|
+
*/
|
|
265
|
+
const attachments = home && store && process.platform !== 'win32' ? createAttachmentStore({
|
|
266
|
+
root: path.join(home, 'state', 'attachments'),
|
|
267
|
+
sessionProject: sessionId => runtime.snapshot(sessionId)?.projectRoot ?? records.get(sessionId)?.session?.projectRoot,
|
|
268
|
+
crashPoint,
|
|
269
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
270
|
+
// A collected object's staged copy goes with it.
|
|
271
|
+
onDiscard: attachmentId => (runtime as AlpRuntime & AttachmentRuntime).dropAttachment?.(attachmentId),
|
|
272
|
+
...attachmentOptions,
|
|
273
|
+
}) : undefined;
|
|
274
|
+
// The runtime side of the seam (issue #121 branch J): a runtime that takes attachment parts reads them through this.
|
|
275
|
+
(runtime as AlpRuntime & AttachmentRuntime).bindAttachments?.(attachments?.reader);
|
|
276
|
+
/**
|
|
277
|
+
* Gates of roots whose conversation a lifecycle operation changes (a rewind): prompts, scheduled
|
|
278
|
+
* deliveries and reopens of the root wait until it is through (§12.7).
|
|
279
|
+
*/
|
|
280
|
+
const holds = new Map<string, { count: number; open: Promise<void>; release: () => void }>();
|
|
281
|
+
// Conservatively invalidate in-flight attach reads even when a lifecycle hold ends during I/O.
|
|
282
|
+
let holdRevision = 0;
|
|
283
|
+
function holdPrompts(root: string) {
|
|
284
|
+
holdRevision++;
|
|
285
|
+
let gate = holds.get(root);
|
|
286
|
+
if (!gate) {
|
|
287
|
+
let release!: () => void;
|
|
288
|
+
const open = new Promise<void>(resolve => { release = resolve; });
|
|
289
|
+
gate = { count: 0, open, release };
|
|
290
|
+
holds.set(root, gate);
|
|
291
|
+
}
|
|
292
|
+
gate.count++;
|
|
293
|
+
const held = gate;
|
|
294
|
+
let released = false;
|
|
295
|
+
return () => {
|
|
296
|
+
if (released) return;
|
|
297
|
+
released = true;
|
|
298
|
+
if (--held.count === 0) { if (holds.get(root) === held) holds.delete(root); held.release(); }
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
/** Prompt deliveries in flight per root: a rewind refuses while one is on its way. */
|
|
302
|
+
const promptsInFlight = new Map<string, number>();
|
|
303
|
+
const rootIdOf = (sessionId: string) => rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
304
|
+
/** Waits while the root's conversation is being changed, then counts a delivery in flight until `run` settles. */
|
|
305
|
+
async function gated<T>(sessionId: string, run: () => Promise<T>): Promise<T> {
|
|
306
|
+
const root = rootIdOf(sessionId);
|
|
307
|
+
while (holds.has(root)) await holds.get(root)!.open;
|
|
308
|
+
refuseFenced(root);
|
|
309
|
+
promptsInFlight.set(root, (promptsInFlight.get(root) ?? 0) + 1);
|
|
310
|
+
try { return await run(); }
|
|
311
|
+
finally {
|
|
312
|
+
const left = (promptsInFlight.get(root) ?? 1) - 1;
|
|
313
|
+
if (left > 0) promptsInFlight.set(root, left); else promptsInFlight.delete(root);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/** A root whose rewind is applied but not committed takes no prompt or reopen until that rewind is sent again. */
|
|
317
|
+
function fencedRoot(root: string): string | undefined { return conversation?.fenced(root); }
|
|
318
|
+
function refuseFenced(root: string) {
|
|
319
|
+
const requestId = fencedRoot(root);
|
|
320
|
+
if (requestId !== undefined) throw new RpcError(ERROR.conflict, `A rewind of this session is not finished; send session.rewind again with requestId ${requestId}`, { reason: 'session_busy' });
|
|
321
|
+
}
|
|
322
|
+
/** Forks and rewinds of Codex and Claude conversations (§12.7): with a store, through the lifecycle journal. */
|
|
323
|
+
const journal = store ? createLifecycleJournal(path.join(store.root, 'lifecycle')) : undefined;
|
|
324
|
+
const conversation: ReturnType<typeof createConversation> | undefined = store && journal ? createConversation({
|
|
325
|
+
runtime, store, journal, records, cursors, logs, treeLogLimit: TREE_LOG_LIMIT,
|
|
326
|
+
summary: id => summary(id), digest,
|
|
327
|
+
unsettled: (root): string | undefined => fencedRoot(root) ? 'a rewind of it is not finished; send that rewind again'
|
|
328
|
+
: recovering.has(root) ? 'it is being reopened after a restart'
|
|
329
|
+
: openingSessions.has(root) ? 'it is opening'
|
|
330
|
+
: promptsInFlight.get(root) ? 'a prompt is being delivered' : undefined,
|
|
331
|
+
holdPrompts,
|
|
332
|
+
broadcast: (root, envelope) => { for (const connection of attached.get(root) ?? []) deliver(connection, envelope); },
|
|
333
|
+
get registry() { return registry; },
|
|
334
|
+
get worktrees() { return worktrees; },
|
|
335
|
+
attachments,
|
|
336
|
+
crashPoint,
|
|
337
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
338
|
+
startedAt,
|
|
339
|
+
}) : undefined;
|
|
340
|
+
/** The daemon's own start-up; the scheduler waits for it before it delivers. */
|
|
341
|
+
let restored: Promise<unknown> = Promise.resolve();
|
|
342
|
+
/**
|
|
343
|
+
* The sessions the recovery is opening again, and the ones it could not open. A job
|
|
344
|
+
* that waits for such a session waits for it, and a session that could not be opened
|
|
345
|
+
* fails the job with the reason.
|
|
346
|
+
*/
|
|
347
|
+
const openingSessions = new Map<string, number>();
|
|
348
|
+
const recoveryErrors = new Map<string, string>();
|
|
349
|
+
/** A session is being opened again; two opens at once are counted, not overwritten. */
|
|
350
|
+
const markOpening = (sessionId: string) => openingSessions.set(sessionId, (openingSessions.get(sessionId) ?? 0) + 1);
|
|
351
|
+
/** The session is open again (or was never open): the next open is counted anew. */
|
|
352
|
+
const clearOpening = (sessionId: string) => {
|
|
353
|
+
const count = (openingSessions.get(sessionId) ?? 0) - 1;
|
|
354
|
+
if (count > 0) openingSessions.set(sessionId, count);
|
|
355
|
+
else openingSessions.delete(sessionId);
|
|
356
|
+
};
|
|
357
|
+
/**
|
|
358
|
+
* The reason a session could not be opened again belongs to the jobs that wait for
|
|
359
|
+
* that session: a reason no job needs is no reason at all, and the map of them must
|
|
360
|
+
* not grow with the number of sessions.
|
|
361
|
+
*/
|
|
362
|
+
function keepRecoveryError(sessionId: string, message: string) {
|
|
363
|
+
if (scheduler?.holds(sessionId)) recoveryErrors.set(sessionId, message);
|
|
364
|
+
}
|
|
365
|
+
/** The reason is dropped when the last job that needed it is through. */
|
|
366
|
+
function dropRecoveryError(sessionId: string) {
|
|
367
|
+
if (!scheduler?.holds(sessionId)) recoveryErrors.delete(sessionId);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* The tick that delivers the jobs whose time has come.
|
|
371
|
+
*/
|
|
372
|
+
const scheduler = schedules ? createScheduler({
|
|
373
|
+
store: schedules,
|
|
374
|
+
runtime,
|
|
375
|
+
deliver: deliverJob,
|
|
376
|
+
ready: () => restored,
|
|
377
|
+
session: sessionId => openingSessions.has(sessionId)
|
|
378
|
+
? { opening: true }
|
|
379
|
+
: recoveryErrors.has(sessionId)
|
|
380
|
+
? { error: { message: `The session this job continues could not be opened again: ${recoveryErrors.get(sessionId)}`, code: 'session_open_failed' } }
|
|
381
|
+
: undefined,
|
|
382
|
+
settled: sessionId => dropRecoveryError(sessionId),
|
|
383
|
+
stopping: () => closing,
|
|
384
|
+
now: clock,
|
|
385
|
+
...(scheduleDeliveryTimeoutMs === undefined ? {} : { deliveryTimeoutMs: scheduleDeliveryTimeoutMs }),
|
|
386
|
+
}) : undefined;
|
|
387
|
+
restored = store ? restore() : Promise.resolve();
|
|
388
|
+
|
|
389
|
+
const deliver = (connection: Connection, envelope: Envelope) => {
|
|
390
|
+
const message = { jsonrpc: '2.0', method: 'event', params: envelope };
|
|
391
|
+
// Stable events too large for transport still advance the replay position explicitly.
|
|
392
|
+
const bytes = frameBytes(message);
|
|
393
|
+
if (bytes > 512 * 1024 && envelope.cursor !== undefined) message.params = {
|
|
394
|
+
...envelope, event: { type: 'item', item: { kind: 'notice', id: `oversized:${envelope.cursor}`, level: 'warning', text: `History event ${envelope.cursor} is too large to display (${bytes} bytes).` } },
|
|
395
|
+
};
|
|
396
|
+
connection.send(message);
|
|
397
|
+
};
|
|
398
|
+
/** Connections that called question.watch, with the projectRoot they asked for and whether they want roots' turn ends and attention. */
|
|
399
|
+
const watchers = new Map<Connection, { projectRoot?: string; turns: boolean; attention: boolean }>();
|
|
400
|
+
|
|
401
|
+
/** The project of a tree, live or recorded. */
|
|
402
|
+
function projectOf(root: string) {
|
|
403
|
+
return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Tells watchers not attached to the tree of a question asked or resolved there, or, for those
|
|
408
|
+
* that asked for `turns`, of the end of a root's turn. Their copy has no `cursor`: it is not part
|
|
409
|
+
* of a timeline they replay (docs/protocol/alp-json-rpc-v1.md §8.1, §12.2).
|
|
410
|
+
*/
|
|
411
|
+
function tellWatchers(root: string, envelope: Envelope, turn = false) {
|
|
412
|
+
if (!watchers.size) return;
|
|
413
|
+
const { cursor: _cursor, ...announced } = envelope;
|
|
414
|
+
const project = projectOf(root);
|
|
415
|
+
for (const [connection, { projectRoot, turns }] of watchers) {
|
|
416
|
+
if (turn && !turns) continue;
|
|
417
|
+
if (attached.get(root)?.has(connection)) continue;
|
|
418
|
+
if (projectRoot !== undefined && project !== projectRoot) continue;
|
|
419
|
+
deliver(connection, announced);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Tells the connections watching attention that a root's changed: `attention` when set, none when
|
|
425
|
+
* cleared. Never kept: a client reads the current ones from question.watch (§12.2), so a change
|
|
426
|
+
* missed while it was away is not lost.
|
|
427
|
+
*/
|
|
428
|
+
function tellAttention(root: string, attention: TurnAttention | undefined) {
|
|
429
|
+
if (!watchers.size) return;
|
|
430
|
+
const project = projectOf(root);
|
|
431
|
+
const envelope: Envelope = { sessionId: root, epoch: `attention-${startedAt}`, seq: 0, ts: new Date().toISOString(), event: { type: 'attention', ...(attention ? { attention } : {}) } };
|
|
432
|
+
for (const [connection, watch] of watchers) {
|
|
433
|
+
if (!watch.attention) continue;
|
|
434
|
+
if (watch.projectRoot !== undefined && project !== watch.projectRoot) continue;
|
|
435
|
+
deliver(connection, envelope);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* The acknowledgement of each root whose write is on its way. Whatever else can change a root's
|
|
441
|
+
* attention (a turn of the root starting or ending, archiving) drops it, so a failed write brings
|
|
442
|
+
* the attention back only when nothing changed it meanwhile; it lives no longer than the write.
|
|
443
|
+
*/
|
|
444
|
+
const pendingAcks = new Map<string, object>();
|
|
445
|
+
|
|
446
|
+
/** The attention of the roots of `projectRoot` (every project when absent): archived roots never ask. */
|
|
447
|
+
function attentionOf(projectRoot?: string) {
|
|
448
|
+
const found: Array<{ sessionId: string; attention: TurnAttention }> = [];
|
|
449
|
+
for (const record of records.values()) {
|
|
450
|
+
if (record.id !== record.rootId || !record.attention || record.archived) continue;
|
|
451
|
+
if (projectRoot !== undefined && projectOf(record.id) !== projectRoot) continue;
|
|
452
|
+
found.push({ sessionId: record.id, attention: record.attention });
|
|
453
|
+
}
|
|
454
|
+
return found;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Records a change; the write is queued, and a failure is logged and counted in daemon.status. */
|
|
458
|
+
function save(record: SessionRecord & { activeTurnId?: string }, changes: Partial<SessionRecord & { activeTurnId?: string }> = {}) {
|
|
459
|
+
Object.assign(record, changes, { updatedAt: new Date().toISOString() });
|
|
460
|
+
records.set(record.id, record);
|
|
461
|
+
return store?.put(record).catch(() => {}) ?? Promise.resolve();
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Gives an envelope of a tree its next cursor and queues it for the tree's timeline. */
|
|
465
|
+
function keep(root: string, envelope: Envelope): Envelope {
|
|
466
|
+
const cursor = (cursors.get(root) ?? 0) + 1;
|
|
467
|
+
cursors.set(root, cursor);
|
|
468
|
+
const kept = { ...envelope, cursor };
|
|
469
|
+
void store?.append(root, kept).catch(() => {});
|
|
470
|
+
return kept;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Continues a tree's cursors after what its stored timeline already holds. */
|
|
474
|
+
function seen(root: string, log: Envelope[]) {
|
|
475
|
+
const last = log.at(-1)?.cursor ?? 0;
|
|
476
|
+
if (last > (cursors.get(root) ?? 0)) cursors.set(root, last);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** Lifecycle bookkeeping for one event; returns true when it named the root. */
|
|
480
|
+
function track(sessionId: string, root: string, event: AlpEvent): boolean {
|
|
481
|
+
const now = new Date().toISOString();
|
|
482
|
+
let record = records.get(sessionId);
|
|
483
|
+
if (event.type === 'session.opened') {
|
|
484
|
+
record ??= { version: 1, id: sessionId, rootId: root, status: 'initializing', createdAt: now, updatedAt: now };
|
|
485
|
+
// A reopened session keeps its last usage until its runtime reports again.
|
|
486
|
+
const usage = event.session.usage ?? record.session?.usage;
|
|
487
|
+
// Recovery has not yet restored runtime parking when session.opened arrives.
|
|
488
|
+
const parked = recovering.has(root) ? record.session?.parked : event.session.parked;
|
|
489
|
+
save(record, { rootId: root, session: { ...event.session, ...(usage ? { usage } : {}), ...(parked ? { parked } : {}) }, status: 'idle', lastError: undefined, activeTurnId: undefined });
|
|
490
|
+
return false;
|
|
491
|
+
}
|
|
492
|
+
if (!record) return false;
|
|
493
|
+
if (event.type === 'session.updated') save(record, { session: { ...record.session, ...event.session, ...(event.session.parked ? {} : { parked: undefined }) } });
|
|
494
|
+
// Work on an archived session brings it back.
|
|
495
|
+
// A root's new turn ends the attention of its last one, as Paseo clears it then.
|
|
496
|
+
else if (event.type === 'turn.started') save(record, { status: 'running', activeTurnId: event.turnId, archived: undefined, ...(sessionId === root ? { attention: undefined } : {}) });
|
|
497
|
+
else if (event.type === 'turn.ended') save(record, { status: 'idle', activeTurnId: undefined,
|
|
498
|
+
// A root's turn that completed or failed asks every client for a look until one acknowledges it (Paseo's checkAndSetAttention).
|
|
499
|
+
...(sessionId === root ? { attention: turnAttention(event) } : {}),
|
|
500
|
+
...(record.session ? { session: { ...record.session, parked: event.state === 'failed' ? runtime.snapshot(sessionId)?.parked : undefined } } : {}),
|
|
501
|
+
...(event.state === 'failed' ? { lastError: { message: event.error?.message ?? 'Turn failed' } } : {}) });
|
|
502
|
+
// The latest usage, for a closed session's summary; written with the record's next change.
|
|
503
|
+
else if (event.type === 'usage' && record.session) record.session = { ...record.session, usage: event.usage };
|
|
504
|
+
else if (event.type === 'session.failed') save(record, { status: 'error', lastError: event.error });
|
|
505
|
+
else if (event.type === 'session.closed') save(record, { status: record.status === 'error' ? 'error' : 'closed', activeTurnId: undefined });
|
|
506
|
+
else if (event.type === 'item' && sessionId === root && !record.title && event.item.kind === 'user_message' && fromUser(event.item)) {
|
|
507
|
+
// The user's first message names an unnamed root, as Paseo names an agent (ALPD §15).
|
|
508
|
+
const title = titleFromPrompt(event.item.text);
|
|
509
|
+
if (title) { save(record, { title }); return true; }
|
|
510
|
+
}
|
|
511
|
+
return false;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** What a root's ended turn asks of the user: a look when it completed, attention when it failed, nothing when canceled. */
|
|
515
|
+
function turnAttention(event: Extract<AlpEvent, { type: 'turn.ended' }>): TurnAttention | undefined {
|
|
516
|
+
if (event.state === 'canceled') return undefined;
|
|
517
|
+
const message = event.error?.message?.trim();
|
|
518
|
+
return { reason: event.state === 'completed' ? 'finished' : 'error', at: new Date().toISOString(), turnId: event.turnId, ...(event.state === 'failed' && message ? { message: event.error!.message } : {}) };
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* Tells the viewers of a live root its name, as a `session.updated` kept in its timeline, so a
|
|
523
|
+
* viewer attached later replays it. Nothing is sent for a root that is not open.
|
|
524
|
+
*/
|
|
525
|
+
function announceTitle(root: string, title: string) {
|
|
526
|
+
const session = runtime.snapshot(root);
|
|
527
|
+
if (!session || rootOf.get(root) !== root) return;
|
|
528
|
+
const envelope = keep(root, { sessionId: root, epoch: `title-${startedAt}`, seq: 0, ts: new Date().toISOString(), event: { type: 'session.updated', session: { ...session, title } } });
|
|
529
|
+
const log = logs.get(root) ?? [];
|
|
530
|
+
log.push(envelope);
|
|
531
|
+
if (log.length > TREE_LOG_LIMIT) log.splice(0, log.length - TREE_LOG_LIMIT);
|
|
532
|
+
logs.set(root, log);
|
|
533
|
+
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
runtime.onEvent(original => {
|
|
537
|
+
// While alpd stops, records keep what was running, so the next alpd continues it (ALPD §31).
|
|
538
|
+
if (closing) return;
|
|
539
|
+
let envelope = original;
|
|
540
|
+
const { sessionId, event } = envelope;
|
|
541
|
+
if (event.type === 'session.opened') {
|
|
542
|
+
const parent = event.session.parentId;
|
|
543
|
+
rootOf.set(sessionId, parent ? rootOf.get(parent) ?? parent : sessionId);
|
|
544
|
+
}
|
|
545
|
+
const root = rootOf.get(sessionId) ?? sessionId;
|
|
546
|
+
let named = false;
|
|
547
|
+
if (rootOf.has(sessionId)) {
|
|
548
|
+
envelope = keep(root, envelope);
|
|
549
|
+
const log = logs.get(root) ?? [];
|
|
550
|
+
log.push(envelope);
|
|
551
|
+
if (log.length > TREE_LOG_LIMIT) log.splice(0, log.length - TREE_LOG_LIMIT);
|
|
552
|
+
logs.set(root, log);
|
|
553
|
+
const before = records.get(root)?.attention;
|
|
554
|
+
named = track(sessionId, root, event);
|
|
555
|
+
const after = records.get(root)?.attention;
|
|
556
|
+
// A root's turn starting or ending decides its attention, even when it was already none.
|
|
557
|
+
if (sessionId === root && (event.type === 'turn.started' || event.type === 'turn.ended')) pendingAcks.delete(root);
|
|
558
|
+
if (after !== before) tellAttention(root, after);
|
|
559
|
+
}
|
|
560
|
+
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
561
|
+
if (event.type === 'question' || event.type === 'question.resolved') tellWatchers(root, envelope);
|
|
562
|
+
else if (event.type === 'turn.ended' && sessionId === root) tellWatchers(root, envelope, true);
|
|
563
|
+
// After the message that named it, so its cursor follows the message's.
|
|
564
|
+
if (named) announceTitle(root, records.get(root)!.title!);
|
|
565
|
+
if (event.type === 'session.closed' && sessionId === root) {
|
|
566
|
+
setImmediate(() => forget(root));
|
|
567
|
+
} else {
|
|
568
|
+
setImmediate(() => void reap(root));
|
|
569
|
+
}
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Loads records, settles sessions a crash or a stop left working, and prunes expired
|
|
574
|
+
* trees. Trees with assignments the runtime can continue, whose root was working, or
|
|
575
|
+
* whose root a scheduled job waits for, are reopened afterwards (ALPD §31).
|
|
576
|
+
*/
|
|
577
|
+
async function restore() {
|
|
578
|
+
await store!.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: true });
|
|
579
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS, { temporaries: true }).catch(error => recoveryLog.warn('could not prune the lifecycle journal', { code: 'ALPD_LIFECYCLE_PRUNE_FAILED', error }));
|
|
580
|
+
const loaded = await store!.list();
|
|
581
|
+
await reconcileReceipts(loaded);
|
|
582
|
+
const now = Date.now();
|
|
583
|
+
const ended = { code: 'daemon_restarted', message: 'alpd stopped while this session was working' };
|
|
584
|
+
const epoch = `restart-${startedAt}`;
|
|
585
|
+
const continuing = new Set(runtime.recoverable().map(entry => entry.assignmentId));
|
|
586
|
+
// The roots a job waits for: they are reopened, so the job finds its session.
|
|
587
|
+
// Every project of the host is read here: the daemon serves them all.
|
|
588
|
+
const pending = await schedules?.all({ status: 'pending' }) ?? [];
|
|
589
|
+
for (const job of pending) scheduler?.hold(job);
|
|
590
|
+
const scheduled = new Set(pending.map(job => job.sessionId));
|
|
591
|
+
const reopen: Array<{ record: SessionRecord; working: boolean }> = [];
|
|
592
|
+
const byRoot = trees(loaded);
|
|
593
|
+
const removed = await expire(byRoot, now);
|
|
594
|
+
for (const [root, tree] of byRoot) {
|
|
595
|
+
const head = tree.find(record => record.id === root);
|
|
596
|
+
if (removed.has(root)) continue;
|
|
597
|
+
// A root that was closed is not opened again for a job: a job continues a session
|
|
598
|
+
// that is alive, and a closed one fails with the reason.
|
|
599
|
+
if (head && resumable(head) && (head.status === 'running' || (head.status === 'idle' && head.session?.parked) || tree.some(record => continuing.has(record.id)) || (scheduled.has(head.id) && head.status !== 'closed'))) reopen.push({ record: head, working: head.status === 'running' });
|
|
600
|
+
if (tree.some(record => LIVE.includes(record.status))) seen(root, await store!.timeline(root));
|
|
601
|
+
for (const record of tree as Array<SessionRecord & { activeTurnId?: string }>) {
|
|
602
|
+
records.set(record.id, record);
|
|
603
|
+
if (!LIVE.includes(record.status)) continue;
|
|
604
|
+
const envelope = (event: AlpEvent): Envelope => ({ sessionId: record.id, epoch, seq: 0, ts: new Date().toISOString(), event });
|
|
605
|
+
// The turn a crash or a stop cut off is reported interrupted, never continued as if nothing happened.
|
|
606
|
+
if (record.activeTurnId) keep(root, envelope({ type: 'turn.ended', turnId: record.activeTurnId, state: 'failed', error: { message: ended.message, code: ended.code } }));
|
|
607
|
+
if (record.id === root) {
|
|
608
|
+
if (!(record.status === 'idle' && record.session?.parked)) save(record, record.status === 'idle' ? { status: 'closed', activeTurnId: undefined } : { status: 'error', lastError: ended, activeTurnId: undefined });
|
|
609
|
+
} else if (continuing.has(record.id) && reopen.some(entry => entry.record.id === root)) {
|
|
610
|
+
// The runtime reopens it under the same id; until then it is closed.
|
|
611
|
+
save(record, { status: 'closed', activeTurnId: undefined });
|
|
612
|
+
} else {
|
|
613
|
+
// Children never survive their runtime; their requester learns the assignment failed.
|
|
614
|
+
keep(root, envelope({ type: 'session.closed' }));
|
|
615
|
+
save(record, { status: 'closed', lastError: ended, activeTurnId: undefined });
|
|
616
|
+
if (runLogDir && !continuing.has(record.id)) {
|
|
617
|
+
const line = JSON.stringify({ ts: new Date().toISOString(), rootSessionId: root, event: 'assignment.finished', assignmentId: record.id, agent: record.session?.agent, sessionId: record.id, status: 'failed', error: ended.message, reconciled: true }) + '\n';
|
|
618
|
+
await mkdir(runLogDir, { recursive: true }).then(() => appendFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`), line)).catch(() => {});
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
// Forks and rewinds a crash cut off: finished from their journal, or settled unknown, before any tree reopens.
|
|
624
|
+
if (conversation) await conversation.recover().catch(error => recoveryLog.error('could not recover lifecycle operations', { code: 'ALPD_LIFECYCLE_RECOVERY_FAILED', error }));
|
|
625
|
+
// Assignments whose tree cannot be reopened end now, and their tasks go back to open.
|
|
626
|
+
const reopened = new Set(reopen.map(entry => entry.record.id));
|
|
627
|
+
for (const rootId of new Set(runtime.recoverable().map(entry => entry.rootId))) {
|
|
628
|
+
if (!reopened.has(rootId)) await runtime.abandon(rootId, 'its root session cannot be reopened').catch(() => {});
|
|
629
|
+
}
|
|
630
|
+
for (const { record, working } of reopen) {
|
|
631
|
+
// A root whose rewind could not be finished stays closed: it would reopen on the old conversation.
|
|
632
|
+
if (fencedRoot(record.id)) { recoveryLog.warn(`${record.id} is not reopened: a rewind of it is not finished`, { code: 'ALPD_REWIND_FENCED', sessionId: record.id }); continue; }
|
|
633
|
+
// The session is opened again: a job that waits for it waits, it does not fail.
|
|
634
|
+
markOpening(record.id);
|
|
635
|
+
recovering.set(record.id, recoverTree(record, working, () => { clearOpening(record.id); }));
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
function trees(list: Iterable<SessionRecord>) {
|
|
640
|
+
const byRoot = new Map<string, SessionRecord[]>();
|
|
641
|
+
for (const record of list) byRoot.set(record.rootId, [...(byRoot.get(record.rootId) ?? []), record]);
|
|
642
|
+
return byRoot;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/**
|
|
646
|
+
* Retention (ALPD §68): deletes trees nobody needs any more, with their records, timeline and
|
|
647
|
+
* run log. A tree stays while any of its sessions is live or was written in the last 30 days,
|
|
648
|
+
* while a receipt of one of its sessions is still honoured (7 days from its last write, so a
|
|
649
|
+
* retried prompt is answered from it), while the runtime can continue one of its assignments,
|
|
650
|
+
* and while it is open, attached or being recovered. Timelines are never trimmed while their
|
|
651
|
+
* tree stays, so every cursor a client holds for it replays.
|
|
652
|
+
*/
|
|
653
|
+
async function expire(byRoot: Map<string, SessionRecord[]>, now = Date.now()) {
|
|
654
|
+
const removed = new Set<string>();
|
|
655
|
+
const receiptWritten = new Map<string, number>();
|
|
656
|
+
// Receipts age as the store prunes them: by when their file was written, and by what they say.
|
|
657
|
+
for (const { receipt, writtenAt } of await store!.receipts()) {
|
|
658
|
+
const at = Date.parse(receipt.updatedAt);
|
|
659
|
+
receiptWritten.set(receipt.sessionId, Math.max(receiptWritten.get(receipt.sessionId) ?? 0, Number.isNaN(at) ? now : at, writtenAt));
|
|
660
|
+
}
|
|
661
|
+
const continuing = new Set(runtime.recoverable().map(entry => entry.rootId));
|
|
662
|
+
for (const [root, tree] of byRoot) {
|
|
663
|
+
const remove = async () => {
|
|
664
|
+
if (!tree.some(record => record.id === root)) return;
|
|
665
|
+
if (tree.some(record => LIVE.includes(record.status))) return;
|
|
666
|
+
if (now - Math.max(...tree.map(record => Date.parse(record.updatedAt) || now)) <= RETENTION_MS) return;
|
|
667
|
+
if (tree.some(record => now - (receiptWritten.get(record.id) ?? 0) <= RECEIPT_RETENTION_MS)) return;
|
|
668
|
+
if (continuing.has(root) || rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
669
|
+
// A tree a job waits for stays: the job is to continue that very session.
|
|
670
|
+
if (scheduler?.holds(root)) return;
|
|
671
|
+
const ids = tree.map(record => record.id);
|
|
672
|
+
// A tree restored from a backup counts from its restore: its files were written then.
|
|
673
|
+
if (now - await store!.writtenAt(ids) <= RETENTION_MS) return;
|
|
674
|
+
if (rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
|
|
675
|
+
if (await conversation?.retainsFork(root)) return;
|
|
676
|
+
// Forgotten before the files go, so a resume arriving meanwhile finds nothing to reopen.
|
|
677
|
+
for (const id of ids) records.delete(id);
|
|
678
|
+
cursors.delete(root);
|
|
679
|
+
await store!.remove(root, ids);
|
|
680
|
+
// The history is gone: what its prompts pinned is released (kept releasedGraceMs more).
|
|
681
|
+
await attachments?.releaseSessions(ids).catch(error => recoveryLog.warn('could not release the attachments of removed sessions', { code: 'ALPD_ATTACHMENT_RELEASE_FAILED', error }));
|
|
682
|
+
if (runLogDir) await unlink(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`)).catch(() => {});
|
|
683
|
+
removed.add(root);
|
|
684
|
+
};
|
|
685
|
+
// A source cannot start a native fork between the dependency check and deletion.
|
|
686
|
+
if (conversation) await conversation.lifecycle.serial(root, remove);
|
|
687
|
+
else await remove();
|
|
688
|
+
}
|
|
689
|
+
if (removed.size) recoveryLog.info(`retention removed ${removed.size} session tree${removed.size > 1 ? 's' : ''} unused for ${RETENTION_MS / 86_400_000} days`, { code: 'ALP_RETENTION_REMOVED', trees: removed.size });
|
|
690
|
+
return removed;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/** Retention while alpd runs: receipts past their window, then expired trees; temporary files stay, as writes may be under way. */
|
|
694
|
+
async function sweep() {
|
|
695
|
+
if (closing || !store) return;
|
|
696
|
+
try {
|
|
697
|
+
await restored;
|
|
698
|
+
await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
|
|
699
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS);
|
|
700
|
+
await expire(trees(records.values()));
|
|
701
|
+
} catch (error) {
|
|
702
|
+
recoveryLog.warn('retention sweep failed', { code: 'ALP_RETENTION_FAILED', error });
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : undefined;
|
|
706
|
+
sweeper?.unref();
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* The scheduler's tick. It runs as long as alpd runs, so a job that comes due is
|
|
710
|
+
* delivered even when nobody is watching: the tick is not the runtime's watchdog,
|
|
711
|
+
* which stops as soon as no assignment is left.
|
|
712
|
+
*/
|
|
713
|
+
scheduler?.start(scheduleTickMs);
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Completes receipts a crash left pending when the tree's timeline shows how the runtime
|
|
717
|
+
* answered; the rest stay pending, so their prompt answers outcome_unknown and is never
|
|
718
|
+
* sent again by itself.
|
|
719
|
+
*/
|
|
720
|
+
async function reconcileReceipts(loaded: SessionRecord[]) {
|
|
721
|
+
const rootOfRecord = new Map(loaded.map(record => [record.id, record.rootId]));
|
|
722
|
+
const timelines = new Map<string, Envelope[]>();
|
|
723
|
+
for (const { key, receipt } of await store!.receipts()) {
|
|
724
|
+
if (receipt.state !== 'pending') continue;
|
|
725
|
+
const root = rootOfRecord.get(receipt.sessionId);
|
|
726
|
+
if (!root) continue;
|
|
727
|
+
if (!timelines.has(root)) timelines.set(root, await store!.timeline(root).catch(() => []));
|
|
728
|
+
const answer = timelines.get(root)!.find(({ sessionId, event }) => sessionId === receipt.sessionId
|
|
729
|
+
&& (event.type === 'prompt.accepted' || event.type === 'prompt.failed') && event.clientMessageId === receipt.clientMessageId);
|
|
730
|
+
if (!answer) continue;
|
|
731
|
+
const event = answer.event as Extract<AlpEvent, { type: 'prompt.accepted' | 'prompt.failed' }>;
|
|
732
|
+
const outcome = event.type === 'prompt.accepted' ? 'accepted' : event.error.code === 'outcome_unknown' ? 'unknown' : 'failed';
|
|
733
|
+
await store!.putReceipt(key, { ...receipt, state: 'completed', outcome, ...(event.type === 'prompt.failed' ? { error: event.error } : {}), reconciled: true, updatedAt: new Date().toISOString() })
|
|
734
|
+
.catch(() => {});
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
function resumable(record: SessionRecord) {
|
|
739
|
+
return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** Reopens a root nobody watches yet and continues what it and its assignments were doing. */
|
|
743
|
+
async function recoverTree(record: SessionRecord, working: boolean, opened?: () => void) {
|
|
744
|
+
const session = record.session!;
|
|
745
|
+
// The open of this session is counted once: the flag is cleared when the open is
|
|
746
|
+
// over, whether it succeeded or not, and a second open of the same session keeps
|
|
747
|
+
// its own count.
|
|
748
|
+
let openedOnce = false;
|
|
749
|
+
const open = () => { if (openedOnce) return; openedOnce = true; opened?.(); };
|
|
750
|
+
try {
|
|
751
|
+
if (worktrees && record.spec?.cwd) await worktrees.assertAvailable(record.spec.cwd);
|
|
752
|
+
const stored = await treeLog(record.id);
|
|
753
|
+
seen(record.id, stored);
|
|
754
|
+
logs.set(record.id, [...stored]);
|
|
755
|
+
await runtime.open(record.id, {
|
|
756
|
+
...record.spec!,
|
|
757
|
+
persist: true,
|
|
758
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...(record.base ? { base: record.base } : {}) },
|
|
759
|
+
}, { history: 'skip', delegation: record.delegation ?? true });
|
|
760
|
+
// The session is open again: a job that waits for it may be delivered.
|
|
761
|
+
open();
|
|
762
|
+
const outcomes = await runtime.recover(record.id, { continueRoot: working, parkedRoot: session.parked });
|
|
763
|
+
recoveryLog.info(`recovered ${record.id}: ${outcomes.map(outcome => `${outcome.agent} ${outcome.outcome}`).join(', ') || 'root'}`, { event: 'recovered', sessionId: record.id, rootId: record.rootId });
|
|
764
|
+
} catch (error: any) {
|
|
765
|
+
// The session is not open: a job that waits for it fails with the reason.
|
|
766
|
+
open();
|
|
767
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
768
|
+
recoveryLog.error(`could not recover ${record.id}`, { code: 'ALP_RECOVERY_FAILED', sessionId: record.id, rootId: record.rootId, error });
|
|
769
|
+
await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {});
|
|
770
|
+
} finally {
|
|
771
|
+
recovering.delete(record.id);
|
|
772
|
+
setImmediate(() => void reap(record.id));
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* Sends a prompt at most once per (session, clientMessageId), as Paseo's MessageReceipts
|
|
778
|
+
* (ALPD §15, §66). The answer comes only after the receipt holds the runtime's outcome
|
|
779
|
+
* and the tree's timeline holds its events. A repeat with the same content answers what
|
|
780
|
+
* the first delivery did, with other content a conflict; a receipt left pending by a
|
|
781
|
+
* crash, or a delivery the provider may or may not have received, is outcome_unknown.
|
|
782
|
+
*/
|
|
783
|
+
function deliverOnce(sessionId: string, clientMessageId: string, fingerprint: string, send: () => Promise<void>, { requireReceipt = false, prepare, abandon }: {
|
|
784
|
+
requireReceipt?: boolean;
|
|
785
|
+
/** Before the pending receipt, once no receipt answers: refusals here record nothing; attachments are pinned here. */
|
|
786
|
+
prepare?: (key: string) => Promise<void>;
|
|
787
|
+
/** The prompt certainly did not reach the runtime: what prepare pinned may go. */
|
|
788
|
+
abandon?: (key: string) => Promise<void>;
|
|
789
|
+
} = {}) {
|
|
790
|
+
const key = digest(['prompt', sessionId, clientMessageId]);
|
|
791
|
+
const unknown = () => new RpcError(ERROR.conflict, `alpd cannot tell whether message ${clientMessageId} reached the agent; check the session, then send it again with a new id`, { reason: 'outcome_unknown' });
|
|
792
|
+
const answer = (receipt: Receipt, extra: object = {}) => ({ outcome: receipt.outcome ?? 'accepted', ...(receipt.error ? { error: receipt.error } : {}), ...extra });
|
|
793
|
+
const attempt = async () => {
|
|
794
|
+
let existing: Receipt | UnreadableReceipt | undefined = unsaved.get(key);
|
|
795
|
+
if (!existing) {
|
|
796
|
+
try { existing = await store!.receipt(key); }
|
|
797
|
+
catch (error) { throw persistenceFailed(`message ${clientMessageId}`, error); }
|
|
798
|
+
}
|
|
799
|
+
if (existing) {
|
|
800
|
+
if (existing.state === 'unreadable') throw unknown();
|
|
801
|
+
if (existing.fingerprint !== fingerprint) throw new RpcError(ERROR.conflict, `Message ${clientMessageId} was already sent with different content`, { reason: 'key_conflict' });
|
|
802
|
+
if (existing.state === 'pending' || existing.outcome === 'unknown') throw unknown();
|
|
803
|
+
return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
|
|
804
|
+
}
|
|
805
|
+
// Scheduler replays fail closed when a prior attempt's receipt was pruned,
|
|
806
|
+
// lost or never committed. Absence cannot prove that nothing was sent.
|
|
807
|
+
if (requireReceipt) throw unknown();
|
|
808
|
+
const receipt = (state: Receipt['state'], changes: Partial<Receipt> = {}): Receipt => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: new Date().toISOString() });
|
|
809
|
+
live(sessionId);
|
|
810
|
+
// Attachments are pinned before anything is sent: a crash from here on keeps them.
|
|
811
|
+
await prepare?.(key);
|
|
812
|
+
crashPoint('prompt.before-receipt');
|
|
813
|
+
// Nothing is sent unless the pending receipt is on disk: a crash from here on answers outcome_unknown.
|
|
814
|
+
try { await store!.putReceipt(key, receipt('pending')); }
|
|
815
|
+
catch (error) {
|
|
816
|
+
await abandon?.(key).catch(() => {});
|
|
817
|
+
throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error);
|
|
818
|
+
}
|
|
819
|
+
crashPoint('prompt.after-receipt');
|
|
820
|
+
// The runtime reports how the provider answered as an event, before prompt() resolves.
|
|
821
|
+
let reply: { outcome: 'accepted' | 'failed' | 'unknown'; error?: { message: string; code?: string } } = { outcome: 'accepted' };
|
|
822
|
+
const stop = runtime.onEvent(({ sessionId: from, event }) => {
|
|
823
|
+
if (from !== sessionId) return;
|
|
824
|
+
if (event.type === 'prompt.accepted' && event.clientMessageId === clientMessageId) reply = { outcome: 'accepted' };
|
|
825
|
+
if (event.type === 'prompt.failed' && event.clientMessageId === clientMessageId) reply = { outcome: event.error.code === 'outcome_unknown' ? 'unknown' : 'failed', error: event.error };
|
|
826
|
+
});
|
|
827
|
+
try {
|
|
828
|
+
await send();
|
|
829
|
+
} catch (error) {
|
|
830
|
+
// The runtime refused it before reaching the provider (the session closed meanwhile): not sent.
|
|
831
|
+
await store!.removeReceipt(key).catch(() => {});
|
|
832
|
+
await abandon?.(key).catch(() => {});
|
|
833
|
+
throw error;
|
|
834
|
+
} finally {
|
|
835
|
+
stop();
|
|
836
|
+
}
|
|
837
|
+
const root = rootOf.get(sessionId) ?? sessionId;
|
|
838
|
+
const lost = await store!.drain({ records: [sessionId], timelines: [root] });
|
|
839
|
+
crashPoint('prompt.after-send');
|
|
840
|
+
const done = receipt('completed', reply);
|
|
841
|
+
let durable = lost.length === 0;
|
|
842
|
+
try { await store!.putReceipt(key, done); }
|
|
843
|
+
catch {
|
|
844
|
+
unsaved.set(key, done);
|
|
845
|
+
durable = false;
|
|
846
|
+
}
|
|
847
|
+
crashPoint('prompt.after-completed');
|
|
848
|
+
if (reply.outcome === 'unknown') throw unknown();
|
|
849
|
+
return answer(done, { durable });
|
|
850
|
+
};
|
|
851
|
+
const previous = delivering.get(key) ?? Promise.resolve();
|
|
852
|
+
const result = previous.catch(() => {}).then(() => gated(sessionId, attempt));
|
|
853
|
+
delivering.set(key, result);
|
|
854
|
+
void result.finally(() => { if (delivering.get(key) === result) delivering.delete(key); }).catch(() => {});
|
|
855
|
+
return result;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* The delivery of a scheduled job: the prompt path a client uses, with a
|
|
860
|
+
* clientMessageId of the job's own. The receipt of that message is what keeps a job
|
|
861
|
+
* from running twice: a retry after a crash reads the receipt instead of sending.
|
|
862
|
+
*/
|
|
863
|
+
async function deliverJob(job: ScheduleJob, content: PromptContent, messageId: string, send: AlpRuntime['prompt'] = (id, input) => runtime.prompt(id, input)): Promise<ScheduleDelivery> {
|
|
864
|
+
// The id is the job's own, so it is the same in every attempt of this job.
|
|
865
|
+
const clientMessageId = messageId || scheduleMessageId(job);
|
|
866
|
+
return deliverOnce(job.sessionId, clientMessageId, digest({ delivery: 'auto', content }), async () => {
|
|
867
|
+
live(job.sessionId);
|
|
868
|
+
await send(job.sessionId, { clientMessageId, delivery: 'auto', content });
|
|
869
|
+
}, { requireReceipt: job.attempts > 1 });
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Waits for an opened root's record and timeline (its native thread) to be written, so a
|
|
874
|
+
* crash after the answer can still resume it (ALPD §66); `durable: false` when they were not.
|
|
875
|
+
*/
|
|
876
|
+
async function persisted(root: string) {
|
|
877
|
+
if (!store) return {};
|
|
878
|
+
return { durable: (await store.drain({ records: [root], timelines: [root] })).length === 0 };
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
function forget(root: string) {
|
|
882
|
+
if (runtime.snapshot(root)) return;
|
|
883
|
+
for (const [id, candidate] of rootOf) if (candidate === root) { rootOf.delete(id); recoveryErrors.delete(id); }
|
|
884
|
+
recoveryErrors.delete(root);
|
|
885
|
+
logs.delete(root);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/** Closes an idle root that no client watches. */
|
|
889
|
+
async function reap(root: string) {
|
|
890
|
+
if (closing || attached.get(root)?.size || recovering.has(root)) return false;
|
|
891
|
+
// A root a job waits for stays open: the job is to continue that very session.
|
|
892
|
+
if (scheduler?.holds(root)) return false;
|
|
893
|
+
const session = runtime.snapshot(root);
|
|
894
|
+
if (!session || session.busy) return false;
|
|
895
|
+
await runtime.close(root).catch(() => {});
|
|
896
|
+
return true;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
function attach(connection: Connection, root: string) {
|
|
900
|
+
const set = attached.get(root) ?? new Set();
|
|
901
|
+
set.add(connection);
|
|
902
|
+
attached.set(root, set);
|
|
903
|
+
connection.roots.add(root);
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
function detach(connection: Connection, root: string) {
|
|
907
|
+
attached.get(root)?.delete(connection);
|
|
908
|
+
if (!attached.get(root)?.size) attached.delete(root);
|
|
909
|
+
connection.roots.delete(root);
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
function summary(id: string): SessionSummary | undefined {
|
|
913
|
+
const record = records.get(id);
|
|
914
|
+
const live = runtime.snapshot(id);
|
|
915
|
+
const session = live ?? record?.session;
|
|
916
|
+
if (!session) return undefined;
|
|
917
|
+
const status: SessionStatus = live ? (live.activeTurnId ? 'running' : 'idle') : record?.status === 'error' ? 'error' : 'closed';
|
|
918
|
+
return { ...session, ...(live ? {} : { busy: false, activeTurnId: undefined }), status, title: record?.title, ...(record?.archived ? { archived: true } : {}), ...(record?.attention && !record.archived ? { attention: record.attention } : {}), lastError: record?.lastError, createdAt: record?.createdAt, updatedAt: record?.updatedAt, ...(record && conversation ? conversation.fields(record, session) : {}) };
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** The record of a root the user acts on. */
|
|
922
|
+
function rootRecord(sessionId: string) {
|
|
923
|
+
if (typeof sessionId !== 'string') throw new RpcError(-32602, 'sessionId is required');
|
|
924
|
+
const record = records.get(sessionId);
|
|
925
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
|
|
926
|
+
if (record.rootId !== record.id) throw new RpcError(-32602, 'Only a root session can be renamed or archived');
|
|
927
|
+
return record;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
function known(sessionId: string) {
|
|
931
|
+
const found = summary(sessionId);
|
|
932
|
+
if (!found) throw new RpcError(ERROR.notFound, 'Session is not open');
|
|
933
|
+
return found;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
function live(sessionId: string) {
|
|
937
|
+
const session = runtime.snapshot(sessionId);
|
|
938
|
+
if (!session) throw new RpcError(ERROR.notFound, 'Session is not open');
|
|
939
|
+
return session;
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
async function treeLog(root: string) {
|
|
943
|
+
return logs.get(root) ?? await store?.timeline(root) ?? [];
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/**
|
|
947
|
+
* Delivers a tree's history: the root's latest items, then the children's events in their
|
|
948
|
+
* original order, so a grandchild opens while its parent is still open.
|
|
949
|
+
*/
|
|
950
|
+
function replayHistory(connection: Connection, root: string, log: Envelope[], { children = true } = {}) {
|
|
951
|
+
const items = new Map<string, Envelope>();
|
|
952
|
+
for (const envelope of log) {
|
|
953
|
+
if (envelope.sessionId === root && envelope.event.type === 'item') items.set(envelope.event.item.id, envelope);
|
|
954
|
+
}
|
|
955
|
+
for (const item of items.values()) deliver(connection, item);
|
|
956
|
+
if (children) for (const envelope of log) if (envelope.sessionId !== root && current(envelope)) deliver(connection, envelope);
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/** Questions in a log are history; announceQuestions delivers the ones still waiting. */
|
|
960
|
+
function current(envelope: Envelope) {
|
|
961
|
+
return envelope.event.type !== 'question' && envelope.event.type !== 'question.resolved';
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
function announceQuestions(connection: Connection, root: string) {
|
|
965
|
+
for (const question of runtime.questions()) {
|
|
966
|
+
if (question.rootId !== root) continue;
|
|
967
|
+
deliver(connection, { sessionId: question.sessionId, epoch: `announce-${startedAt}`, seq: 0, ts: new Date().toISOString(), event: { type: 'question', question } });
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
/**
|
|
972
|
+
* Re-announces a live tree to a client that reopens its root: the root as it is now,
|
|
973
|
+
* its timeline when asked, then live children and running turns.
|
|
974
|
+
*/
|
|
975
|
+
function announce(connection: Connection, root: string, history: 'replay' | 'skip') {
|
|
976
|
+
const log = logs.get(root) ?? [];
|
|
977
|
+
const sessions = runtime.list().filter(session => (rootOf.get(session.id) ?? session.id) === root);
|
|
978
|
+
for (const session of sessions) {
|
|
979
|
+
const opened = log.find(envelope => envelope.sessionId === session.id && envelope.event.type === 'session.opened');
|
|
980
|
+
if (!opened || opened.event.type !== 'session.opened') continue;
|
|
981
|
+
const seq = Math.max(...log.filter(envelope => envelope.sessionId === session.id).map(envelope => envelope.seq));
|
|
982
|
+
const envelope = (event: Envelope['event']): Envelope => ({ sessionId: session.id, epoch: opened.epoch, seq, ts: new Date().toISOString(), event });
|
|
983
|
+
deliver(connection, envelope({ ...opened.event, session }));
|
|
984
|
+
if (history === 'replay' && session.id === root) replayHistory(connection, root, log, { children: false });
|
|
985
|
+
deliver(connection, envelope({ type: 'session.ready' }));
|
|
986
|
+
if (session.activeTurnId) deliver(connection, envelope({ type: 'turn.started', turnId: session.activeTurnId, origin: 'user' }));
|
|
987
|
+
}
|
|
988
|
+
announceQuestions(connection, root);
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/** Reopens a closed root from its record: the native thread resumes, alpd replays the history. */
|
|
992
|
+
async function resume(connection: Connection, record: SessionRecord, spec: any, history: 'replay' | 'skip', delegation: boolean) {
|
|
993
|
+
const session = record.session;
|
|
994
|
+
if (record.rootId !== record.id) throw new RpcError(ERROR.failed, 'Only root sessions can be resumed');
|
|
995
|
+
if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, 'This session cannot be resumed');
|
|
996
|
+
const agent = spec.agent ?? spec.restore?.agent;
|
|
997
|
+
if (agent !== undefined && agent !== session.agent) throw new RpcError(ERROR.failed, 'Cannot resume a session as a different ALP agent');
|
|
998
|
+
// The session is opened again from the first moment: a job that waits for it waits
|
|
999
|
+
// for the open, it does not fail with 'the session is closed'.
|
|
1000
|
+
markOpening(record.id);
|
|
1001
|
+
// The reason of an earlier failure is not true while the session opens again.
|
|
1002
|
+
recoveryErrors.delete(record.id);
|
|
1003
|
+
let applied = false;
|
|
1004
|
+
try {
|
|
1005
|
+
if (worktrees) await worktrees.assertAvailable(record.spec.cwd);
|
|
1006
|
+
const stored = await treeLog(record.id);
|
|
1007
|
+
seen(record.id, stored);
|
|
1008
|
+
logs.set(record.id, [...stored]);
|
|
1009
|
+
attach(connection, record.id);
|
|
1010
|
+
const opened = await runtime.open(record.id, {
|
|
1011
|
+
...record.spec,
|
|
1012
|
+
...(spec.mode !== undefined ? { mode: spec.mode } : {}),
|
|
1013
|
+
...(spec.thinking !== undefined ? { thinking: spec.thinking } : {}),
|
|
1014
|
+
persist: true,
|
|
1015
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...(record.base ? { base: record.base } : {}) },
|
|
1016
|
+
}, { history: stored.length ? 'skip' : history, delegation: record.delegation ?? delegation });
|
|
1017
|
+
applied = true;
|
|
1018
|
+
await persistAcceptedSpec(record.id, opened, { mode: spec.mode !== undefined, thinking: spec.thinking !== undefined });
|
|
1019
|
+
if (history === 'replay') replayHistory(connection, record.id, stored);
|
|
1020
|
+
return opened;
|
|
1021
|
+
} catch (error: any) {
|
|
1022
|
+
// A durable-write failure does not undo a successful open or abandon its viewer.
|
|
1023
|
+
if (applied) throw error;
|
|
1024
|
+
detach(connection, record.id);
|
|
1025
|
+
// The session could not be opened: a job that waits for it says why.
|
|
1026
|
+
keepRecoveryError(record.id, error?.message ?? String(error));
|
|
1027
|
+
throw error;
|
|
1028
|
+
} finally {
|
|
1029
|
+
clearOpening(record.id);
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
/** Causal successful apply/open only: never infer requested configuration from later events. */
|
|
1034
|
+
async function persistAcceptedSpec(id: string, accepted: SessionSnapshot, fields: { mode?: boolean; thinking?: boolean }) {
|
|
1035
|
+
const record = records.get(id);
|
|
1036
|
+
if (!record?.spec || (!fields.mode && !fields.thinking)) return;
|
|
1037
|
+
record.spec = {
|
|
1038
|
+
...record.spec,
|
|
1039
|
+
...(fields.mode ? { mode: accepted.mode } : {}),
|
|
1040
|
+
...(fields.thinking ? { thinking: accepted.thinking } : {}),
|
|
1041
|
+
};
|
|
1042
|
+
record.updatedAt = new Date().toISOString();
|
|
1043
|
+
try { await store?.put(record); }
|
|
1044
|
+
catch (error) { throw persistenceFailed(`the configuration of ${id}; the runtime already applied it`, error); }
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/** Projects, tasks, library and settings (docs/protocol/alp-json-rpc-v1.md §15); a team save syncs the projects sessions ran in. */
|
|
1048
|
+
const registry = home ? createRegistry(home) : undefined;
|
|
1049
|
+
const worktrees = home && registry && process.platform !== 'win32' ? createWorkspaceWorktrees(home, registry, async (directory, run) => {
|
|
1050
|
+
if (!runtime.withWorkspaceMutation) throw new RegistryError(1005, 'Runtime cannot prove safe worktree removal', { reason: 'guard_unavailable' });
|
|
1051
|
+
try { return await runtime.withWorkspaceMutation(directory, run); } catch (error: any) { if (error?.data?.reason) throw new RegistryError(1004, 'Workspace is in use or has retained assignment results', error.data); throw error; }
|
|
1052
|
+
}, async directory => { if (!runtime.registerWorkspace) throw new RegistryError(1005, 'Runtime cannot register safe workspace ownership', { reason: 'guard_unavailable' }); await runtime.registerWorkspace(directory); }) : undefined;
|
|
1053
|
+
const workspaceDescriptor = async (w: any) => worktrees ? worktrees.describe(w) : w;
|
|
1054
|
+
// workspace.git.status and workspace.git.diff (§12.5): read-only, by registry workspaceId.
|
|
1055
|
+
const gitReader = registry ? createGitReader({ registry, log: (message, fields) => log.warn(message, { code: 'ALPD_GIT_READ_FAILED', ...fields }) }) : undefined;
|
|
1056
|
+
// Terminals (§12.10): a real PTY shell as the daemon's account, only while the host opted in
|
|
1057
|
+
// (<ALP_HOME>/terminal.json); bound to the caller's principal and the workspace's directory.
|
|
1058
|
+
const terminals = home && registry ? createTerminalService({
|
|
1059
|
+
home,
|
|
1060
|
+
resolveWorkspace: workspaceId => registry.resolve(workspaceId),
|
|
1061
|
+
log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
|
|
1062
|
+
...terminalOptions,
|
|
1063
|
+
}) : undefined;
|
|
1064
|
+
const terminalCall = <T>(run: (service: NonNullable<typeof terminals>) => Promise<T>) => {
|
|
1065
|
+
if (!terminals) throw new RpcError(ERROR.unavailable, 'This alpd has no home: it serves no terminals', { reason: 'terminal_unsupported' });
|
|
1066
|
+
return run(terminals);
|
|
1067
|
+
};
|
|
1068
|
+
const attachmentCall = <T>(run: (store: NonNullable<typeof attachments>) => Promise<T>) => {
|
|
1069
|
+
if (!attachments) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not store attachments (capability attachments is not listed)');
|
|
1070
|
+
return run(attachments);
|
|
1071
|
+
};
|
|
1072
|
+
const gitCall = <T>(run: (reader: NonNullable<typeof gitReader>) => Promise<T>) => {
|
|
1073
|
+
if (!gitReader) throw new RpcError(ERROR.unavailable, 'Registry needs ALP_HOME');
|
|
1074
|
+
return run(gitReader);
|
|
1075
|
+
};
|
|
1076
|
+
const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap(record => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
|
|
1077
|
+
const extensionOwners = new Map<string, Connection>();
|
|
1078
|
+
const handlers: Record<string, (connection: Connection, params: any) => Promise<unknown> | unknown> = {
|
|
1079
|
+
'extension.register': async (connection, params) => {
|
|
1080
|
+
const method = params?.method;
|
|
1081
|
+
if (typeof method !== 'string' || !/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(method) || method === '__proto__' || method === 'constructor' || method === 'toString') throw new RpcError(ERROR.protocol, 'extension.register requires a safe method name');
|
|
1082
|
+
if (method.length > 128 || (reservedNamespaces.has(method.split('.')[0]) && !originalMethods.has(method))) throw new RpcError(ERROR.protocol, 'extension.register requires an extension namespace and a name of at most 128 characters');
|
|
1083
|
+
if (originalMethods.has(method) || extensionOwners.has(method) || Object.hasOwn(handlers, method)) throw new RpcError(ERROR.conflict, `${method} is already registered`);
|
|
1084
|
+
if ((methodOwners.get(connection)?.size ?? 0) >= 128 || extensionOwners.size >= 1024) throw new RpcError(ERROR.conflict, 'too many registered extension methods');
|
|
1085
|
+
extensionOwners.set(method, connection);
|
|
1086
|
+
if (!methodOwners.has(connection)) methodOwners.set(connection, new Set());
|
|
1087
|
+
methodOwners.get(connection).add(method);
|
|
1088
|
+
handlers[method] = async (_connection, invokeParams) => {
|
|
1089
|
+
const owner = extensionOwners.get(method);
|
|
1090
|
+
if (!owner || !connections.has(owner)) { delete handlers[method]; extensionOwners.delete(method); throw new RpcError(ERROR.notFound, `${method} is not available`); }
|
|
1091
|
+
return invokeExtended(owner, _connection, method, invokeParams ?? {});
|
|
1092
|
+
};
|
|
1093
|
+
return { registered: method };
|
|
1094
|
+
},
|
|
1095
|
+
'extension.unregister': async (connection, params) => {
|
|
1096
|
+
const method = params?.method;
|
|
1097
|
+
if (typeof method !== 'string' || !method.trim()) throw new RpcError(ERROR.protocol, 'extension.unregister requires a method name');
|
|
1098
|
+
const owner = extensionOwners.get(method);
|
|
1099
|
+
if (!owner) throw new RpcError(ERROR.notFound, `${method} is not registered`);
|
|
1100
|
+
if (owner !== connection) throw new RpcError(ERROR.conflict, `${method} is owned by another connection`);
|
|
1101
|
+
delete handlers[method];
|
|
1102
|
+
extensionOwners.delete(method);
|
|
1103
|
+
const owned = methodOwners.get(connection);
|
|
1104
|
+
owned?.delete(method);
|
|
1105
|
+
return { unregistered: method };
|
|
1106
|
+
},
|
|
1107
|
+
'daemon.status': async () => ({ pid: process.pid, startedAt, version, protocolVersion: PROTOCOL_VERSION, sessions: runtime.list().length, questions: runtime.questions().length, ...(previousExit ? { previousExit } : {}), ...(store ? { persistence: store.health() } : {}), health: await health() }),
|
|
1108
|
+
|
|
1109
|
+
'session.status'(_connection, { sessionId }) {
|
|
1110
|
+
if (typeof sessionId !== 'string') throw new RpcError(-32602, 'sessionId is required');
|
|
1111
|
+
const status = runtime.status(sessionId);
|
|
1112
|
+
if (!status) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not live`);
|
|
1113
|
+
return { status };
|
|
1114
|
+
},
|
|
1115
|
+
|
|
1116
|
+
'session.message'(_connection, { sessionId, text }) {
|
|
1117
|
+
runtime.message(sessionId, text);
|
|
1118
|
+
return {};
|
|
1119
|
+
},
|
|
1120
|
+
|
|
1121
|
+
/** The assignment log of a session's tree, from the run log. */
|
|
1122
|
+
async 'session.log'(_connection, { sessionId }) {
|
|
1123
|
+
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
1124
|
+
if (!runLogDir) return { rootId: root, entries: [] };
|
|
1125
|
+
const text = await readFile(path.join(runLogDir, `${root.replace(/[^\w.-]/g, '_')}.jsonl`), 'utf8').catch(() => '');
|
|
1126
|
+
const entries = text.split('\n').filter(Boolean).flatMap(line => { try { return [JSON.parse(line)]; } catch { return []; } });
|
|
1127
|
+
return { rootId: root, entries };
|
|
1128
|
+
},
|
|
1129
|
+
|
|
1130
|
+
'question.list'(_connection, { projectRoot } = {}) {
|
|
1131
|
+
return { questions: runtime.questions().filter(question => projectRoot === undefined || projectOf(question.rootId) === projectRoot) };
|
|
1132
|
+
},
|
|
1133
|
+
|
|
1134
|
+
/**
|
|
1135
|
+
* The questions waiting now; from then on this connection is told of `question` and
|
|
1136
|
+
* `question.resolved` in every tree, or those of `projectRoot`, attached or not. Calling it
|
|
1137
|
+
* again replaces the filter; it lasts as long as the connection (ALPD §15). With `turns`, also
|
|
1138
|
+
* of `turn.ended` of every root; with `attention`, also of each root's attention, now and as it
|
|
1139
|
+
* changes (docs/protocol/alp-json-rpc-v1.md §12.2).
|
|
1140
|
+
*/
|
|
1141
|
+
'question.watch'(connection, { projectRoot, turns, attention } = {}) {
|
|
1142
|
+
// No await between registering and listing: an event either is in the list or follows it.
|
|
1143
|
+
watchers.set(connection, { projectRoot, turns: turns === true, attention: attention === true });
|
|
1144
|
+
return {
|
|
1145
|
+
questions: runtime.questions().filter(question => projectRoot === undefined || projectOf(question.rootId) === projectRoot),
|
|
1146
|
+
...(attention === true ? { attention: attentionOf(projectRoot) } : {}),
|
|
1147
|
+
};
|
|
1148
|
+
},
|
|
1149
|
+
|
|
1150
|
+
/**
|
|
1151
|
+
* Acknowledges a root's attention for every client, as Paseo's clear_agent_attention; with `at`,
|
|
1152
|
+
* only the attention set then, so a look at an older turn end never hides a newer one (§12.2).
|
|
1153
|
+
*/
|
|
1154
|
+
async 'session.attention.clear'(_connection, { sessionId, at }) {
|
|
1155
|
+
if (typeof sessionId !== 'string') throw new RpcError(-32602, 'sessionId is required');
|
|
1156
|
+
if (at !== undefined && typeof at !== 'string') throw new RpcError(-32602, 'at must be a string');
|
|
1157
|
+
const record = records.get(sessionId);
|
|
1158
|
+
if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
|
|
1159
|
+
const attention = record.attention;
|
|
1160
|
+
if (!attention || (at !== undefined && attention.at !== at)) return { cleared: false };
|
|
1161
|
+
// Not a change of the session: its place in session.list stays.
|
|
1162
|
+
const ack = {};
|
|
1163
|
+
pendingAcks.set(record.id, ack);
|
|
1164
|
+
record.attention = undefined;
|
|
1165
|
+
try { await store?.put(record); }
|
|
1166
|
+
catch (error) {
|
|
1167
|
+
// Brought back only if nothing decided its attention meanwhile: a turn that started since, or
|
|
1168
|
+
// archiving, ended it anyway. Nobody was told of the clear, so nobody is told of this.
|
|
1169
|
+
if (pendingAcks.get(record.id) === ack && !record.attention) record.attention = attention;
|
|
1170
|
+
throw persistenceFailed(`the attention of ${record.id}`, error);
|
|
1171
|
+
}
|
|
1172
|
+
finally { if (pendingAcks.get(record.id) === ack) pendingAcks.delete(record.id); }
|
|
1173
|
+
// What holds now: a turn that ended while the write was on its way set a newer one, which stays.
|
|
1174
|
+
tellAttention(record.id, record.attention);
|
|
1175
|
+
return { cleared: true };
|
|
1176
|
+
},
|
|
1177
|
+
|
|
1178
|
+
/**
|
|
1179
|
+
* The files of a directory whose path matches a query, read-only and confined to it: no link
|
|
1180
|
+
* is followed, only names are read (docs/protocol/alp-json-rpc-v1.md §12.3, ALPD §15).
|
|
1181
|
+
*/
|
|
1182
|
+
async 'workspace.files.search'(_connection, { projectRoot, query, limit } = {}) {
|
|
1183
|
+
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot) || path.resolve(projectRoot) !== projectRoot) {
|
|
1184
|
+
throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot must be an absolute, normalized path', { reason: 'invalid_path' });
|
|
1185
|
+
}
|
|
1186
|
+
try {
|
|
1187
|
+
return await searchWorkspaceFiles(projectRoot, { query, limit });
|
|
1188
|
+
} catch (error) {
|
|
1189
|
+
if (error instanceof FilesError) throw new RpcError(ERROR.notFound, error.message, { reason: 'not_directory' });
|
|
1190
|
+
throw error;
|
|
1191
|
+
}
|
|
1192
|
+
},
|
|
1193
|
+
|
|
1194
|
+
/**
|
|
1195
|
+
* The entries of a directory under projectRoot, and the content of a text file there:
|
|
1196
|
+
* read-only, confined to it, no link followed, blocked paths always refused, .gitignore'd ones
|
|
1197
|
+
* unless includeIgnored (docs/protocol/alp-json-rpc-v1.md §12.4, ALPD §15).
|
|
1198
|
+
*/
|
|
1199
|
+
async 'workspace.files.list'(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
1200
|
+
return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
1201
|
+
},
|
|
1202
|
+
async 'workspace.files.read'(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
1203
|
+
return filesCall(projectRoot, () => readWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
1204
|
+
},
|
|
1205
|
+
|
|
1206
|
+
/** The project board: live claims, decisions and findings (ALPD §18). */
|
|
1207
|
+
async 'board.list'(_connection, { projectRoot } = {}) {
|
|
1208
|
+
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, 'An absolute projectRoot is required');
|
|
1209
|
+
return { pins: await runtime.board(projectRoot) };
|
|
1210
|
+
},
|
|
1211
|
+
|
|
1212
|
+
/** Pauses delegation and wakes on a runtime, or everywhere (ALPD §29). */
|
|
1213
|
+
'daemon.pause'(_connection, { runtime: kind, now = false, reason } = {}) {
|
|
1214
|
+
try { return runtime.pause({ ...(kind === undefined ? {} : { runtime: kind }), now: now === true, ...(reason === undefined ? {} : { reason }) }); }
|
|
1215
|
+
catch (error: any) { throw new RpcError(-32602, error?.message ?? String(error)); }
|
|
1216
|
+
},
|
|
1217
|
+
|
|
1218
|
+
'daemon.resume'(_connection, { runtime: kind } = {}) {
|
|
1219
|
+
try { return runtime.resume(kind === undefined ? {} : { runtime: kind }); }
|
|
1220
|
+
catch (error: any) { throw new RpcError(-32602, error?.message ?? String(error)); }
|
|
1221
|
+
},
|
|
1222
|
+
|
|
1223
|
+
'daemon.pauses'() {
|
|
1224
|
+
return runtime.pauses();
|
|
1225
|
+
},
|
|
1226
|
+
'daemon.usage': (_connection, { refresh = false } = {}) => runtime.usage(refresh === true),
|
|
1227
|
+
|
|
1228
|
+
/** Asks a finished assignment, or the last one on a task, about its work (ALPD §27). */
|
|
1229
|
+
async 'assignment.recall'(_connection, { assignmentId, taskId, projectRoot, question } = {}) {
|
|
1230
|
+
if (projectRoot !== undefined && (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot))) throw new RpcError(-32602, 'projectRoot must be absolute');
|
|
1231
|
+
try {
|
|
1232
|
+
return await runtime.recall({ assignmentId, taskId, projectRoot }, question);
|
|
1233
|
+
} catch (error: any) {
|
|
1234
|
+
throw new RpcError(ERROR.failed, error?.message ?? String(error));
|
|
1235
|
+
}
|
|
1236
|
+
},
|
|
1237
|
+
|
|
1238
|
+
'question.answer'(_connection, { questionId, text, dismiss = false, reason }) {
|
|
1239
|
+
if (typeof questionId !== 'string') throw new RpcError(-32602, 'questionId is required');
|
|
1240
|
+
if (dismiss !== true && typeof text !== 'string') throw new RpcError(-32602, 'text or dismiss is required');
|
|
1241
|
+
// A unique prefix is enough, as in the CLI.
|
|
1242
|
+
const matches = runtime.questions().filter(question => question.id === questionId || question.id.startsWith(questionId));
|
|
1243
|
+
if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
|
|
1244
|
+
runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason } : { text });
|
|
1245
|
+
return { questionId: matches[0].id };
|
|
1246
|
+
},
|
|
1247
|
+
|
|
1248
|
+
'daemon.shutdown': () => {
|
|
1249
|
+
setImmediate(() => onShutdown?.());
|
|
1250
|
+
return {};
|
|
1251
|
+
},
|
|
1252
|
+
|
|
1253
|
+
'registry.owner': (_c, params) => registryCall(async () => {
|
|
1254
|
+
const result = params.operation ? await registry!.mutate(params.operation, params.args ?? {}, { requestId: params.requestId, ifRevision: params.ifRevision }) : undefined;
|
|
1255
|
+
const { receipts: _receipts, ...metadata } = await registry!.snapshot();
|
|
1256
|
+
return { ...(result ? { result } : {}), registry: metadata };
|
|
1257
|
+
}),
|
|
1258
|
+
'registry.worktree': (_c, p) => registryCall(() => worktrees!.grants(p)),
|
|
1259
|
+
'workspace.worktree.options': (_c, p) => registryCall(async () => { const w = (await registry!.snapshot()).workspaces.find(w => w.id === p.workspaceId); if (!w) throw new RegistryError(1001, 'No workspace', { reason: 'not_found' }); const grants = await worktrees!.grants(p); return { mappingIds: grants.mappings.filter(m => m.source === (w.canonical ?? w.directory)).map(m => m.id) }; }),
|
|
1260
|
+
'workspace.worktree.create': (_c, p) => registryCall(async () => { const result = await worktrees!.mutate('create', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
|
|
1261
|
+
'workspace.worktree.remove': (_c, p) => registryCall(async () => { const result = await worktrees!.mutate('remove', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
|
|
1262
|
+
'workspace.git.status': (_c, p) => gitCall(reader => reader.status(p.workspaceId)),
|
|
1263
|
+
'workspace.git.diff': (_c, p) => gitCall(reader => reader.diff({ workspaceId: p.workspaceId, compare: p.compare, path: p.path, cursor: p.cursor })),
|
|
1264
|
+
'project.list': (_c, p) => registryList('projects', p),
|
|
1265
|
+
'workspace.list': (_c, p) => registryList('workspaces', p),
|
|
1266
|
+
'workspace.get': (_c, p) => registryCall(async () => {
|
|
1267
|
+
await registry!.resolve(p.workspaceId, undefined, true);
|
|
1268
|
+
const r = await registry!.snapshot();
|
|
1269
|
+
return { workspace: { ...await workspaceDescriptor(r.workspaces.find(w => w.id === p.workspaceId)), revision: r.revision }, revision: r.revision };
|
|
1270
|
+
}),
|
|
1271
|
+
'project.register': (_c, p) => registryMutation('project.register', p),
|
|
1272
|
+
'project.remove': (_c, p) => registryMutation('project.remove', p),
|
|
1273
|
+
'workspace.update': (_c, p) => registryMutation('workspace.update', p),
|
|
1274
|
+
'catalog.get': () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
|
|
1275
|
+
// attachment.* (§12.6): each call acts for its principal context; without the store (no home or
|
|
1276
|
+
// store, or Windows) alpd does not serve them, as for any method it does not know.
|
|
1277
|
+
// terminal.* (§12.10): each call acts for its principal context; input, resize and the stream
|
|
1278
|
+
// belong to the connection that attached the terminal.
|
|
1279
|
+
'terminal.create': (_c, p) => terminalCall(service => service.create(principalOf(p), p)),
|
|
1280
|
+
'terminal.list': (_c, p) => terminalCall(service => service.list(principalOf(p), p)),
|
|
1281
|
+
'terminal.attach': (c, p) => terminalCall(service => service.attach(principalOf(p), c, p)),
|
|
1282
|
+
'terminal.input': (c, p) => terminalCall(service => service.input(principalOf(p), c, p)),
|
|
1283
|
+
'terminal.resize': (c, p) => terminalCall(service => service.resize(principalOf(p), c, p)),
|
|
1284
|
+
'terminal.close': (_c, p) => terminalCall(service => service.close(principalOf(p), p)),
|
|
1285
|
+
'terminal.revoke': (_c, p) => terminalCall(service => service.revoke(p.principalId)),
|
|
1286
|
+
'attachment.begin': (_c, p) => attachmentCall(store => store.begin(principalOf(p), p)),
|
|
1287
|
+
'attachment.chunk': (_c, p) => attachmentCall(store => store.chunk(principalOf(p), p)),
|
|
1288
|
+
'attachment.commit': (_c, p) => attachmentCall(store => store.commit(principalOf(p), p)),
|
|
1289
|
+
'attachment.abort': (_c, p) => attachmentCall(store => store.abort(principalOf(p), p)),
|
|
1290
|
+
'attachment.get': (_c, p) => attachmentCall(store => store.get(principalOf(p), p)),
|
|
1291
|
+
'attachment.delete': (_c, p) => attachmentCall(store => store.remove(principalOf(p), p)),
|
|
1292
|
+
|
|
1293
|
+
async 'session.create'(connection, { sessionId, workspaceId, spec, history = 'skip', delegation = true, resume: resuming = false }) {
|
|
1294
|
+
if (workspaceId !== undefined) {
|
|
1295
|
+
if (!registry || typeof workspaceId !== 'string') throw new RpcError(-32602, 'Invalid workspaceId');
|
|
1296
|
+
try { spec = { ...spec, cwd: await registry.resolve(workspaceId, spec?.cwd) }; } catch (e) { if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data); throw e; }
|
|
1297
|
+
const placements = (await registryCall(() => registry!.snapshot())).sessions;
|
|
1298
|
+
const prior = Object.hasOwn(placements, sessionId) ? placements[sessionId] : undefined;
|
|
1299
|
+
if (prior && prior !== workspaceId) throw new RpcError(ERROR.conflict, 'Session belongs to another workspace', { reason: 'workspace_mismatch' });
|
|
1300
|
+
}
|
|
1301
|
+
if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
|
|
1302
|
+
if (worktrees) await registryCall(() => worktrees.assertAvailable(spec.cwd));
|
|
1303
|
+
if (sessionId !== undefined && (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, 'Invalid session id');
|
|
1304
|
+
if (history !== 'replay' && history !== 'skip') throw new RpcError(-32602, 'history must be replay or skip');
|
|
1305
|
+
const id = sessionId ?? `ses_${randomBytes(8).toString('hex')}`;
|
|
1306
|
+
// A root alpd is reopening after a restart: attach once it is open, rather than open it twice.
|
|
1307
|
+
await recovering.get(id);
|
|
1308
|
+
// A root whose conversation is being rewound opens once the rewind is through, on its new conversation.
|
|
1309
|
+
while (holds.has(id)) await holds.get(id)!.open;
|
|
1310
|
+
refuseFenced(id);
|
|
1311
|
+
let reservedWorkspaceId: string | undefined;
|
|
1312
|
+
const reserve = async () => {
|
|
1313
|
+
if (!registry) return;
|
|
1314
|
+
const directory = runtime.snapshot(id)?.projectRoot ?? records.get(id)?.session?.projectRoot ?? records.get(id)?.spec?.cwd ?? spec.cwd;
|
|
1315
|
+
if (workspaceId) await registryCall(() => registry!.resolve(workspaceId, directory));
|
|
1316
|
+
if (Object.hasOwn((await registry.snapshot()).sessions, id)) return;
|
|
1317
|
+
if (workspaceId) await registryCall(() => registry!.mutate('placement.assign', { sessionId: id, workspaceId }, { requestId: `reserve:${randomBytes(12).toString('hex')}` }));
|
|
1318
|
+
else await registryCall(() => registry!.mutate('placement.prepare', { sessions: [{ id, projectRoot: directory }] }, { requestId: `prepare:${randomBytes(12).toString('hex')}` }));
|
|
1319
|
+
reservedWorkspaceId = (await registry.snapshot()).sessions[id];
|
|
1320
|
+
};
|
|
1321
|
+
const rollback = async () => {
|
|
1322
|
+
if (!registry || !reservedWorkspaceId) return;
|
|
1323
|
+
await registryCall(() => registry!.mutate('placement.remove', { sessionId: id, workspaceId: reservedWorkspaceId }, { requestId: `rollback:${randomBytes(12).toString('hex')}` }));
|
|
1324
|
+
};
|
|
1325
|
+
const existing = runtime.snapshot(id);
|
|
1326
|
+
if (existing) {
|
|
1327
|
+
// Reopening a root that kept working after its viewer left: attach to it.
|
|
1328
|
+
const agent = spec.agent ?? spec.restore?.agent;
|
|
1329
|
+
if (existing.parentId || (agent !== undefined && agent !== existing.agent)) throw new RpcError(ERROR.failed, 'Session is already open');
|
|
1330
|
+
await reserve();
|
|
1331
|
+
attach(connection, id);
|
|
1332
|
+
announce(connection, id, history);
|
|
1333
|
+
return { session: existing, attached: true };
|
|
1334
|
+
}
|
|
1335
|
+
const record = records.get(id);
|
|
1336
|
+
if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
|
|
1337
|
+
if (record) {
|
|
1338
|
+
await reserve();
|
|
1339
|
+
try {
|
|
1340
|
+
const session = await resume(connection, record, spec, history, delegation);
|
|
1341
|
+
return { session, attached: false, resumed: true, ...await persisted(id) };
|
|
1342
|
+
} catch (error) { if (!runtime.snapshot(id)) await rollback(); throw error; }
|
|
1343
|
+
}
|
|
1344
|
+
const { restore: _restore, ...kept } = spec;
|
|
1345
|
+
const now = new Date().toISOString();
|
|
1346
|
+
const created: SessionRecord = { version: 1, id, rootId: id, spec: kept, delegation, status: 'initializing', createdAt: now, updatedAt: now };
|
|
1347
|
+
records.set(id, created);
|
|
1348
|
+
// A root is resumable only once its record is on disk; without it the create fails and nothing starts.
|
|
1349
|
+
try { await store?.put(created); }
|
|
1350
|
+
catch (error) {
|
|
1351
|
+
if (records.get(id) === created) records.delete(id);
|
|
1352
|
+
throw persistenceFailed(`session ${id}; it was not started`, error);
|
|
1353
|
+
}
|
|
1354
|
+
try {
|
|
1355
|
+
await reserve();
|
|
1356
|
+
attach(connection, id);
|
|
1357
|
+
const session = await runtime.open(id, spec, { history, delegation });
|
|
1358
|
+
return { session, attached: false, ...await persisted(id) };
|
|
1359
|
+
} catch (error) {
|
|
1360
|
+
detach(connection, id);
|
|
1361
|
+
records.delete(id);
|
|
1362
|
+
await store?.remove(id, [id]);
|
|
1363
|
+
await rollback();
|
|
1364
|
+
throw error;
|
|
1365
|
+
}
|
|
1366
|
+
},
|
|
1367
|
+
|
|
1368
|
+
/** The team and main a new root would run with, and the teams it may choose (ALPD §60). */
|
|
1369
|
+
async 'session.preview'(_connection, { spec }) {
|
|
1370
|
+
if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
|
|
1371
|
+
return { preview: await runtime.preview(spec) };
|
|
1372
|
+
},
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* Watches a tree. With `after`, the cursor of the last event a client has, only later
|
|
1376
|
+
* events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
|
|
1377
|
+
* with the whole timeline. The replay and the live events that follow are in cursor order.
|
|
1378
|
+
*/
|
|
1379
|
+
async 'session.history'(_connection, { sessionId, before, limit, maxBytes }) {
|
|
1380
|
+
known(sessionId);
|
|
1381
|
+
if (!store) throw new RpcError(1005, 'Durable history unavailable');
|
|
1382
|
+
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
1383
|
+
try { return await store.history(root, sessionId, { before, limit, maxBytes }); }
|
|
1384
|
+
catch (error) { if (error instanceof HistoryError) throw new RpcError(error.reason === 'stale_cursor' ? 1004 : -32602, error.message, { reason: error.reason }); throw error; }
|
|
1385
|
+
},
|
|
1386
|
+
|
|
1387
|
+
async 'session.attach'(connection, { sessionId, replay = true, after, generation }) {
|
|
1388
|
+
if (after !== undefined && (!Number.isSafeInteger(after) || after < 0)) throw new RpcError(-32602, 'after must be a cursor');
|
|
1389
|
+
known(sessionId);
|
|
1390
|
+
const root = rootIdOf(sessionId);
|
|
1391
|
+
for (;;) {
|
|
1392
|
+
// A rewind reserves its marker cursor before publishing it. Wait through afterRewind,
|
|
1393
|
+
// including if it began while a history read awaited, so replay owns every cursor <= tip.
|
|
1394
|
+
while (holds.has(root)) await holds.get(root)!.open;
|
|
1395
|
+
refuseFenced(root);
|
|
1396
|
+
const revision = holdRevision;
|
|
1397
|
+
const found = known(sessionId);
|
|
1398
|
+
let stored: Envelope[] = [];
|
|
1399
|
+
if (replay || (store && !cursors.has(root))) {
|
|
1400
|
+
// The in-memory log keeps a live tree's latest events only; older ones come from the store.
|
|
1401
|
+
const memory = logs.get(root);
|
|
1402
|
+
const covered = !!memory?.length && (memory[0].cursor ?? 1) <= (after ?? 0) + 1;
|
|
1403
|
+
if (!covered) stored = store ? await store.timeline(root) : memory ?? [];
|
|
1404
|
+
}
|
|
1405
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1406
|
+
if (generation !== undefined) {
|
|
1407
|
+
const checkpoint = await store?.history(root, sessionId, { limit: 1 });
|
|
1408
|
+
if (holds.has(root) || revision !== holdRevision) continue;
|
|
1409
|
+
if (checkpoint?.generation !== generation) throw new RpcError(1004, 'History generation changed', { reason: 'stale_cursor' });
|
|
1410
|
+
}
|
|
1411
|
+
// From here to the return nothing awaits, so no live event slips between replay and attach.
|
|
1412
|
+
const live = logs.get(root) ?? [];
|
|
1413
|
+
const tip = Math.max(cursors.get(root) ?? 0, stored.at(-1)?.cursor ?? 0, live.at(-1)?.cursor ?? 0);
|
|
1414
|
+
if (generation !== undefined && replay) {
|
|
1415
|
+
const covered = Math.max(after ?? 0, stored.at(-1)?.cursor ?? 0);
|
|
1416
|
+
const next = live.find(envelope => (envelope.cursor ?? 0) > covered)?.cursor;
|
|
1417
|
+
if ((next !== undefined && next > covered + 1) || (next === undefined && tip > covered)) {
|
|
1418
|
+
throw new RpcError(1005, 'History advanced beyond replay coverage; retry attach', { reason: 'history_gap' });
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
// Without a store the in-memory log keeps only the latest events: a cursor before them cannot continue either.
|
|
1422
|
+
const first = replay ? [...stored, ...live].find(envelope => envelope.cursor !== undefined)?.cursor : undefined;
|
|
1423
|
+
// A cursor in history a rewind set aside starts over too: what the client holds after it is not this conversation.
|
|
1424
|
+
const reset = after !== undefined && (after > tip || (replay && after < tip && (first === undefined || first > after + 1)) || !!conversation?.discarded(records.get(root), after));
|
|
1425
|
+
const from = reset ? 0 : after ?? 0;
|
|
1426
|
+
attach(connection, root);
|
|
1427
|
+
if (replay) {
|
|
1428
|
+
let last = from;
|
|
1429
|
+
for (const envelope of stored) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
|
|
1430
|
+
for (const envelope of live) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
|
|
1431
|
+
}
|
|
1432
|
+
announceQuestions(connection, root);
|
|
1433
|
+
return { session: root === found.id ? found : summary(root), cursor: tip, ...(reset ? { reset: true } : {}) };
|
|
1434
|
+
}
|
|
1435
|
+
},
|
|
1436
|
+
|
|
1437
|
+
async 'session.release'(connection, { sessionId }) {
|
|
1438
|
+
const root = rootOf.get(sessionId) ?? sessionId;
|
|
1439
|
+
detach(connection, root);
|
|
1440
|
+
return { closed: await reap(root) };
|
|
1441
|
+
},
|
|
1442
|
+
|
|
1443
|
+
async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content, ...context }) {
|
|
1444
|
+
if (typeof clientMessageId !== 'string' || !Array.isArray(content)) throw new RpcError(-32602, 'clientMessageId and content are required');
|
|
1445
|
+
if (delivery !== 'auto' && delivery !== 'steer') throw new RpcError(-32602, 'delivery must be auto or steer');
|
|
1446
|
+
// Images are inline only (the schema refuses a path or URL); here their number and decoded size.
|
|
1447
|
+
const images = content.filter((part: { type?: string }) => part?.type === 'image');
|
|
1448
|
+
if (images.length > PROMPT_IMAGES.maxCount) throw new RpcError(-32602, `A prompt takes at most ${PROMPT_IMAGES.maxCount} images`);
|
|
1449
|
+
let total = 0;
|
|
1450
|
+
for (const image of images) {
|
|
1451
|
+
const bytes = base64Bytes(image.data);
|
|
1452
|
+
total += bytes;
|
|
1453
|
+
if (bytes > PROMPT_IMAGES.maxBytes) throw new RpcError(-32602, `An image in a prompt is at most ${PROMPT_IMAGES.maxBytes} bytes`);
|
|
1454
|
+
if (total > PROMPT_IMAGES.maxTotalBytes) throw new RpcError(-32602, `The images of a prompt are at most ${PROMPT_IMAGES.maxTotalBytes} bytes together`);
|
|
1455
|
+
}
|
|
1456
|
+
// Attachments (§12.6): resolved for this principal, project and session, in order. The runtime
|
|
1457
|
+
// gets their descriptors (ids, names, digests), never a path; the fingerprint their digests.
|
|
1458
|
+
const attached = content.filter((part: { type?: string }) => part?.type === 'attachment');
|
|
1459
|
+
let resolved: RuntimeAttachment[] = [];
|
|
1460
|
+
if (attached.length) {
|
|
1461
|
+
if (!attachments || !store) throw new RpcError(ERROR.unavailable, 'This alpd does not store attachments', { reason: 'attachment_unsupported' });
|
|
1462
|
+
resolved = await attachments.resolve(principalOf(context), sessionId, attached.map((part: { attachmentId?: unknown }) => part.attachmentId));
|
|
1463
|
+
}
|
|
1464
|
+
let index = 0;
|
|
1465
|
+
const delivered: PromptContent = attached.length ? content.map((part: { type?: string }) => part?.type === 'attachment' ? resolved[index++] : part) : content;
|
|
1466
|
+
const fingerprinted = attached.length ? content.map((part: any) => part?.type === 'attachment' ? { type: 'attachment', attachmentId: part.attachmentId, sha256: resolved.find(entry => entry.attachmentId === part.attachmentId)!.sha256 } : part) : content;
|
|
1467
|
+
const send = async () => {
|
|
1468
|
+
// Failures of an open session arrive as prompt.failed events; an unknown session has no watcher.
|
|
1469
|
+
live(sessionId);
|
|
1470
|
+
await runtime.prompt(sessionId, { clientMessageId, delivery, content: delivered });
|
|
1471
|
+
};
|
|
1472
|
+
if (!store) {
|
|
1473
|
+
await gated(sessionId, send);
|
|
1474
|
+
return {};
|
|
1475
|
+
}
|
|
1476
|
+
if (!attached.length) return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
1477
|
+
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content: fingerprinted }), send, {
|
|
1478
|
+
prepare: async key => {
|
|
1479
|
+
// Never dropped, never turned into a path: a runtime that cannot read them refuses the prompt here.
|
|
1480
|
+
if (!(runtime as AlpRuntime & AttachmentRuntime).takesAttachments?.(sessionId)) throw new RpcError(ERROR.unavailable, 'This session\'s runtime cannot read attachments yet; they stay stored and the prompt was not sent', { reason: 'attachment_unsupported' });
|
|
1481
|
+
await attachments!.pin(`prompt:${key}`, sessionId, resolved.map(entry => entry.attachmentId));
|
|
1482
|
+
},
|
|
1483
|
+
abandon: key => attachments!.release(`prompt:${key}`),
|
|
1484
|
+
});
|
|
1485
|
+
},
|
|
1486
|
+
|
|
1487
|
+
/** A new root from a root's conversation cut at a turn, or from a branch a rewind set aside (§12.7). */
|
|
1488
|
+
async 'session.fork'(_connection, params) {
|
|
1489
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not fork conversations (capability session.fork is not listed)');
|
|
1490
|
+
return conversation.fork({ ...params, principal: principalOf(params) });
|
|
1491
|
+
},
|
|
1492
|
+
|
|
1493
|
+
/** The root's conversation from before a turn on, same id; the later turns stay a recoverable branch, files untouched (§12.7). */
|
|
1494
|
+
async 'session.rewind'(_connection, params) {
|
|
1495
|
+
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not rewind conversations (capability session.rewind is not listed)');
|
|
1496
|
+
return conversation.rewind(params);
|
|
1497
|
+
},
|
|
1498
|
+
|
|
1499
|
+
/** Restarts a live root's native process on its own conversation at the idle barrier (§12.8). */
|
|
1500
|
+
async 'session.reload'(_connection, params) {
|
|
1501
|
+
if (!conversation?.reloads) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not reload sessions (capability session.reload is not listed)');
|
|
1502
|
+
return conversation.reload(params);
|
|
1503
|
+
},
|
|
1504
|
+
|
|
1505
|
+
/** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
|
|
1506
|
+
async 'session.resumeCommand'(_connection, { sessionId }) {
|
|
1507
|
+
if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd has no resume command (capability session.resumeCommand is not listed)');
|
|
1508
|
+
return conversation.resumeCommand(sessionId);
|
|
1509
|
+
},
|
|
1510
|
+
|
|
1511
|
+
async 'session.interrupt'(_connection, { sessionId, turnId }) {
|
|
1512
|
+
if (turnId !== undefined) {
|
|
1513
|
+
if (typeof turnId !== 'string' || !turnId) throw new RpcError(-32602, 'turnId must be a nonempty string');
|
|
1514
|
+
if (!runtime.interruptTurn) throw new RpcError(ERROR.unavailable, 'This runtime cannot interrupt a specific turn');
|
|
1515
|
+
return { interrupted: await runtime.interruptTurn(sessionId, turnId) };
|
|
1516
|
+
}
|
|
1517
|
+
await runtime.interrupt(sessionId);
|
|
1518
|
+
return {};
|
|
1519
|
+
},
|
|
1520
|
+
|
|
1521
|
+
/**
|
|
1522
|
+
* A session's permissions mode while idle; with model, thinking or team, a live root's configuration
|
|
1523
|
+
* at the idle barrier through a restart on the same conversation (§12.9, capability session.configure.live).
|
|
1524
|
+
*/
|
|
1525
|
+
async 'session.configure'(_connection, params) {
|
|
1526
|
+
const { sessionId, mode } = params;
|
|
1527
|
+
if (params.model !== undefined || params.thinking !== undefined || params.team !== undefined) {
|
|
1528
|
+
if (!conversation?.configures) throw new RpcError(RPC_ERROR.invalidParams, 'This alpd changes only the mode of a session (capability session.configure.live is not listed)', { reason: 'invalid_params' });
|
|
1529
|
+
return conversation.configure(params);
|
|
1530
|
+
}
|
|
1531
|
+
return { session: await runtime.configure(sessionId, { mode }, {
|
|
1532
|
+
onApplied: accepted => persistAcceptedSpec(sessionId, accepted, { mode: true }),
|
|
1533
|
+
}) };
|
|
1534
|
+
},
|
|
1535
|
+
|
|
1536
|
+
/** What a change of model, thinking, team or mode would run a live root with (§12.9). */
|
|
1537
|
+
async 'session.configure.preview'(_connection, params) {
|
|
1538
|
+
if (!conversation?.configures) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not preview configurations (capability session.configure.live is not listed)');
|
|
1539
|
+
return { preview: await conversation.configurePreview(params) };
|
|
1540
|
+
},
|
|
1541
|
+
|
|
1542
|
+
async 'session.close'(_connection, { sessionId }) {
|
|
1543
|
+
await runtime.close(sessionId);
|
|
1544
|
+
return {};
|
|
1545
|
+
},
|
|
1546
|
+
|
|
1547
|
+
/** The user's name for a root, in place of its first prompt (ALPD §61). */
|
|
1548
|
+
async 'session.rename'(_connection, { sessionId, title }) {
|
|
1549
|
+
if (typeof title !== 'string' || !title.trim() || [...title].length > 200) throw new RpcError(-32602, 'title must be 1 to 200 characters');
|
|
1550
|
+
const record = rootRecord(sessionId);
|
|
1551
|
+
// A name is not activity: the record keeps its time.
|
|
1552
|
+
const before = record.title;
|
|
1553
|
+
Object.assign(record, { title: title.replace(/\s+/g, ' ').trim() });
|
|
1554
|
+
try { await store?.put(record); }
|
|
1555
|
+
catch (error) { record.title = before; throw persistenceFailed(`the name of ${record.id}`, error); }
|
|
1556
|
+
announceTitle(record.id, record.title!);
|
|
1557
|
+
return { session: summary(record.id) };
|
|
1558
|
+
},
|
|
1559
|
+
|
|
1560
|
+
/** Sets a root aside: it closes, with its tree, and leaves the lists until unarchived (ALPD §61). */
|
|
1561
|
+
async 'session.archive'(_connection, { sessionId, archived = true }) {
|
|
1562
|
+
const record = rootRecord(sessionId);
|
|
1563
|
+
if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
|
|
1564
|
+
const before = { archived: record.archived, attention: record.attention };
|
|
1565
|
+
// An archived root never asks for attention, nor does an acknowledgement on its way bring one back.
|
|
1566
|
+
Object.assign(record, { archived: archived === true ? true : undefined }, archived === true ? { attention: undefined } : {});
|
|
1567
|
+
if (archived === true) pendingAcks.delete(record.id);
|
|
1568
|
+
try { await store?.put(record); }
|
|
1569
|
+
catch (error) { Object.assign(record, before); throw persistenceFailed(`the archive state of ${record.id}`, error); }
|
|
1570
|
+
if (before.attention && !record.attention) tellAttention(record.id, undefined);
|
|
1571
|
+
return { session: summary(record.id) };
|
|
1572
|
+
},
|
|
1573
|
+
|
|
1574
|
+
'session.get'(_connection, { sessionId }) {
|
|
1575
|
+
return { session: known(sessionId) };
|
|
1576
|
+
},
|
|
1577
|
+
|
|
1578
|
+
/**
|
|
1579
|
+
* Roots first, then newest first, by id last. With `limit` a page, and `nextCursor` while more
|
|
1580
|
+
* follow; `cursor` continues after the session it names; `query` keeps the sessions whose title
|
|
1581
|
+
* or id holds every word of it; `projectRoots` those of any of these projects, as a gateway lists
|
|
1582
|
+
* a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
|
|
1583
|
+
*/
|
|
1584
|
+
'session.list'(_connection, { projectRoot, projectRoots, rootsOnly = false, includeClosed = false, includeArchived = false, limit, cursor, query } = {}): { sessions: SessionSummary[]; nextCursor?: string } {
|
|
1585
|
+
const projects = Array.isArray(projectRoots) ? new Set<string>(projectRoots) : undefined;
|
|
1586
|
+
const after = cursor === undefined ? undefined : listCursor.decode(cursor);
|
|
1587
|
+
const words = typeof query === 'string' ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
|
|
1588
|
+
const ids = new Set([...runtime.list().map(session => session.id), ...records.keys()]);
|
|
1589
|
+
const sessions = [...ids].map(summary).filter((session): session is SessionSummary => !!session)
|
|
1590
|
+
.filter(session => includeClosed || session.status === 'idle' || session.status === 'running')
|
|
1591
|
+
.filter(session => includeArchived || !session.archived)
|
|
1592
|
+
.filter(session => !rootsOnly || !session.parentId)
|
|
1593
|
+
.filter(session => projectRoot === undefined || session.projectRoot === projectRoot)
|
|
1594
|
+
.filter(session => !projects || projects.has(session.projectRoot))
|
|
1595
|
+
.filter(session => !words.length || words.every(word => `${session.title ?? ''}\n${session.id}`.toLowerCase().includes(word)))
|
|
1596
|
+
.sort((a, b) => listCursor.compare(listCursor.key(a), listCursor.key(b)))
|
|
1597
|
+
.filter(session => !after || listCursor.compare(listCursor.key(session), after) > 0);
|
|
1598
|
+
if (limit === undefined || sessions.length <= limit) return { sessions };
|
|
1599
|
+
const page = sessions.slice(0, limit);
|
|
1600
|
+
return { sessions: page, nextCursor: listCursor.encode(listCursor.key(page.at(-1)!)) };
|
|
1601
|
+
},
|
|
1602
|
+
|
|
1603
|
+
/**
|
|
1604
|
+
* A scheduled continuation of a root session: alpd opens the turn itself
|
|
1605
|
+
* when the time comes, without a user message. The target is a live root session of
|
|
1606
|
+
* the project; a session that is closed when the job is due fails the job, and the
|
|
1607
|
+
* reason is kept.
|
|
1608
|
+
*/
|
|
1609
|
+
async 'schedule.create'(_connection, { projectRoot, sessionId, dueAt, prompt } = {}) {
|
|
1610
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1611
|
+
if (typeof projectRoot !== 'string' || typeof sessionId !== 'string' || typeof dueAt !== 'string' || typeof prompt !== 'string') {
|
|
1612
|
+
throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot, sessionId, dueAt and prompt are required');
|
|
1613
|
+
}
|
|
1614
|
+
if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot must be an absolute path');
|
|
1615
|
+
const snapshot = runtime.snapshot(sessionId);
|
|
1616
|
+
if (!snapshot) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not open`);
|
|
1617
|
+
if (snapshot.parentId) throw new RpcError(RPC_ERROR.invalidParams, 'A scheduled job continues a root session');
|
|
1618
|
+
// The project is compared as a path, not as a spelling: a client that names the
|
|
1619
|
+
// same directory with a trailing slash means the same project.
|
|
1620
|
+
if (projectKey(snapshot.projectRoot) !== projectKey(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'That session does not belong to that project');
|
|
1621
|
+
if (!snapshot.persistent || !snapshot.threadId) log.warn(`a job on ${sessionId} cannot survive a restart of alpd: the session keeps no thread to resume`, { code: 'ALP_SCHEDULE_SESSION_NOT_RESUMABLE', sessionId });
|
|
1622
|
+
// The session waits for the job before the job is written, so it is not closed
|
|
1623
|
+
// in between; the job's own hold takes over once it exists.
|
|
1624
|
+
scheduler?.holdSession(sessionId);
|
|
1625
|
+
try {
|
|
1626
|
+
const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt });
|
|
1627
|
+
scheduler?.hold(job);
|
|
1628
|
+
return { job };
|
|
1629
|
+
} catch (error) {
|
|
1630
|
+
throw scheduleFailed(error);
|
|
1631
|
+
} finally {
|
|
1632
|
+
scheduler?.releaseSession(sessionId);
|
|
1633
|
+
}
|
|
1634
|
+
},
|
|
1635
|
+
|
|
1636
|
+
/** The jobs of this project, oldest first by the time they are due. */
|
|
1637
|
+
async 'schedule.list'(_connection, { projectRoot, status } = {}) {
|
|
1638
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1639
|
+
// The jobs of every project live in one directory: the project is the boundary.
|
|
1640
|
+
requestedProject(projectRoot);
|
|
1641
|
+
try {
|
|
1642
|
+
return { jobs: await schedules.list({ projectRoot, status }) };
|
|
1643
|
+
} catch (error) {
|
|
1644
|
+
throw scheduleFailed(error);
|
|
1645
|
+
}
|
|
1646
|
+
},
|
|
1647
|
+
|
|
1648
|
+
/** One job, with what became of it. */
|
|
1649
|
+
async 'schedule.get'(_connection, { id, projectRoot } = {}) {
|
|
1650
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1651
|
+
if (typeof id !== 'string') throw new RpcError(RPC_ERROR.invalidParams, 'id is required');
|
|
1652
|
+
requestedProject(projectRoot);
|
|
1653
|
+
// The store keeps the project boundary itself: a job of another project is not
|
|
1654
|
+
// there for this one, whatever the caller asked for.
|
|
1655
|
+
const job = await storeJob(id, projectRoot);
|
|
1656
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1657
|
+
return { job };
|
|
1658
|
+
},
|
|
1659
|
+
|
|
1660
|
+
/** A job that will not run: cancelled before its time. */
|
|
1661
|
+
async 'schedule.cancel'(_connection, { id, projectRoot } = {}) {
|
|
1662
|
+
if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
|
|
1663
|
+
if (typeof id !== 'string') throw new RpcError(RPC_ERROR.invalidParams, 'id is required');
|
|
1664
|
+
requestedProject(projectRoot);
|
|
1665
|
+
const job = await storeJob(id, projectRoot);
|
|
1666
|
+
if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
|
|
1667
|
+
// A job that is being delivered now is not cancelled: the delivery is under way.
|
|
1668
|
+
if (scheduler?.delivering(id)) throw new RpcError(ERROR.conflict, `Job ${id} is being delivered now`, { reason: 'key_conflict' });
|
|
1669
|
+
try {
|
|
1670
|
+
const cancelled = await schedules.cancel(id, { projectRoot });
|
|
1671
|
+
scheduler?.release(cancelled);
|
|
1672
|
+
return { job: cancelled };
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
throw scheduleFailed(error);
|
|
1675
|
+
}
|
|
1676
|
+
},
|
|
1677
|
+
};
|
|
1678
|
+
const registryCall = async (run: () => Promise<any>) => {
|
|
1679
|
+
if (!registry) throw new RpcError(ERROR.unavailable, 'Registry needs ALP_HOME');
|
|
1680
|
+
try { return await run(); } catch (e) {
|
|
1681
|
+
if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data);
|
|
1682
|
+
throw new RpcError(ERROR.failed, e instanceof Error ? e.message : String(e), { reason: 'persistence_failed' });
|
|
1683
|
+
}
|
|
1684
|
+
};
|
|
1685
|
+
const registryList = async (kind: 'projects' | 'workspaces', params: any = {}) => registryCall(async () => {
|
|
1686
|
+
const r = await registry!.snapshot();
|
|
1687
|
+
const allowed = params.projectRoots;
|
|
1688
|
+
let entries: any[] = r[kind].filter((e: any) => kind === 'projects' ? params.includeRemoved || !e.removedAt : params.includeArchived || (!e.archivedAt && !r.projects.find(p => p.id === e.projectId)?.removedAt));
|
|
1689
|
+
if (allowed !== undefined) {
|
|
1690
|
+
entries = (await Promise.all(entries.map(async e => {
|
|
1691
|
+
const directory = kind === 'projects' ? e.root : e.directory;
|
|
1692
|
+
const canonical = await fsRealpath(directory).catch(() => undefined);
|
|
1693
|
+
return canonical && (!e.canonical || canonical === e.canonical) && allowed.includes(canonical) ? e : undefined;
|
|
1694
|
+
}))).filter(Boolean);
|
|
1695
|
+
}
|
|
1696
|
+
const offset = params.cursor === undefined ? 0 : Number(params.cursor);
|
|
1697
|
+
if (!Number.isSafeInteger(offset) || offset < 0) throw new RpcError(-32602, 'Invalid registry cursor');
|
|
1698
|
+
const limit = params.limit ?? 100;
|
|
1699
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new RpcError(-32602, 'Invalid registry limit');
|
|
1700
|
+
return { [kind]: await Promise.all(entries.slice(offset, offset + limit).map(async e => ({ ...(kind === 'workspaces' ? await workspaceDescriptor(e) : e), revision: r.revision }))), revision: r.revision, total: entries.length, nextCursor: offset + limit < entries.length ? String(offset + limit) : null };
|
|
1701
|
+
});
|
|
1702
|
+
const registryMutation = (method: string, p: any) => registryCall(async () => {
|
|
1703
|
+
if (!Number.isSafeInteger(p.ifRevision) || p.ifRevision < 0) throw new RpcError(-32602, 'ifRevision is required');
|
|
1704
|
+
const { requestId, ifRevision, authorizedRoots, ...args } = p;
|
|
1705
|
+
const result = await registry!.mutate(method, args, { requestId, ifRevision, allowedRoots: authorizedRoots });
|
|
1706
|
+
return result.workspace ? { ...result, workspace: await workspaceDescriptor(result.workspace) } : result;
|
|
1707
|
+
});
|
|
1708
|
+
runtime.bindSchedules?.(async (action, params) => handlers[`schedule.${action}`](undefined as any, params));
|
|
1709
|
+
for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
|
|
1710
|
+
Object.setPrototypeOf(handlers, null);
|
|
1711
|
+
// Every v1 method name stays the daemon's, served here or not, so no extension takes one.
|
|
1712
|
+
const originalMethods = new Set([...Object.keys(handlers), ...RPC_METHODS]);
|
|
1713
|
+
const reservedNamespaces = new Set([...originalMethods].map(method => method.split('.')[0]));
|
|
1714
|
+
|
|
1715
|
+
async function invokeExtended(owner: Connection, caller: Connection, method: string, params: any) {
|
|
1716
|
+
if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, 'too many pending extension calls');
|
|
1717
|
+
const id = ++owner.nextId;
|
|
1718
|
+
const invocation = { jsonrpc: '2.0', id, method: 'extension.invoke', params: { method, params } };
|
|
1719
|
+
if (Buffer.byteLength(encodeFrame(invocation), 'utf8') > MAX_FRAME) throw new RpcError(-32600, 'ALP daemon frame exceeds size limit');
|
|
1720
|
+
return new Promise((resolve, reject) => {
|
|
1721
|
+
const timer = setTimeout(() => {
|
|
1722
|
+
owner.pending.delete(id);
|
|
1723
|
+
reject(new RpcError(ERROR.failed, `${method} timed out`));
|
|
1724
|
+
}, 30_000);
|
|
1725
|
+
owner.pending.set(id, { resolve, reject, timer, caller });
|
|
1726
|
+
try { owner.send(invocation); }
|
|
1727
|
+
catch (error) { clearTimeout(timer); owner.pending.delete(id); reject(error); }
|
|
1728
|
+
});
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
/**
|
|
1732
|
+
* Liveness is that alpd answers at all. Readiness is that it can do its work: it accepts
|
|
1733
|
+
* connections, and its state directory can be read and written now with no write failing.
|
|
1734
|
+
* Not ready is a state to fix, not a reason to stop: the checks say what and the codes
|
|
1735
|
+
* match alpd's log.
|
|
1736
|
+
*/
|
|
1737
|
+
async function health() {
|
|
1738
|
+
const checks: Array<{ id: string; ok: boolean; code?: string; message?: string }> = [{ id: 'accepting', ok: !closing, ...(closing ? { code: 'ALP_SHUTTING_DOWN', message: 'alpd is shutting down' } : {}) }];
|
|
1739
|
+
if (store) {
|
|
1740
|
+
const probe = await store.probe();
|
|
1741
|
+
checks.push({ id: 'state', ...probe });
|
|
1742
|
+
const failing = store.failing();
|
|
1743
|
+
checks.push({ id: 'persistence', ok: failing === 0, ...(failing ? { code: 'ALP_PERSISTENCE_FAILING', message: `${failing} write${failing > 1 ? 's' : ''} of sessions or timelines failed and have not been written since` } : {}) });
|
|
1744
|
+
}
|
|
1745
|
+
return { live: true, ready: checks.every(check => check.ok), checks };
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
/**
|
|
1749
|
+
* One workspace.files.list or read call: projectRoot checked, refusals answered with their code
|
|
1750
|
+
* and reason, any other failure with a fixed message (it may name a host path; alpd logs it).
|
|
1751
|
+
*/
|
|
1752
|
+
async function filesCall<T>(projectRoot: unknown, read: () => Promise<T>): Promise<T> {
|
|
1753
|
+
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot) || path.resolve(projectRoot) !== projectRoot) {
|
|
1754
|
+
throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot must be an absolute, normalized path', { reason: 'invalid_path' });
|
|
1755
|
+
}
|
|
1756
|
+
try {
|
|
1757
|
+
return await read();
|
|
1758
|
+
} catch (error) {
|
|
1759
|
+
if (error instanceof FileAccessError) throw new RpcError(error.code, error.message, { reason: error.reason });
|
|
1760
|
+
if (error instanceof FilesError) throw new RpcError(ERROR.notFound, error.message, { reason: 'not_directory' });
|
|
1761
|
+
log.error('workspace file read failed', { code: 'ALPD_FILES_FAILED', error });
|
|
1762
|
+
throw new RpcError(ERROR.failed, 'alpd could not read the workspace file');
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
/** What this daemon lists in daemon.hello: only features it serves now (docs/protocol/alp-json-rpc-v1.md §6). */
|
|
1767
|
+
const capabilities = [...(runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : []), CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...(store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : []), ...(schedules ? [CAPABILITY.schedule] : []), ...(registry ? ['workspace.registry', CAPABILITY.workspaceGit] : []), ...(worktrees ? ['workspace.worktree'] : []), ...(attachments ? [CAPABILITY.attachments] : []), ...(conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : []), ...(conversation?.reloads ? [CAPABILITY.sessionReload] : []), ...(conversation?.configures ? [CAPABILITY.sessionConfigureLive] : []), ...(conversation ? [CAPABILITY.sessionResumeCommand] : []), ...operations.capabilities];
|
|
1768
|
+
|
|
1769
|
+
/** A response too large for the wire becomes an error the client can read. */
|
|
1770
|
+
function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
|
|
1771
|
+
if (frameBytes(response) <= MAX_FRAME) return response;
|
|
1772
|
+
log.warn('a response exceeded the frame size limit', { code: 'ALP_IPC_RESPONSE_TOO_LARGE', requestId: String(response.id) });
|
|
1773
|
+
return { jsonrpc: '2.0', id: response.id, error: { code: ERROR.failed, message: 'The response exceeds the ALP frame size limit', data: { reason: 'response_too_large' } } };
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
/**
|
|
1777
|
+
* One incoming message, in the order docs/protocol/alp-json-rpc-v1.md §5 fixes: a message that is
|
|
1778
|
+
* not a single JSON-RPC 2.0 object, a frame over the limit, a notification, an invalid id or params,
|
|
1779
|
+
* the handshake, an unknown method, then the method's own params. Nothing runs before all of them pass.
|
|
1780
|
+
*/
|
|
1781
|
+
async function dispatch(connection: Connection, message: any, receivedBytes?: number) {
|
|
1782
|
+
const single = !!message && typeof message === 'object' && !Array.isArray(message);
|
|
1783
|
+
const { id, method, params } = single ? message : {} as any;
|
|
1784
|
+
const respond = (body: object) => connection.send(fits({ jsonrpc: '2.0', id: validId(id) ? id : null, ...body }));
|
|
1785
|
+
try {
|
|
1786
|
+
if (Array.isArray(message)) throw new RpcError(RPC_ERROR.invalidRequest, 'Batch requests are not supported', { reason: 'batch_unsupported' });
|
|
1787
|
+
// Validate the envelope before anything else: a frame that is not JSON-RPC 2.0 must never be
|
|
1788
|
+
// correlated against (or consume) a pending extension call, however it is shaped.
|
|
1789
|
+
if (!single || message.jsonrpc !== '2.0') throw new RpcError(RPC_ERROR.invalidRequest, 'Invalid request');
|
|
1790
|
+
const oversized = (receivedBytes ?? frameBytes(message)) > MAX_FRAME;
|
|
1791
|
+
// A frame with no `method` property is a response to an outgoing extension.invoke. It must carry
|
|
1792
|
+
// exactly one of result/error and an id; a malformed or unknown one is dropped, leaving any
|
|
1793
|
+
// pending invocation intact (never mis-correlated, never leaked).
|
|
1794
|
+
if (!Object.prototype.hasOwnProperty.call(message, 'method')) {
|
|
1795
|
+
const hasResult = Object.prototype.hasOwnProperty.call(message, 'result');
|
|
1796
|
+
const hasError = Object.prototype.hasOwnProperty.call(message, 'error');
|
|
1797
|
+
if (id === undefined || id === null || hasResult === hasError) return;
|
|
1798
|
+
const waiter = connection.pending.get(id);
|
|
1799
|
+
if (!waiter) return;
|
|
1800
|
+
connection.pending.delete(id);
|
|
1801
|
+
clearTimeout(waiter.timer);
|
|
1802
|
+
if (oversized) { waiter.reject(new RpcError(RPC_ERROR.invalidRequest, 'ALP daemon frame exceeds size limit')); return; }
|
|
1803
|
+
if (hasError) waiter.reject(new RpcError(message.error?.code ?? ERROR.failed, message.error?.message ?? 'extension call failed', message.error?.data));
|
|
1804
|
+
else waiter.resolve(message.result);
|
|
1805
|
+
return;
|
|
1806
|
+
}
|
|
1807
|
+
if (oversized) throw new RpcError(RPC_ERROR.invalidRequest, 'ALP daemon frame exceeds size limit', { reason: 'frame_too_large' });
|
|
1808
|
+
if (typeof method !== 'string') throw new RpcError(RPC_ERROR.invalidRequest, 'Invalid request');
|
|
1809
|
+
// v1 defines no notifications to the daemon: one is dropped unrun, and JSON-RPC forbids answering it.
|
|
1810
|
+
if (id === undefined) { log.debug('ignored a notification', { code: 'ALP_IPC_NOTIFICATION_IGNORED', method }); return; }
|
|
1811
|
+
if (!validId(id)) throw new RpcError(RPC_ERROR.invalidRequest, 'A request id must be a string of at most 128 characters or a safe integer', { reason: 'invalid_id' });
|
|
1812
|
+
if (params !== undefined && (params === null || typeof params !== 'object' || Array.isArray(params))) throw new RpcError(RPC_ERROR.invalidParams, 'params must be an object', { reason: 'invalid_params' });
|
|
1813
|
+
if (method === 'daemon.hello') {
|
|
1814
|
+
if (params?.protocolVersion !== PROTOCOL_VERSION) throw new RpcError(ERROR.protocol, `ALP daemon speaks protocol ${PROTOCOL_VERSION}; restart it after upgrading (alp daemon restart)`, { reason: 'protocol_version', supported: [PROTOCOL_VERSION] });
|
|
1815
|
+
const issues = validateParams(method, params)!;
|
|
1816
|
+
if (issues.length) throw invalidParams(issues);
|
|
1817
|
+
connection.helloed = true;
|
|
1818
|
+
// Terminals are listed only while the host's switch is on (and the PTY module loads).
|
|
1819
|
+
const terminalLimits = await terminals?.advertised();
|
|
1820
|
+
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities: terminalLimits ? [...capabilities, CAPABILITY.terminal] : capabilities, ...(attachments ? { attachmentLimits: attachments.limits } : {}), ...(terminalLimits ? { terminalLimits } : {}) } });
|
|
1821
|
+
return;
|
|
1822
|
+
}
|
|
1823
|
+
if (!connection.helloed) throw new RpcError(ERROR.protocol, 'daemon.hello is required first', { reason: 'hello_required' });
|
|
1824
|
+
await restored;
|
|
1825
|
+
if (!connections.has(connection)) return;
|
|
1826
|
+
const handler = Object.hasOwn(handlers, method) ? handlers[method] : undefined;
|
|
1827
|
+
if (!handler) throw new RpcError(RPC_ERROR.methodNotFound, `Unknown method '${method}'`);
|
|
1828
|
+
// Built-in methods are checked against the v1 schema; extension methods own their params.
|
|
1829
|
+
const issues = validateParams(method, params);
|
|
1830
|
+
if (issues?.length) throw invalidParams(issues);
|
|
1831
|
+
respond({ result: await handler(connection, params ?? {}) });
|
|
1832
|
+
} catch (error) {
|
|
1833
|
+
const code = error instanceof RpcError ? error.code : /is not open/.test(String((error as Error)?.message)) ? ERROR.notFound : ERROR.failed;
|
|
1834
|
+
const data = error instanceof RpcError && error.data !== undefined ? { data: error.data } : {};
|
|
1835
|
+
// Plain errors are mostly refusals of bad input; logged so an unexpected one can be traced by its request.
|
|
1836
|
+
if (!(error instanceof RpcError) && code === ERROR.failed) log.warn(`${method} failed`, { code: 'ALP_RPC_FAILED', requestId: id, sessionId: params?.sessionId, method, error });
|
|
1837
|
+
else if (error instanceof RpcError && (error.data as { reason?: string } | undefined)?.reason === 'persistence_failed') log.warn(`${method} failed`, { code: 'ALP_PERSISTENCE_FAILED', requestId: id, sessionId: params?.sessionId, method, error });
|
|
1838
|
+
respond({ error: { code, message: error instanceof Error ? error.message : String(error), ...data } });
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
const methodOwners = new Map();
|
|
1843
|
+
function disconnect(connection: Connection) {
|
|
1844
|
+
const owned = methodOwners.get(connection);
|
|
1845
|
+
if (owned) for (const method of owned) { delete handlers[method]; extensionOwners.delete(method); }
|
|
1846
|
+
methodOwners.delete(connection);
|
|
1847
|
+
for (const [id, waiting] of connection.pending) { clearTimeout(waiting.timer); waiting.reject(new Error('ALP daemon connection closed')); }
|
|
1848
|
+
connection.pending.clear();
|
|
1849
|
+
for (const owner of connections) for (const [id, waiting] of owner.pending) {
|
|
1850
|
+
if (waiting.caller !== connection) continue;
|
|
1851
|
+
clearTimeout(waiting.timer);
|
|
1852
|
+
owner.pending.delete(id);
|
|
1853
|
+
waiting.reject(new Error('ALP daemon caller connection closed'));
|
|
1854
|
+
}
|
|
1855
|
+
connections.delete(connection);
|
|
1856
|
+
watchers.delete(connection);
|
|
1857
|
+
terminals?.disconnect(connection);
|
|
1858
|
+
for (const root of [...connection.roots]) {
|
|
1859
|
+
detach(connection, root);
|
|
1860
|
+
void reap(root);
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
const server = net.createServer(socket => {
|
|
1865
|
+
if (closing) { socket.destroy(); return; }
|
|
1866
|
+
const connection: Connection = {
|
|
1867
|
+
socket,
|
|
1868
|
+
helloed: false,
|
|
1869
|
+
roots: new Set(),
|
|
1870
|
+
send(message) { if (!socket.destroyed) socket.write(encodeFrame(message)); },
|
|
1871
|
+
nextId: 0,
|
|
1872
|
+
pending: new Map(),
|
|
1873
|
+
};
|
|
1874
|
+
connections.add(connection);
|
|
1875
|
+
let buffer = '';
|
|
1876
|
+
/** UTF-8 bytes of `buffer`, kept as chunks arrive so a large frame costs linear time. */
|
|
1877
|
+
let bytes = 0;
|
|
1878
|
+
socket.setEncoding('utf8');
|
|
1879
|
+
// A frame over MAX_FRAME bytes, its newline included, ends the connection: nothing after it can be trusted to align.
|
|
1880
|
+
const tooLarge = () => { log.warn('closed a connection that sent a frame over the size limit', { code: 'ALP_IPC_FRAME_TOO_LARGE' }); buffer = ''; bytes = 0; socket.destroy(); };
|
|
1881
|
+
socket.on('data', (chunk: string) => {
|
|
1882
|
+
buffer += chunk;
|
|
1883
|
+
bytes += Buffer.byteLength(chunk, 'utf8');
|
|
1884
|
+
// Only the new chunk can hold a newline: the buffer before it had none.
|
|
1885
|
+
if (!chunk.includes('\n')) {
|
|
1886
|
+
if (bytes >= MAX_FRAME) tooLarge();
|
|
1887
|
+
return;
|
|
1888
|
+
}
|
|
1889
|
+
let start = 0;
|
|
1890
|
+
for (let index = buffer.indexOf('\n', buffer.length - chunk.length); index >= 0; index = buffer.indexOf('\n', start)) {
|
|
1891
|
+
const line = buffer.slice(start, index);
|
|
1892
|
+
start = index + 1;
|
|
1893
|
+
if (Buffer.byteLength(line, 'utf8') + 1 > MAX_FRAME) { tooLarge(); return; }
|
|
1894
|
+
if (!line.trim()) continue;
|
|
1895
|
+
let message;
|
|
1896
|
+
try { message = JSON.parse(line); } catch { log.warn('a client sent a line that is not JSON', { code: 'ALP_IPC_PARSE_ERROR', bytes: line.length }); connection.send({ jsonrpc: '2.0', id: null, error: { code: RPC_ERROR.parseError, message: 'Parse error' } }); continue; }
|
|
1897
|
+
void dispatch(connection, message, Buffer.byteLength(line, 'utf8') + 1);
|
|
1898
|
+
}
|
|
1899
|
+
// What is left has no newline yet; with one it would already be over the limit.
|
|
1900
|
+
buffer = buffer.slice(start);
|
|
1901
|
+
bytes = Buffer.byteLength(buffer, 'utf8');
|
|
1902
|
+
if (bytes >= MAX_FRAME) tooLarge();
|
|
1903
|
+
});
|
|
1904
|
+
// A client that goes away mid-write resets its connection; that alone is no trouble.
|
|
1905
|
+
socket.on('error', (error: NodeJS.ErrnoException) => log[error.code === 'ECONNRESET' || error.code === 'EPIPE' ? 'debug' : 'warn']('a client connection failed', { code: 'ALP_IPC_SOCKET_ERROR', error }));
|
|
1906
|
+
socket.on('close', () => disconnect(connection));
|
|
1907
|
+
});
|
|
1908
|
+
|
|
1909
|
+
return {
|
|
1910
|
+
extend(method, handler, owner = null) {
|
|
1911
|
+
if (typeof method !== 'string' || !method.trim()) throw new Error('extend needs a method name');
|
|
1912
|
+
if (originalMethods.has(method)) throw new Error(`${method} is a built-in method and cannot be overridden`);
|
|
1913
|
+
if (Object.hasOwn(handlers, method)) throw new Error(`${method} is already registered`);
|
|
1914
|
+
handlers[method] = async (_connection, params) => {
|
|
1915
|
+
try {
|
|
1916
|
+
const result = await handler(params ?? {});
|
|
1917
|
+
return result === undefined ? {} : result;
|
|
1918
|
+
} catch (error) {
|
|
1919
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1920
|
+
throw new Error(message.length > 2000 ? `${message.slice(0, 2000)}...` : message);
|
|
1921
|
+
}
|
|
1922
|
+
};
|
|
1923
|
+
if (owner) {
|
|
1924
|
+
if (!methodOwners.has(owner)) methodOwners.set(owner, new Set());
|
|
1925
|
+
methodOwners.get(owner).add(method);
|
|
1926
|
+
}
|
|
1927
|
+
},
|
|
1928
|
+
|
|
1929
|
+
async listen() {
|
|
1930
|
+
if (process.platform !== 'win32') {
|
|
1931
|
+
await assertPrivateDirectory(path.dirname(socketPath), { create: true });
|
|
1932
|
+
const existing = await lstat(socketPath).catch(error => { if (error.code === 'ENOENT') return undefined; throw error; });
|
|
1933
|
+
if (existing) {
|
|
1934
|
+
await assertPrivateSocket(socketPath);
|
|
1935
|
+
// Never unlink a live daemon; only ECONNREFUSED proves a stale Unix socket.
|
|
1936
|
+
const active = await new Promise<boolean>((resolve, reject) => {
|
|
1937
|
+
const probe = net.createConnection(socketPath);
|
|
1938
|
+
probe.once('connect', () => { probe.destroy(); resolve(true); });
|
|
1939
|
+
probe.once('error', error => { probe.destroy(); if ((error as NodeJS.ErrnoException).code === 'ECONNREFUSED') resolve(false); else reject(error); });
|
|
1940
|
+
probe.setTimeout(1000, () => { probe.destroy(); reject(new Error('IPC endpoint probe timed out')); });
|
|
1941
|
+
});
|
|
1942
|
+
if (active) throw new Error('IPC endpoint already in use by a running daemon');
|
|
1943
|
+
const current = await assertPrivateSocket(socketPath);
|
|
1944
|
+
if (!current || current.dev !== existing.dev || current.ino !== existing.ino) throw new Error('IPC endpoint changed during validation');
|
|
1945
|
+
await unlink(socketPath);
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
// libuv unlinks its bind path on close without checking inode identity. Bind at an
|
|
1949
|
+
// unpublished sibling, then publish; cleanup of the public endpoint is ours alone.
|
|
1950
|
+
const bindPath = process.platform === 'win32' ? socketPath : path.join(path.dirname(socketPath), `.s${randomBytes(3).toString('hex')}`);
|
|
1951
|
+
await new Promise<void>((resolve, reject) => {
|
|
1952
|
+
server.once('error', reject);
|
|
1953
|
+
server.listen(bindPath, () => { server.off('error', reject); resolve(); });
|
|
1954
|
+
});
|
|
1955
|
+
if (process.platform !== 'win32') {
|
|
1956
|
+
try {
|
|
1957
|
+
await chmod(bindPath, 0o600);
|
|
1958
|
+
const info = await lstat(bindPath);
|
|
1959
|
+
await rename(bindPath, socketPath);
|
|
1960
|
+
socketIdentity = { dev: info.dev, ino: info.ino };
|
|
1961
|
+
}
|
|
1962
|
+
catch (error) { await new Promise<void>(resolve => server.close(() => resolve())); throw error; }
|
|
1963
|
+
}
|
|
1964
|
+
},
|
|
1965
|
+
|
|
1966
|
+
local() {
|
|
1967
|
+
const events = new Set<(envelope: Envelope) => void>();
|
|
1968
|
+
const notifications = new Set<(method: string, params: any) => void>();
|
|
1969
|
+
const closes = new Set<(error: Error) => void>();
|
|
1970
|
+
const pending = new Map<number, { resolve: (value: any) => void; reject: (error: Error) => void }>();
|
|
1971
|
+
let sequence = 0;
|
|
1972
|
+
let ended = false;
|
|
1973
|
+
const connection: Connection = {
|
|
1974
|
+
helloed: true,
|
|
1975
|
+
roots: new Set(),
|
|
1976
|
+
nextId: 0,
|
|
1977
|
+
pending: new Map(),
|
|
1978
|
+
send(message: any) {
|
|
1979
|
+
if (message.method === 'event') {
|
|
1980
|
+
for (const listener of events) listener(message.params);
|
|
1981
|
+
return;
|
|
1982
|
+
}
|
|
1983
|
+
// Other notifications (terminal.event, §12.10) carry a method and no id.
|
|
1984
|
+
if (typeof message.method === 'string' && message.id === undefined) {
|
|
1985
|
+
for (const listener of notifications) listener(message.method, message.params);
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
const waiter = pending.get(message.id);
|
|
1989
|
+
if (!waiter) return;
|
|
1990
|
+
pending.delete(message.id);
|
|
1991
|
+
if (message.error) waiter.reject(new AlpRpcError(message.error));
|
|
1992
|
+
else waiter.resolve(message.result);
|
|
1993
|
+
},
|
|
1994
|
+
};
|
|
1995
|
+
connections.add(connection);
|
|
1996
|
+
return {
|
|
1997
|
+
request(method, params = {}) {
|
|
1998
|
+
if (ended) return Promise.reject(new Error('ALP daemon connection closed'));
|
|
1999
|
+
const id = ++sequence;
|
|
2000
|
+
return new Promise((resolve, reject) => {
|
|
2001
|
+
pending.set(id, { resolve, reject });
|
|
2002
|
+
void dispatch(connection, { jsonrpc: '2.0', id, method, params });
|
|
2003
|
+
});
|
|
2004
|
+
},
|
|
2005
|
+
onEvent(listener) { events.add(listener); return () => events.delete(listener); },
|
|
2006
|
+
onNotification(listener) { notifications.add(listener); return () => notifications.delete(listener); },
|
|
2007
|
+
onClose(listener) { closes.add(listener); return () => closes.delete(listener); },
|
|
2008
|
+
close() {
|
|
2009
|
+
if (ended) return;
|
|
2010
|
+
ended = true;
|
|
2011
|
+
disconnect(connection);
|
|
2012
|
+
// Match the socket client's teardown: in-flight requests fail and close listeners fire.
|
|
2013
|
+
const error = new Error('ALP daemon connection closed');
|
|
2014
|
+
for (const waiter of pending.values()) waiter.reject(error);
|
|
2015
|
+
pending.clear();
|
|
2016
|
+
for (const listener of closes) listener(error);
|
|
2017
|
+
closes.clear();
|
|
2018
|
+
},
|
|
2019
|
+
};
|
|
2020
|
+
},
|
|
2021
|
+
|
|
2022
|
+
accept(send) {
|
|
2023
|
+
const connection: Connection = { helloed: false, roots: new Set(), send, nextId: 0, pending: new Map() };
|
|
2024
|
+
connections.add(connection);
|
|
2025
|
+
let ended = false;
|
|
2026
|
+
return {
|
|
2027
|
+
receive(message) { if (!ended) void dispatch(connection, message); },
|
|
2028
|
+
close() {
|
|
2029
|
+
if (ended) return;
|
|
2030
|
+
ended = true;
|
|
2031
|
+
disconnect(connection);
|
|
2032
|
+
},
|
|
2033
|
+
};
|
|
2034
|
+
},
|
|
2035
|
+
|
|
2036
|
+
async close() {
|
|
2037
|
+
closing = true;
|
|
2038
|
+
if (sweeper) clearInterval(sweeper);
|
|
2039
|
+
attachments?.close();
|
|
2040
|
+
// Every terminal ends with alpd, its whole process tree killed.
|
|
2041
|
+
await terminals?.shutdown();
|
|
2042
|
+
// The tick that runs now is waited for: a delivery under way finishes, so its
|
|
2043
|
+
// receipt is written and the job is not left half delivered.
|
|
2044
|
+
await scheduler?.stop();
|
|
2045
|
+
const stopped = new Promise<void>(resolve => server.close(() => resolve()));
|
|
2046
|
+
for (const connection of connections) connection.socket?.destroy();
|
|
2047
|
+
await stopped;
|
|
2048
|
+
if (socketIdentity) {
|
|
2049
|
+
const current = await lstat(socketPath).catch(error => { if (error.code === 'ENOENT') return undefined; throw error; });
|
|
2050
|
+
if (current?.isSocket() && current.dev === socketIdentity.dev && current.ino === socketIdentity.ino) await unlink(socketPath);
|
|
2051
|
+
socketIdentity = undefined;
|
|
2052
|
+
}
|
|
2053
|
+
await store?.flush();
|
|
2054
|
+
},
|
|
2055
|
+
};
|
|
2056
|
+
}
|