@anhlp/alp-daemon 0.0.0-beta.2 → 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.
- package/README.md +4 -0
- package/dist/THIRD-PARTY-NOTICES.txt +27 -2
- package/dist/alpd.js +39374 -17503
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +41 -2
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +688 -0
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +156 -3
- package/dist/files.js +402 -59
- package/dist/git.d.ts +98 -0
- package/dist/git.js +1246 -0
- package/dist/gitignore.d.ts +5 -0
- package/dist/gitignore.js +26 -7
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +21 -1
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/main.js +146 -21
- package/dist/model-catalog.d.ts +2 -0
- package/dist/model-catalog.js +44 -0
- package/dist/native-entry.d.ts +2 -0
- package/dist/native-entry.js +3 -0
- package/dist/native-register.d.ts +1 -0
- package/dist/native-register.js +13 -0
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +201 -0
- package/dist/operations.d.ts +20 -3
- package/dist/operations.js +62 -21
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +298 -0
- package/dist/schedules.d.ts +70 -0
- package/dist/schedules.js +246 -0
- package/dist/server.d.ts +14 -2
- package/dist/server.js +903 -97
- package/dist/store.d.ts +72 -2
- package/dist/store.js +111 -4
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal-screen.d.ts +24 -0
- package/dist/terminal-screen.js +99 -0
- package/dist/terminals.d.ts +203 -0
- package/dist/terminals.js +570 -0
- package/dist/windows-terminal.d.ts +32 -0
- package/dist/windows-terminal.js +79 -0
- package/dist/worktrees.d.ts +65 -0
- package/dist/worktrees.js +318 -0
- package/native/README.md +201 -0
- package/native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/native/prebuilt/darwin-x64/manifest.json +11 -0
- package/native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/native/terminal-owner.c +389 -0
- package/package.json +71 -8
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +535 -71
- package/src/git.ts +1220 -0
- package/src/gitignore.ts +25 -8
- package/src/history.ts +118 -0
- package/src/index.ts +7 -0
- package/src/lifecycle.ts +283 -0
- package/src/main.ts +154 -23
- package/src/model-catalog.ts +36 -0
- package/src/native-entry.ts +5 -0
- package/src/native-register.ts +21 -0
- package/src/native-terminal.ts +127 -0
- package/src/operations.ts +53 -22
- package/src/registry.ts +238 -0
- package/src/scheduler.ts +438 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +1019 -109
- package/src/store.ts +117 -4
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +653 -0
- package/src/windows-terminal.ts +74 -0
- package/src/worktrees.ts +382 -0
package/src/server.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { realpath as fsRealpath } from 'node:fs/promises';
|
|
2
|
+
import { createRegistry, RegistryError } from './registry.js';
|
|
3
|
+
import { createWorkspaceWorktrees } from './worktrees.js';
|
|
4
|
+
import { HistoryError } from './history.js';
|
|
1
5
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
6
|
import { appendFile, chmod, mkdir, readFile, unlink, lstat, rename } from 'node:fs/promises';
|
|
3
7
|
import net from 'node:net';
|
|
@@ -5,15 +9,24 @@ import os from 'node:os';
|
|
|
5
9
|
import { assertPrivateDirectory, assertPrivateSocket } from '@anhlp/alp-client/index';
|
|
6
10
|
import path from 'node:path';
|
|
7
11
|
import { createLogger } from '@anhlp/alp-core/log';
|
|
8
|
-
import { AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from '@anhlp/alp-protocol';
|
|
12
|
+
import { AGENT_NAME, AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from '@anhlp/alp-protocol';
|
|
9
13
|
import { validateParams } from '@anhlp/alp-protocol/contract';
|
|
10
14
|
export { ERROR } from '@anhlp/alp-protocol';
|
|
11
|
-
import { DEFAULT_MODEL, models, modes, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
|
|
15
|
+
import { DEFAULT_MODEL, models, modes, type ModelCatalog, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
|
|
12
16
|
import type { Receipt, SessionRecord, SessionStatus, Store, UnreadableReceipt } from './store.js';
|
|
13
|
-
import type { SessionSummary } from '@anhlp/alp-protocol/session';
|
|
17
|
+
import type { PromptContent, SessionSummary } from '@anhlp/alp-protocol/session';
|
|
18
|
+
import type { ScheduleJob, TurnAttention } from '@anhlp/alp-protocol/index';
|
|
14
19
|
import { RpcError } from './rpc-error.js';
|
|
15
|
-
import { createOperations, type OperationsOptions } from './operations.js';
|
|
16
|
-
import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from './files.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';
|
|
17
30
|
|
|
18
31
|
/**
|
|
19
32
|
* alpd's JSON-RPC surface over one shared runtime (plans/reference/ALPD.md §3, §6, §14).
|
|
@@ -56,6 +69,43 @@ function crashPoint(name: string) {
|
|
|
56
69
|
const persistenceFailed = (what: string, error: unknown) =>
|
|
57
70
|
new RpcError(ERROR.failed, `alpd could not record ${what}: ${error instanceof Error ? error.message : String(error)}`, { reason: 'persistence_failed' });
|
|
58
71
|
|
|
72
|
+
/** A job store's refusal as a protocol error: what it refused, and why. */
|
|
73
|
+
const scheduleFailed = (error: any) => {
|
|
74
|
+
if (error instanceof RpcError) return error;
|
|
75
|
+
switch (error?.code) {
|
|
76
|
+
case 'SCHEDULE_NOT_FOUND': return new RpcError(ERROR.notFound, error.message, { reason: 'not_found' });
|
|
77
|
+
case 'SCHEDULE_NOT_PENDING': return new RpcError(ERROR.conflict, error.message, { reason: 'task_state' });
|
|
78
|
+
case 'INVALID_SCHEDULE': return new RpcError(RPC_ERROR.invalidParams, error.message, { reason: 'invalid_params' });
|
|
79
|
+
}
|
|
80
|
+
return error;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The project of a request: an absolute path, or nothing. The three methods that read
|
|
85
|
+
* or change a job refuse a missing project the same way, so a client that names no
|
|
86
|
+
* project is told what is wrong, not shown the jobs of the host.
|
|
87
|
+
*/
|
|
88
|
+
const requestedProject = (projectRoot: unknown): string => {
|
|
89
|
+
if (typeof projectRoot !== 'string' || !projectRoot) throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot is required');
|
|
90
|
+
// A relative path would be read against the daemon's own directory, which is another
|
|
91
|
+
// project.
|
|
92
|
+
if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot must be an absolute path');
|
|
93
|
+
return projectRoot;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Who an attachment call acts for: the principal context a trusted gateway puts on its own
|
|
98
|
+
* connection (its credential id and grant epoch, and the canonical workspaces it may use now), or
|
|
99
|
+
* the local owner, as workspace.worktree does (§12.6, §16).
|
|
100
|
+
*/
|
|
101
|
+
function principalOf(params: { principalId?: unknown; principalEpoch?: unknown; authorizedRoots?: unknown }): Principal {
|
|
102
|
+
return {
|
|
103
|
+
id: typeof params.principalId === 'string' ? params.principalId : 'owner',
|
|
104
|
+
epoch: typeof params.principalEpoch === 'string' ? params.principalEpoch : 'owner',
|
|
105
|
+
...(Array.isArray(params.authorizedRoots) ? { roots: params.authorizedRoots.filter((root): root is string => typeof root === 'string') } : {}),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
59
109
|
/** A stable hash of JSON data, independent of key order (as Paseo's receipts). */
|
|
60
110
|
function digest(value: unknown) {
|
|
61
111
|
return createHash('sha256').update(JSON.stringify(value, (_key, candidate) =>
|
|
@@ -67,6 +117,12 @@ function digest(value: unknown) {
|
|
|
67
117
|
type Connection = {
|
|
68
118
|
socket?: net.Socket;
|
|
69
119
|
helloed: boolean;
|
|
120
|
+
/** It said in daemon.hello that an ALP agent started it (t-ca1f): refused what only the user may do. */
|
|
121
|
+
agent?: boolean;
|
|
122
|
+
/** The 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;
|
|
70
126
|
roots: Set<string>;
|
|
71
127
|
send(message: unknown): void;
|
|
72
128
|
nextId: number;
|
|
@@ -75,6 +131,13 @@ type Connection = {
|
|
|
75
131
|
|
|
76
132
|
/** Retained events per live tree, for attach and replay. */
|
|
77
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
|
+
};
|
|
78
141
|
const SESSION_ID = /^[\w.:-]{1,128}$/;
|
|
79
142
|
const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
80
143
|
const RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
@@ -93,6 +156,17 @@ function titleFromPrompt(text: string): string | undefined {
|
|
|
93
156
|
return line ? [...line].slice(0, PROMPT_TITLE_CHARS).join('').trim() || undefined : undefined;
|
|
94
157
|
}
|
|
95
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
|
+
|
|
96
170
|
/**
|
|
97
171
|
* session.list's order and its keyset cursor: roots before children, the latest `updatedAt`
|
|
98
172
|
* first, then by id, so a page continues after the last session it holds, as Paseo's history pages
|
|
@@ -137,7 +211,9 @@ export type DaemonServer = {
|
|
|
137
211
|
* shape so every viewer agrees; re-exported here to keep `@anhlp/alp-daemon/server`'s API. */
|
|
138
212
|
export type { SessionSummary };
|
|
139
213
|
|
|
140
|
-
export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates }: {
|
|
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;
|
|
141
217
|
runtime: AlpRuntime;
|
|
142
218
|
socketPath: string;
|
|
143
219
|
version: string;
|
|
@@ -154,8 +230,32 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
154
230
|
home?: OperationsOptions['home'];
|
|
155
231
|
/** ALP's built-in agents and teams, for the library and team methods. */
|
|
156
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'>>;
|
|
157
241
|
}): DaemonServer {
|
|
158
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
|
+
});
|
|
159
259
|
/** Root of every live session. */
|
|
160
260
|
const rootOf = new Map<string, string>();
|
|
161
261
|
const attached = new Map<string, Set<Connection>>();
|
|
@@ -172,17 +272,173 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
172
272
|
/** Roots alpd reopens after a restart; they stay open until their recovery has started. */
|
|
173
273
|
const recovering = new Map<string, Promise<void>>();
|
|
174
274
|
const startedAt = new Date().toISOString();
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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 }>();
|
|
180
431
|
|
|
181
432
|
/** The project of a tree, live or recorded. */
|
|
182
433
|
function projectOf(root: string) {
|
|
183
434
|
return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
|
|
184
435
|
}
|
|
185
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
|
+
|
|
186
442
|
/**
|
|
187
443
|
* Tells watchers not attached to the tree of a question asked or resolved there, or, for those
|
|
188
444
|
* that asked for `turns`, of the end of a root's turn. Their copy has no `cursor`: it is not part
|
|
@@ -195,11 +451,45 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
195
451
|
for (const [connection, { projectRoot, turns }] of watchers) {
|
|
196
452
|
if (turn && !turns) continue;
|
|
197
453
|
if (attached.get(root)?.has(connection)) continue;
|
|
198
|
-
if (projectRoot !== undefined && project
|
|
454
|
+
if (projectRoot !== undefined && !sameProject(project, projectRoot)) continue;
|
|
199
455
|
deliver(connection, announced);
|
|
200
456
|
}
|
|
201
457
|
}
|
|
202
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
|
+
|
|
203
493
|
/** Records a change; the write is queued, and a failure is logged and counted in daemon.status. */
|
|
204
494
|
function save(record: SessionRecord & { activeTurnId?: string }, changes: Partial<SessionRecord & { activeTurnId?: string }> = {}) {
|
|
205
495
|
Object.assign(record, changes, { updatedAt: new Date().toISOString() });
|
|
@@ -230,19 +520,26 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
230
520
|
record ??= { version: 1, id: sessionId, rootId: root, status: 'initializing', createdAt: now, updatedAt: now };
|
|
231
521
|
// A reopened session keeps its last usage until its runtime reports again.
|
|
232
522
|
const usage = event.session.usage ?? record.session?.usage;
|
|
233
|
-
|
|
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 });
|
|
234
526
|
return false;
|
|
235
527
|
}
|
|
236
528
|
if (!record) return false;
|
|
237
529
|
if (event.type === 'session.updated') save(record, { session: { ...record.session, ...event.session, ...(event.session.parked ? {} : { parked: undefined }) } });
|
|
238
530
|
// Work on an archived session brings it back.
|
|
239
|
-
|
|
240
|
-
else if (event.type === 'turn.
|
|
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' } } : {}) });
|
|
241
538
|
// The latest usage, for a closed session's summary; written with the record's next change.
|
|
242
539
|
else if (event.type === 'usage' && record.session) record.session = { ...record.session, usage: event.usage };
|
|
243
540
|
else if (event.type === 'session.failed') save(record, { status: 'error', lastError: event.error });
|
|
244
541
|
else if (event.type === 'session.closed') save(record, { status: record.status === 'error' ? 'error' : 'closed', activeTurnId: undefined });
|
|
245
|
-
else if (event.type === 'item' && sessionId === root && !record.title && event.item.kind === 'user_message' &&
|
|
542
|
+
else if (event.type === 'item' && sessionId === root && !record.title && event.item.kind === 'user_message' && fromUser(event.item)) {
|
|
246
543
|
// The user's first message names an unnamed root, as Paseo names an agent (ALPD §15).
|
|
247
544
|
const title = titleFromPrompt(event.item.text);
|
|
248
545
|
if (title) { save(record, { title }); return true; }
|
|
@@ -250,6 +547,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
250
547
|
return false;
|
|
251
548
|
}
|
|
252
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
|
+
|
|
253
557
|
/**
|
|
254
558
|
* Tells the viewers of a live root its name, as a `session.updated` kept in its timeline, so a
|
|
255
559
|
* viewer attached later replays it. Nothing is sent for a root that is not open.
|
|
@@ -282,7 +586,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
282
586
|
log.push(envelope);
|
|
283
587
|
if (log.length > TREE_LOG_LIMIT) log.splice(0, log.length - TREE_LOG_LIMIT);
|
|
284
588
|
logs.set(root, log);
|
|
589
|
+
const before = records.get(root)?.attention;
|
|
285
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);
|
|
286
595
|
}
|
|
287
596
|
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
288
597
|
if (event.type === 'question' || event.type === 'question.resolved') tellWatchers(root, envelope);
|
|
@@ -298,24 +607,32 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
298
607
|
|
|
299
608
|
/**
|
|
300
609
|
* Loads records, settles sessions a crash or a stop left working, and prunes expired
|
|
301
|
-
* trees. Trees with assignments the runtime can continue,
|
|
302
|
-
* are reopened afterwards (ALPD §31).
|
|
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).
|
|
303
612
|
*/
|
|
304
613
|
async function restore() {
|
|
305
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 }));
|
|
306
616
|
const loaded = await store!.list();
|
|
307
617
|
await reconcileReceipts(loaded);
|
|
308
618
|
const now = Date.now();
|
|
309
619
|
const ended = { code: 'daemon_restarted', message: 'alpd stopped while this session was working' };
|
|
310
620
|
const epoch = `restart-${startedAt}`;
|
|
311
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));
|
|
312
627
|
const reopen: Array<{ record: SessionRecord; working: boolean }> = [];
|
|
313
628
|
const byRoot = trees(loaded);
|
|
314
629
|
const removed = await expire(byRoot, now);
|
|
315
630
|
for (const [root, tree] of byRoot) {
|
|
316
631
|
const head = tree.find(record => record.id === root);
|
|
317
632
|
if (removed.has(root)) continue;
|
|
318
|
-
|
|
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' });
|
|
319
636
|
if (tree.some(record => LIVE.includes(record.status))) seen(root, await store!.timeline(root));
|
|
320
637
|
for (const record of tree as Array<SessionRecord & { activeTurnId?: string }>) {
|
|
321
638
|
records.set(record.id, record);
|
|
@@ -324,7 +641,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
324
641
|
// The turn a crash or a stop cut off is reported interrupted, never continued as if nothing happened.
|
|
325
642
|
if (record.activeTurnId) keep(root, envelope({ type: 'turn.ended', turnId: record.activeTurnId, state: 'failed', error: { message: ended.message, code: ended.code } }));
|
|
326
643
|
if (record.id === root) {
|
|
327
|
-
save(record, record.status === 'idle' ? { status: 'closed', activeTurnId: undefined } : { status: 'error', lastError: ended, activeTurnId: undefined });
|
|
644
|
+
if (!(record.status === 'idle' && record.session?.parked)) save(record, record.status === 'idle' ? { status: 'closed', activeTurnId: undefined } : { status: 'error', lastError: ended, activeTurnId: undefined });
|
|
328
645
|
} else if (continuing.has(record.id) && reopen.some(entry => entry.record.id === root)) {
|
|
329
646
|
// The runtime reopens it under the same id; until then it is closed.
|
|
330
647
|
save(record, { status: 'closed', activeTurnId: undefined });
|
|
@@ -339,12 +656,20 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
339
656
|
}
|
|
340
657
|
}
|
|
341
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 }));
|
|
342
661
|
// Assignments whose tree cannot be reopened end now, and their tasks go back to open.
|
|
343
662
|
const reopened = new Set(reopen.map(entry => entry.record.id));
|
|
344
663
|
for (const rootId of new Set(runtime.recoverable().map(entry => entry.rootId))) {
|
|
345
664
|
if (!reopened.has(rootId)) await runtime.abandon(rootId, 'its root session cannot be reopened').catch(() => {});
|
|
346
665
|
}
|
|
347
|
-
for (const { record, working } of reopen)
|
|
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
|
+
}
|
|
348
673
|
}
|
|
349
674
|
|
|
350
675
|
function trees(list: Iterable<SessionRecord>) {
|
|
@@ -371,40 +696,62 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
371
696
|
}
|
|
372
697
|
const continuing = new Set(runtime.recoverable().map(entry => entry.rootId));
|
|
373
698
|
for (const [root, tree] of byRoot) {
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
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();
|
|
389
724
|
}
|
|
390
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 });
|
|
391
726
|
return removed;
|
|
392
727
|
}
|
|
393
728
|
|
|
394
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;
|
|
395
731
|
async function sweep() {
|
|
396
|
-
if (closing || !store) return;
|
|
732
|
+
if (closing || !store || sweeping) return;
|
|
733
|
+
sweeping = true;
|
|
397
734
|
try {
|
|
398
735
|
await restored;
|
|
399
736
|
await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
|
|
737
|
+
await journal?.prune(LIFECYCLE_RETENTION_MS);
|
|
400
738
|
await expire(trees(records.values()));
|
|
401
739
|
} catch (error) {
|
|
402
740
|
recoveryLog.warn('retention sweep failed', { code: 'ALP_RETENTION_FAILED', error });
|
|
741
|
+
} finally {
|
|
742
|
+
sweeping = false;
|
|
403
743
|
}
|
|
404
744
|
}
|
|
405
745
|
const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : undefined;
|
|
406
746
|
sweeper?.unref();
|
|
407
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
|
+
|
|
408
755
|
/**
|
|
409
756
|
* Completes receipts a crash left pending when the tree's timeline shows how the runtime
|
|
410
757
|
* answered; the rest stay pending, so their prompt answers outcome_unknown and is never
|
|
@@ -433,20 +780,31 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
433
780
|
}
|
|
434
781
|
|
|
435
782
|
/** Reopens a root nobody watches yet and continues what it and its assignments were doing. */
|
|
436
|
-
async function recoverTree(record: SessionRecord, working: boolean) {
|
|
783
|
+
async function recoverTree(record: SessionRecord, working: boolean, opened?: () => void) {
|
|
437
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?.(); };
|
|
438
790
|
try {
|
|
791
|
+
if (worktrees && record.spec?.cwd) await worktrees.assertAvailable(record.spec.cwd);
|
|
439
792
|
const stored = await treeLog(record.id);
|
|
440
793
|
seen(record.id, stored);
|
|
441
794
|
logs.set(record.id, [...stored]);
|
|
442
795
|
await runtime.open(record.id, {
|
|
443
796
|
...record.spec!,
|
|
444
797
|
persist: true,
|
|
445
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
|
|
798
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...(record.base ? { base: record.base } : {}) },
|
|
446
799
|
}, { history: 'skip', delegation: record.delegation ?? true });
|
|
447
|
-
|
|
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 });
|
|
448
803
|
recoveryLog.info(`recovered ${record.id}: ${outcomes.map(outcome => `${outcome.agent} ${outcome.outcome}`).join(', ') || 'root'}`, { event: 'recovered', sessionId: record.id, rootId: record.rootId });
|
|
449
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));
|
|
450
808
|
recoveryLog.error(`could not recover ${record.id}`, { code: 'ALP_RECOVERY_FAILED', sessionId: record.id, rootId: record.rootId, error });
|
|
451
809
|
await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {});
|
|
452
810
|
} finally {
|
|
@@ -462,7 +820,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
462
820
|
* the first delivery did, with other content a conflict; a receipt left pending by a
|
|
463
821
|
* crash, or a delivery the provider may or may not have received, is outcome_unknown.
|
|
464
822
|
*/
|
|
465
|
-
function deliverOnce(sessionId: string, clientMessageId: string, fingerprint: string, send: () => Promise<void
|
|
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
|
+
} = {}) {
|
|
466
830
|
const key = digest(['prompt', sessionId, clientMessageId]);
|
|
467
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' });
|
|
468
832
|
const answer = (receipt: Receipt, extra: object = {}) => ({ outcome: receipt.outcome ?? 'accepted', ...(receipt.error ? { error: receipt.error } : {}), ...extra });
|
|
@@ -478,12 +842,20 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
478
842
|
if (existing.state === 'pending' || existing.outcome === 'unknown') throw unknown();
|
|
479
843
|
return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
|
|
480
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();
|
|
481
848
|
const receipt = (state: Receipt['state'], changes: Partial<Receipt> = {}): Receipt => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: new Date().toISOString() });
|
|
482
849
|
live(sessionId);
|
|
850
|
+
// Attachments are pinned before anything is sent: a crash from here on keeps them.
|
|
851
|
+
await prepare?.(key);
|
|
483
852
|
crashPoint('prompt.before-receipt');
|
|
484
853
|
// Nothing is sent unless the pending receipt is on disk: a crash from here on answers outcome_unknown.
|
|
485
854
|
try { await store!.putReceipt(key, receipt('pending')); }
|
|
486
|
-
catch (error) {
|
|
855
|
+
catch (error) {
|
|
856
|
+
await abandon?.(key).catch(() => {});
|
|
857
|
+
throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error);
|
|
858
|
+
}
|
|
487
859
|
crashPoint('prompt.after-receipt');
|
|
488
860
|
// The runtime reports how the provider answered as an event, before prompt() resolves.
|
|
489
861
|
let reply: { outcome: 'accepted' | 'failed' | 'unknown'; error?: { message: string; code?: string } } = { outcome: 'accepted' };
|
|
@@ -497,6 +869,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
497
869
|
} catch (error) {
|
|
498
870
|
// The runtime refused it before reaching the provider (the session closed meanwhile): not sent.
|
|
499
871
|
await store!.removeReceipt(key).catch(() => {});
|
|
872
|
+
await abandon?.(key).catch(() => {});
|
|
500
873
|
throw error;
|
|
501
874
|
} finally {
|
|
502
875
|
stop();
|
|
@@ -516,12 +889,26 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
516
889
|
return answer(done, { durable });
|
|
517
890
|
};
|
|
518
891
|
const previous = delivering.get(key) ?? Promise.resolve();
|
|
519
|
-
const result = previous.catch(() => {}).then(attempt);
|
|
892
|
+
const result = previous.catch(() => {}).then(() => gated(sessionId, attempt));
|
|
520
893
|
delivering.set(key, result);
|
|
521
894
|
void result.finally(() => { if (delivering.get(key) === result) delivering.delete(key); }).catch(() => {});
|
|
522
895
|
return result;
|
|
523
896
|
}
|
|
524
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
|
+
|
|
525
912
|
/**
|
|
526
913
|
* Waits for an opened root's record and timeline (its native thread) to be written, so a
|
|
527
914
|
* crash after the answer can still resume it (ALPD §66); `durable: false` when they were not.
|
|
@@ -533,13 +920,16 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
533
920
|
|
|
534
921
|
function forget(root: string) {
|
|
535
922
|
if (runtime.snapshot(root)) return;
|
|
536
|
-
for (const [id, candidate] of rootOf) if (candidate === root) rootOf.delete(id);
|
|
923
|
+
for (const [id, candidate] of rootOf) if (candidate === root) { rootOf.delete(id); recoveryErrors.delete(id); }
|
|
924
|
+
recoveryErrors.delete(root);
|
|
537
925
|
logs.delete(root);
|
|
538
926
|
}
|
|
539
927
|
|
|
540
928
|
/** Closes an idle root that no client watches. */
|
|
541
929
|
async function reap(root: string) {
|
|
542
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;
|
|
543
933
|
const session = runtime.snapshot(root);
|
|
544
934
|
if (!session || session.busy) return false;
|
|
545
935
|
await runtime.close(root).catch(() => {});
|
|
@@ -565,7 +955,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
565
955
|
const session = live ?? record?.session;
|
|
566
956
|
if (!session) return undefined;
|
|
567
957
|
const status: SessionStatus = live ? (live.activeTurnId ? 'running' : 'idle') : record?.status === 'error' ? 'error' : 'closed';
|
|
568
|
-
return { ...session, ...(live ? {} : { busy: false, activeTurnId: undefined }), status, title: record?.title, ...(record?.archived ? { archived: true } : {}), lastError: record?.lastError, createdAt: record?.createdAt, updatedAt: record?.updatedAt };
|
|
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) : {}) };
|
|
569
959
|
}
|
|
570
960
|
|
|
571
961
|
/** The record of a root the user acts on. */
|
|
@@ -645,31 +1035,108 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
645
1035
|
if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, 'This session cannot be resumed');
|
|
646
1036
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
647
1037
|
if (agent !== undefined && agent !== session.agent) throw new RpcError(ERROR.failed, 'Cannot resume a session as a different ALP agent');
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
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;
|
|
652
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);
|
|
653
1050
|
const opened = await runtime.open(record.id, {
|
|
654
1051
|
...record.spec,
|
|
655
1052
|
...(spec.mode !== undefined ? { mode: spec.mode } : {}),
|
|
656
1053
|
...(spec.thinking !== undefined ? { thinking: spec.thinking } : {}),
|
|
657
1054
|
persist: true,
|
|
658
|
-
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
|
|
1055
|
+
restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...(record.base ? { base: record.base } : {}) },
|
|
659
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 });
|
|
660
1059
|
if (history === 'replay') replayHistory(connection, record.id, stored);
|
|
661
1060
|
return opened;
|
|
662
|
-
} catch (error) {
|
|
1061
|
+
} catch (error: any) {
|
|
1062
|
+
// A durable-write failure does not undo a successful open or abandon its viewer.
|
|
1063
|
+
if (applied) throw error;
|
|
663
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));
|
|
664
1067
|
throw error;
|
|
1068
|
+
} finally {
|
|
1069
|
+
clearOpening(record.id);
|
|
665
1070
|
}
|
|
666
1071
|
}
|
|
667
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
|
+
|
|
668
1087
|
/** Projects, tasks, library and settings (docs/protocol/alp-json-rpc-v1.md §15); a team save syncs the projects sessions ran in. */
|
|
669
|
-
const
|
|
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(() => {}); } });
|
|
670
1133
|
const extensionOwners = new Map<string, Connection>();
|
|
1134
|
+
/** workspace.files.find's snapshots, each for the connection that asked. */
|
|
1135
|
+
const findPages = createFindPages();
|
|
671
1136
|
const handlers: Record<string, (connection: Connection, params: any) => Promise<unknown> | unknown> = {
|
|
672
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');
|
|
673
1140
|
const method = params?.method;
|
|
674
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');
|
|
675
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');
|
|
@@ -721,19 +1188,51 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
721
1188
|
},
|
|
722
1189
|
|
|
723
1190
|
'question.list'(_connection, { projectRoot } = {}) {
|
|
724
|
-
return { questions: runtime.questions().filter(question => projectRoot === undefined || projectOf(question.rootId)
|
|
1191
|
+
return { questions: runtime.questions().filter(question => projectRoot === undefined || sameProject(projectOf(question.rootId), projectRoot)) };
|
|
725
1192
|
},
|
|
726
1193
|
|
|
727
1194
|
/**
|
|
728
1195
|
* The questions waiting now; from then on this connection is told of `question` and
|
|
729
1196
|
* `question.resolved` in every tree, or those of `projectRoot`, attached or not. Calling it
|
|
730
1197
|
* again replaces the filter; it lasts as long as the connection (ALPD §15). With `turns`, also
|
|
731
|
-
* of `turn.ended` of every root
|
|
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).
|
|
732
1200
|
*/
|
|
733
|
-
'question.watch'(connection, { projectRoot, turns } = {}) {
|
|
1201
|
+
'question.watch'(connection, { projectRoot, turns, attention } = {}) {
|
|
734
1202
|
// No await between registering and listing: an event either is in the list or follows it.
|
|
735
|
-
watchers.set(connection, { projectRoot, turns: turns === true });
|
|
736
|
-
return {
|
|
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 };
|
|
737
1236
|
},
|
|
738
1237
|
|
|
739
1238
|
/**
|
|
@@ -757,13 +1256,30 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
757
1256
|
* read-only, confined to it, no link followed, blocked paths always refused, .gitignore'd ones
|
|
758
1257
|
* unless includeIgnored (docs/protocol/alp-json-rpc-v1.md §12.4, ALPD §15).
|
|
759
1258
|
*/
|
|
760
|
-
async 'workspace.files.list'(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
761
|
-
return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
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 }));
|
|
762
1261
|
},
|
|
763
1262
|
async 'workspace.files.read'(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
764
1263
|
return filesCall(projectRoot, () => readWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
765
1264
|
},
|
|
766
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
|
+
|
|
767
1283
|
/** The project board: live claims, decisions and findings (ALPD §18). */
|
|
768
1284
|
async 'board.list'(_connection, { projectRoot } = {}) {
|
|
769
1285
|
if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, 'An absolute projectRoot is required');
|
|
@@ -796,13 +1312,22 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
796
1312
|
}
|
|
797
1313
|
},
|
|
798
1314
|
|
|
799
|
-
'question.answer'(
|
|
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' });
|
|
800
1318
|
if (typeof questionId !== 'string') throw new RpcError(-32602, 'questionId is required');
|
|
801
1319
|
if (dismiss !== true && typeof text !== 'string') throw new RpcError(-32602, 'text or dismiss is required');
|
|
802
1320
|
// A unique prefix is enough, as in the CLI.
|
|
803
1321
|
const matches = runtime.questions().filter(question => question.id === questionId || question.id.startsWith(questionId));
|
|
804
1322
|
if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
|
|
805
|
-
|
|
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
|
+
});
|
|
806
1331
|
return { questionId: matches[0].id };
|
|
807
1332
|
},
|
|
808
1333
|
|
|
@@ -811,20 +1336,101 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
811
1336
|
return {};
|
|
812
1337
|
},
|
|
813
1338
|
|
|
814
|
-
'
|
|
815
|
-
|
|
816
|
-
|
|
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
|
+
}
|
|
817
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));
|
|
818
1406
|
if (sessionId !== undefined && (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, 'Invalid session id');
|
|
819
1407
|
if (history !== 'replay' && history !== 'skip') throw new RpcError(-32602, 'history must be replay or skip');
|
|
820
1408
|
const id = sessionId ?? `ses_${randomBytes(8).toString('hex')}`;
|
|
821
1409
|
// A root alpd is reopening after a restart: attach once it is open, rather than open it twice.
|
|
822
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
|
+
};
|
|
823
1428
|
const existing = runtime.snapshot(id);
|
|
824
1429
|
if (existing) {
|
|
825
1430
|
// Reopening a root that kept working after its viewer left: attach to it.
|
|
826
1431
|
const agent = spec.agent ?? spec.restore?.agent;
|
|
827
1432
|
if (existing.parentId || (agent !== undefined && agent !== existing.agent)) throw new RpcError(ERROR.failed, 'Session is already open');
|
|
1433
|
+
await reserve();
|
|
828
1434
|
attach(connection, id);
|
|
829
1435
|
announce(connection, id, history);
|
|
830
1436
|
return { session: existing, attached: true };
|
|
@@ -832,8 +1438,11 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
832
1438
|
const record = records.get(id);
|
|
833
1439
|
if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
|
|
834
1440
|
if (record) {
|
|
835
|
-
|
|
836
|
-
|
|
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; }
|
|
837
1446
|
}
|
|
838
1447
|
const { restore: _restore, ...kept } = spec;
|
|
839
1448
|
const now = new Date().toISOString();
|
|
@@ -845,14 +1454,16 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
845
1454
|
if (records.get(id) === created) records.delete(id);
|
|
846
1455
|
throw persistenceFailed(`session ${id}; it was not started`, error);
|
|
847
1456
|
}
|
|
848
|
-
attach(connection, id);
|
|
849
1457
|
try {
|
|
1458
|
+
await reserve();
|
|
1459
|
+
attach(connection, id);
|
|
850
1460
|
const session = await runtime.open(id, spec, { history, delegation });
|
|
851
1461
|
return { session, attached: false, ...await persisted(id) };
|
|
852
1462
|
} catch (error) {
|
|
853
1463
|
detach(connection, id);
|
|
854
1464
|
records.delete(id);
|
|
855
1465
|
await store?.remove(id, [id]);
|
|
1466
|
+
await rollback();
|
|
856
1467
|
throw error;
|
|
857
1468
|
}
|
|
858
1469
|
},
|
|
@@ -868,32 +1479,65 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
868
1479
|
* events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
|
|
869
1480
|
* with the whole timeline. The replay and the live events that follow are in cursor order.
|
|
870
1481
|
*/
|
|
871
|
-
async 'session.
|
|
872
|
-
|
|
873
|
-
|
|
1482
|
+
async 'session.history'(_connection, { sessionId, before, limit, maxBytes }) {
|
|
1483
|
+
known(sessionId);
|
|
1484
|
+
if (!store) throw new RpcError(1005, 'Durable history unavailable');
|
|
874
1485
|
const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
|
|
875
|
-
|
|
876
|
-
if (
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
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 } : {}) };
|
|
894
1540
|
}
|
|
895
|
-
announceQuestions(connection, root);
|
|
896
|
-
return { session: root === found.id ? found : summary(root), cursor: tip, ...(reset ? { reset: true } : {}) };
|
|
897
1541
|
},
|
|
898
1542
|
|
|
899
1543
|
async 'session.release'(connection, { sessionId }) {
|
|
@@ -902,9 +1546,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
902
1546
|
return { closed: await reap(root) };
|
|
903
1547
|
},
|
|
904
1548
|
|
|
905
|
-
async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content }) {
|
|
1549
|
+
async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content, ...context }) {
|
|
906
1550
|
if (typeof clientMessageId !== 'string' || !Array.isArray(content)) throw new RpcError(-32602, 'clientMessageId and content are required');
|
|
907
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' });
|
|
908
1555
|
// Images are inline only (the schema refuses a path or URL); here their number and decoded size.
|
|
909
1556
|
const images = content.filter((part: { type?: string }) => part?.type === 'image');
|
|
910
1557
|
if (images.length > PROMPT_IMAGES.maxCount) throw new RpcError(-32602, `A prompt takes at most ${PROMPT_IMAGES.maxCount} images`);
|
|
@@ -915,25 +1562,121 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
915
1562
|
if (bytes > PROMPT_IMAGES.maxBytes) throw new RpcError(-32602, `An image in a prompt is at most ${PROMPT_IMAGES.maxBytes} bytes`);
|
|
916
1563
|
if (total > PROMPT_IMAGES.maxTotalBytes) throw new RpcError(-32602, `The images of a prompt are at most ${PROMPT_IMAGES.maxTotalBytes} bytes together`);
|
|
917
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;
|
|
918
1576
|
const send = async () => {
|
|
919
1577
|
// Failures of an open session arrive as prompt.failed events; an unknown session has no watcher.
|
|
920
1578
|
live(sessionId);
|
|
921
|
-
await runtime.prompt(sessionId, { clientMessageId, delivery, content });
|
|
1579
|
+
await runtime.prompt(sessionId, { clientMessageId, delivery, content: delivered });
|
|
922
1580
|
};
|
|
923
1581
|
if (!store) {
|
|
924
|
-
await send
|
|
1582
|
+
await gated(sessionId, send);
|
|
925
1583
|
return {};
|
|
926
1584
|
}
|
|
927
|
-
return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
|
|
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);
|
|
928
1608
|
},
|
|
929
1609
|
|
|
930
|
-
|
|
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
|
+
}
|
|
931
1657
|
await runtime.interrupt(sessionId);
|
|
932
1658
|
return {};
|
|
933
1659
|
},
|
|
934
1660
|
|
|
935
|
-
|
|
936
|
-
|
|
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) };
|
|
937
1680
|
},
|
|
938
1681
|
|
|
939
1682
|
async 'session.close'(_connection, { sessionId }) {
|
|
@@ -958,10 +1701,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
958
1701
|
async 'session.archive'(_connection, { sessionId, archived = true }) {
|
|
959
1702
|
const record = rootRecord(sessionId);
|
|
960
1703
|
if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
|
|
961
|
-
const before = record.archived;
|
|
962
|
-
|
|
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);
|
|
963
1708
|
try { await store?.put(record); }
|
|
964
|
-
catch (error) { 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);
|
|
965
1711
|
return { session: summary(record.id) };
|
|
966
1712
|
},
|
|
967
1713
|
|
|
@@ -976,16 +1722,41 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
976
1722
|
* a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
|
|
977
1723
|
*/
|
|
978
1724
|
'session.list'(_connection, { projectRoot, projectRoots, rootsOnly = false, includeClosed = false, includeArchived = false, limit, cursor, query } = {}): { sessions: SessionSummary[]; nextCursor?: string } {
|
|
979
|
-
const
|
|
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;
|
|
980
1739
|
const after = cursor === undefined ? undefined : listCursor.decode(cursor);
|
|
981
1740
|
const words = typeof query === 'string' ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
|
|
982
|
-
const
|
|
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
|
+
}
|
|
983
1754
|
const sessions = [...ids].map(summary).filter((session): session is SessionSummary => !!session)
|
|
984
1755
|
.filter(session => includeClosed || session.status === 'idle' || session.status === 'running')
|
|
985
1756
|
.filter(session => includeArchived || !session.archived)
|
|
986
1757
|
.filter(session => !rootsOnly || !session.parentId)
|
|
987
|
-
.filter(session =>
|
|
988
|
-
.filter(session => !
|
|
1758
|
+
.filter(session => wantedKey === undefined || keyOf(session.projectRoot) === wantedKey)
|
|
1759
|
+
.filter(session => !allowedKeys || allowedKeys.has(keyOf(session.projectRoot)))
|
|
989
1760
|
.filter(session => !words.length || words.every(word => `${session.title ?? ''}\n${session.id}`.toLowerCase().includes(word)))
|
|
990
1761
|
.sort((a, b) => listCursor.compare(listCursor.key(a), listCursor.key(b)))
|
|
991
1762
|
.filter(session => !after || listCursor.compare(listCursor.key(session), after) > 0);
|
|
@@ -993,8 +1764,115 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
993
1764
|
const page = sessions.slice(0, limit);
|
|
994
1765
|
return { sessions: page, nextCursor: listCursor.encode(listCursor.key(page.at(-1)!)) };
|
|
995
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
|
+
},
|
|
996
1843
|
};
|
|
997
|
-
|
|
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 });
|
|
998
1876
|
Object.setPrototypeOf(handlers, null);
|
|
999
1877
|
// Every v1 method name stays the daemon's, served here or not, so no extension takes one.
|
|
1000
1878
|
const originalMethods = new Set([...Object.keys(handlers), ...RPC_METHODS]);
|
|
@@ -1003,7 +1881,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1003
1881
|
async function invokeExtended(owner: Connection, caller: Connection, method: string, params: any) {
|
|
1004
1882
|
if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, 'too many pending extension calls');
|
|
1005
1883
|
const id = ++owner.nextId;
|
|
1006
|
-
const invocation = { jsonrpc: '2.0', id, method: 'extension.invoke', params: { method, params } };
|
|
1884
|
+
const invocation = { jsonrpc: '2.0', id, method: 'extension.invoke', params: { method, params, caller: { agent: caller.agent === true, ...(caller.agentName !== undefined ? { agentName: caller.agentName } : {}) } } };
|
|
1007
1885
|
if (Buffer.byteLength(encodeFrame(invocation), 'utf8') > MAX_FRAME) throw new RpcError(-32600, 'ALP daemon frame exceeds size limit');
|
|
1008
1886
|
return new Promise((resolve, reject) => {
|
|
1009
1887
|
const timer = setTimeout(() => {
|
|
@@ -1052,7 +1930,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1052
1930
|
}
|
|
1053
1931
|
|
|
1054
1932
|
/** What this daemon lists in daemon.hello: only features it serves now (docs/protocol/alp-json-rpc-v1.md §6). */
|
|
1055
|
-
const capabilities = [CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...(store ? [CAPABILITY.promptReceipts] : []), ...operations.capabilities];
|
|
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];
|
|
1056
1934
|
|
|
1057
1935
|
/** A response too large for the wire becomes an error the client can read. */
|
|
1058
1936
|
function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
|
|
@@ -1102,8 +1980,25 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1102
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] });
|
|
1103
1981
|
const issues = validateParams(method, params)!;
|
|
1104
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' });
|
|
1105
1986
|
connection.helloed = true;
|
|
1106
|
-
|
|
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 } : {}) } });
|
|
1107
2002
|
return;
|
|
1108
2003
|
}
|
|
1109
2004
|
if (!connection.helloed) throw new RpcError(ERROR.protocol, 'daemon.hello is required first', { reason: 'hello_required' });
|
|
@@ -1140,6 +2035,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1140
2035
|
}
|
|
1141
2036
|
connections.delete(connection);
|
|
1142
2037
|
watchers.delete(connection);
|
|
2038
|
+
terminals?.disconnect(connection);
|
|
1143
2039
|
for (const root of [...connection.roots]) {
|
|
1144
2040
|
detach(connection, root);
|
|
1145
2041
|
void reap(root);
|
|
@@ -1250,6 +2146,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1250
2146
|
|
|
1251
2147
|
local() {
|
|
1252
2148
|
const events = new Set<(envelope: Envelope) => void>();
|
|
2149
|
+
const notifications = new Set<(method: string, params: any) => void>();
|
|
1253
2150
|
const closes = new Set<(error: Error) => void>();
|
|
1254
2151
|
const pending = new Map<number, { resolve: (value: any) => void; reject: (error: Error) => void }>();
|
|
1255
2152
|
let sequence = 0;
|
|
@@ -1264,6 +2161,11 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1264
2161
|
for (const listener of events) listener(message.params);
|
|
1265
2162
|
return;
|
|
1266
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
|
+
}
|
|
1267
2169
|
const waiter = pending.get(message.id);
|
|
1268
2170
|
if (!waiter) return;
|
|
1269
2171
|
pending.delete(message.id);
|
|
@@ -1282,6 +2184,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1282
2184
|
});
|
|
1283
2185
|
},
|
|
1284
2186
|
onEvent(listener) { events.add(listener); return () => events.delete(listener); },
|
|
2187
|
+
onNotification(listener) { notifications.add(listener); return () => notifications.delete(listener); },
|
|
1285
2188
|
onClose(listener) { closes.add(listener); return () => closes.delete(listener); },
|
|
1286
2189
|
close() {
|
|
1287
2190
|
if (ended) return;
|
|
@@ -1312,8 +2215,15 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1312
2215
|
},
|
|
1313
2216
|
|
|
1314
2217
|
async close() {
|
|
2218
|
+
unsubscribeCatalog?.();
|
|
1315
2219
|
closing = true;
|
|
1316
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();
|
|
1317
2227
|
const stopped = new Promise<void>(resolve => server.close(() => resolve()));
|
|
1318
2228
|
for (const connection of connections) connection.socket?.destroy();
|
|
1319
2229
|
await stopped;
|