@anhlp/alp-daemon 0.0.0-stage → 0.0.1-beta.10

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