@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.
Files changed (104) hide show
  1. package/README.md +4 -0
  2. package/dist/THIRD-PARTY-NOTICES.txt +27 -2
  3. package/dist/alpd.js +39374 -17503
  4. package/dist/attachments.d.ts +187 -0
  5. package/dist/attachments.js +856 -0
  6. package/dist/build-manifest.json +41 -2
  7. package/dist/conversation.d.ts +119 -0
  8. package/dist/conversation.js +688 -0
  9. package/dist/disk.d.ts +67 -0
  10. package/dist/disk.js +152 -0
  11. package/dist/files.d.ts +156 -3
  12. package/dist/files.js +402 -59
  13. package/dist/git.d.ts +98 -0
  14. package/dist/git.js +1246 -0
  15. package/dist/gitignore.d.ts +5 -0
  16. package/dist/gitignore.js +26 -7
  17. package/dist/history.d.ts +24 -0
  18. package/dist/history.js +149 -0
  19. package/dist/index.d.ts +7 -0
  20. package/dist/index.js +21 -1
  21. package/dist/lifecycle.d.ts +101 -0
  22. package/dist/lifecycle.js +239 -0
  23. package/dist/main.js +146 -21
  24. package/dist/model-catalog.d.ts +2 -0
  25. package/dist/model-catalog.js +44 -0
  26. package/dist/native-entry.d.ts +2 -0
  27. package/dist/native-entry.js +3 -0
  28. package/dist/native-register.d.ts +1 -0
  29. package/dist/native-register.js +13 -0
  30. package/dist/native-terminal.d.ts +45 -0
  31. package/dist/native-terminal.js +201 -0
  32. package/dist/operations.d.ts +20 -3
  33. package/dist/operations.js +62 -21
  34. package/dist/registry.d.ts +89 -0
  35. package/dist/registry.js +343 -0
  36. package/dist/scheduler.d.ts +96 -0
  37. package/dist/scheduler.js +298 -0
  38. package/dist/schedules.d.ts +70 -0
  39. package/dist/schedules.js +246 -0
  40. package/dist/server.d.ts +14 -2
  41. package/dist/server.js +903 -97
  42. package/dist/store.d.ts +72 -2
  43. package/dist/store.js +111 -4
  44. package/dist/terminal-native/README.md +201 -0
  45. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  46. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  48. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  49. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  50. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  51. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  52. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  53. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  54. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  55. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  56. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  57. package/dist/terminal-native/terminal-owner.c +389 -0
  58. package/dist/terminal-screen.d.ts +24 -0
  59. package/dist/terminal-screen.js +99 -0
  60. package/dist/terminals.d.ts +203 -0
  61. package/dist/terminals.js +570 -0
  62. package/dist/windows-terminal.d.ts +32 -0
  63. package/dist/windows-terminal.js +79 -0
  64. package/dist/worktrees.d.ts +65 -0
  65. package/dist/worktrees.js +318 -0
  66. package/native/README.md +201 -0
  67. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  68. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  69. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  70. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  71. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  72. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  73. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  74. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  75. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  76. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  77. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  78. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  79. package/native/terminal-owner.c +389 -0
  80. package/package.json +71 -8
  81. package/src/attachments.ts +908 -0
  82. package/src/conversation.ts +857 -0
  83. package/src/disk.ts +175 -0
  84. package/src/files.ts +535 -71
  85. package/src/git.ts +1220 -0
  86. package/src/gitignore.ts +25 -8
  87. package/src/history.ts +118 -0
  88. package/src/index.ts +7 -0
  89. package/src/lifecycle.ts +283 -0
  90. package/src/main.ts +154 -23
  91. package/src/model-catalog.ts +36 -0
  92. package/src/native-entry.ts +5 -0
  93. package/src/native-register.ts +21 -0
  94. package/src/native-terminal.ts +127 -0
  95. package/src/operations.ts +53 -22
  96. package/src/registry.ts +238 -0
  97. package/src/scheduler.ts +438 -0
  98. package/src/schedules.ts +297 -0
  99. package/src/server.ts +1019 -109
  100. package/src/store.ts +117 -4
  101. package/src/terminal-screen.ts +74 -0
  102. package/src/terminals.ts +653 -0
  103. package/src/windows-terminal.ts +74 -0
  104. package/src/worktrees.ts +382 -0
package/dist/server.js CHANGED
@@ -1,4 +1,8 @@
1
1
  // packages/daemon/src/server.ts
2
+ import { realpath as fsRealpath } from "node:fs/promises";
3
+ import { createRegistry, RegistryError } from "./registry.js";
4
+ import { createWorkspaceWorktrees } from "./worktrees.js";
5
+ import { HistoryError } from "./history.js";
2
6
  import { createHash, randomBytes } from "node:crypto";
3
7
  import { appendFile, chmod, mkdir, readFile, unlink, lstat, rename } from "node:fs/promises";
4
8
  import net from "node:net";
@@ -6,13 +10,20 @@ import os from "node:os";
6
10
  import { assertPrivateDirectory, assertPrivateSocket } from "@anhlp/alp-client/index";
7
11
  import path from "node:path";
8
12
  import { createLogger } from "@anhlp/alp-core/log";
9
- import { AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from "@anhlp/alp-protocol";
13
+ import { AGENT_NAME, AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from "@anhlp/alp-protocol";
10
14
  import { validateParams } from "@anhlp/alp-protocol/contract";
11
15
  import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
12
16
  import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
13
17
  import { RpcError } from "./rpc-error.js";
14
- import { createOperations } from "./operations.js";
15
- import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from "./files.js";
18
+ import { createOperations, fromCore } from "./operations.js";
19
+ import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, searchWorkspaceFiles } from "./files.js";
20
+ import { createGitReader } from "./git.js";
21
+ import { createScheduleStore, projectKey } from "./schedules.js";
22
+ import { createAttachmentStore } from "./attachments.js";
23
+ import { clientMessageId as scheduleMessageId, createScheduler, SCHEDULE_TICK_MS } from "./scheduler.js";
24
+ import { createLifecycleJournal, LIFECYCLE_RETENTION_MS } from "./lifecycle.js";
25
+ import { createConversation } from "./conversation.js";
26
+ import { createTerminalService } from "./terminals.js";
16
27
  var log = createLogger({ component: "alpd.ipc" });
17
28
  var recoveryLog = createLogger({ component: "alpd.recovery" });
18
29
  function validId(id) {
@@ -29,10 +40,39 @@ function crashPoint(name) {
29
40
  process.kill(process.pid, "SIGKILL");
30
41
  }
31
42
  var persistenceFailed = (what, error) => new RpcError(ERROR.failed, `alpd could not record ${what}: ${error instanceof Error ? error.message : String(error)}`, { reason: "persistence_failed" });
43
+ var scheduleFailed = (error) => {
44
+ if (error instanceof RpcError) return error;
45
+ switch (error?.code) {
46
+ case "SCHEDULE_NOT_FOUND":
47
+ return new RpcError(ERROR.notFound, error.message, { reason: "not_found" });
48
+ case "SCHEDULE_NOT_PENDING":
49
+ return new RpcError(ERROR.conflict, error.message, { reason: "task_state" });
50
+ case "INVALID_SCHEDULE":
51
+ return new RpcError(RPC_ERROR.invalidParams, error.message, { reason: "invalid_params" });
52
+ }
53
+ return error;
54
+ };
55
+ var requestedProject = (projectRoot) => {
56
+ if (typeof projectRoot !== "string" || !projectRoot) throw new RpcError(RPC_ERROR.invalidParams, "projectRoot is required");
57
+ if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute path");
58
+ return projectRoot;
59
+ };
60
+ function principalOf(params) {
61
+ return {
62
+ id: typeof params.principalId === "string" ? params.principalId : "owner",
63
+ epoch: typeof params.principalEpoch === "string" ? params.principalEpoch : "owner",
64
+ ...Array.isArray(params.authorizedRoots) ? { roots: params.authorizedRoots.filter((root) => typeof root === "string") } : {}
65
+ };
66
+ }
32
67
  function digest(value) {
33
68
  return createHash("sha256").update(JSON.stringify(value, (_key, candidate) => candidate !== null && typeof candidate === "object" && !Array.isArray(candidate) ? Object.fromEntries(Object.entries(candidate).sort(([a], [b]) => a.localeCompare(b))) : candidate)).digest("hex");
34
69
  }
35
70
  var TREE_LOG_LIMIT = 2e4;
71
+ var AGENT_CAPABILITY = "principal.agent";
72
+ var agentRefused = (connection, method) => {
73
+ if (connection.agent) throw new RpcError(ERROR.forbidden, `${method} is the user's; this connection was opened by an ALP agent`, { reason: "user_only" });
74
+ return void 0;
75
+ };
36
76
  var SESSION_ID = /^[\w.:-]{1,128}$/;
37
77
  var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
38
78
  var RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -43,6 +83,10 @@ function titleFromPrompt(text) {
43
83
  const line = text.split(/\r?\n/).map((entry) => entry.replace(/\s+/g, " ").trim()).find(Boolean);
44
84
  return line ? [...line].slice(0, PROMPT_TITLE_CHARS).join("").trim() || void 0 : void 0;
45
85
  }
86
+ function fromUser(item) {
87
+ if (item.clientMessageId?.startsWith("alp-")) return false;
88
+ return item.origin !== void 0 ? item.origin === "user" : item.clientMessageId !== void 0;
89
+ }
46
90
  var listCursor = {
47
91
  key: (session) => [session.parentId ? 1 : 0, session.updatedAt ?? "", session.id],
48
92
  compare([childA, updatedA, idA], [childB, updatedB, idB]) {
@@ -61,8 +105,32 @@ var listCursor = {
61
105
  return key;
62
106
  }
63
107
  };
64
- function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates }) {
108
+ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions, modelCatalog }) {
65
109
  const connections = /* @__PURE__ */ new Set();
110
+ const catalogResult = () => {
111
+ const state = modelCatalog?.state();
112
+ const acpRows = modelCatalog?.acpRows() ?? [];
113
+ 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 }));
114
+ const acpProviders = Object.fromEntries([...new Set(acpRows.map((row) => row.provider))].map((id) => {
115
+ const acp = state?.acp?.[id];
116
+ return [`acp:${id}`, { status: acp?.status ?? "unprobed", ...acp?.fetchedAt ? { fetchedAt: acp.fetchedAt } : {}, ...acp?.error ? { error: acp.error } : {} }];
117
+ }));
118
+ return {
119
+ models: [...models, ...acpModels],
120
+ modes,
121
+ thinkingOptions,
122
+ defaultModel: `codex:${DEFAULT_MODEL}`,
123
+ ...state ? { fetchedAt: state.fetchedAt, providers: { ...Object.fromEntries(Object.entries(state.providers).map(([runtime2, provider]) => [runtime2, { status: provider.status, fetchedAt: provider.fetchedAt, ...provider.error ? { error: provider.error } : {} }])), ...acpProviders, ...modelCatalog?.acpLoadError() ? { acp: { status: "failed", error: modelCatalog.acpLoadError() } } : {} } } : {}
124
+ };
125
+ };
126
+ const unsubscribeCatalog = modelCatalog?.onUpdated((snapshot) => {
127
+ for (const connection of connections) if (connection.helloed) {
128
+ try {
129
+ connection.send({ jsonrpc: "2.0", method: "catalog.updated", params: { fetchedAt: snapshot.fetchedAt } });
130
+ } catch {
131
+ }
132
+ }
133
+ });
66
134
  const rootOf = /* @__PURE__ */ new Map();
67
135
  const attached = /* @__PURE__ */ new Map();
68
136
  const logs = /* @__PURE__ */ new Map();
@@ -74,12 +142,144 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
74
142
  let socketIdentity;
75
143
  const recovering = /* @__PURE__ */ new Map();
76
144
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
77
- const restored = store ? restore() : Promise.resolve();
78
- const deliver = (connection, envelope) => connection.send({ jsonrpc: "2.0", method: "event", params: envelope });
145
+ const clock = () => Date.now();
146
+ const schedules = home && store ? createScheduleStore(path.join(home, "schedules"), { now: clock }) : void 0;
147
+ const storeJob = async (id, projectRoot) => {
148
+ if (!schedules) return void 0;
149
+ try {
150
+ return await schedules.get(id, { projectRoot });
151
+ } catch (error) {
152
+ throw scheduleFailed(error);
153
+ }
154
+ };
155
+ const attachments = home && store && process.platform !== "win32" ? createAttachmentStore({
156
+ root: path.join(home, "state", "attachments"),
157
+ sessionProject: (sessionId) => runtime.snapshot(sessionId)?.projectRoot ?? records.get(sessionId)?.session?.projectRoot,
158
+ crashPoint,
159
+ log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
160
+ // A collected object's staged copy goes with it.
161
+ onDiscard: (attachmentId) => runtime.dropAttachment?.(attachmentId),
162
+ ...attachmentOptions
163
+ }) : void 0;
164
+ runtime.bindAttachments?.(attachments?.reader);
165
+ const holds = /* @__PURE__ */ new Map();
166
+ let holdRevision = 0;
167
+ function holdPrompts(root) {
168
+ holdRevision++;
169
+ let gate = holds.get(root);
170
+ if (!gate) {
171
+ let release;
172
+ const open = new Promise((resolve) => {
173
+ release = resolve;
174
+ });
175
+ gate = { count: 0, open, release };
176
+ holds.set(root, gate);
177
+ }
178
+ gate.count++;
179
+ const held = gate;
180
+ let released = false;
181
+ return () => {
182
+ if (released) return;
183
+ released = true;
184
+ if (--held.count === 0) {
185
+ if (holds.get(root) === held) holds.delete(root);
186
+ held.release();
187
+ }
188
+ };
189
+ }
190
+ const promptsInFlight = /* @__PURE__ */ new Map();
191
+ const rootIdOf = (sessionId) => rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
192
+ async function gated(sessionId, run) {
193
+ const root = rootIdOf(sessionId);
194
+ while (holds.has(root)) await holds.get(root).open;
195
+ refuseFenced(root);
196
+ promptsInFlight.set(root, (promptsInFlight.get(root) ?? 0) + 1);
197
+ try {
198
+ return await run();
199
+ } finally {
200
+ const left = (promptsInFlight.get(root) ?? 1) - 1;
201
+ if (left > 0) promptsInFlight.set(root, left);
202
+ else promptsInFlight.delete(root);
203
+ }
204
+ }
205
+ function fencedRoot(root) {
206
+ return conversation?.fenced(root);
207
+ }
208
+ function refuseFenced(root) {
209
+ const requestId = fencedRoot(root);
210
+ if (requestId !== void 0) throw new RpcError(ERROR.conflict, `A rewind of this session is not finished; send session.rewind again with requestId ${requestId}`, { reason: "session_busy" });
211
+ }
212
+ const journal = store ? createLifecycleJournal(path.join(store.root, "lifecycle")) : void 0;
213
+ const conversation = store && journal ? createConversation({
214
+ runtime,
215
+ store,
216
+ journal,
217
+ records,
218
+ cursors,
219
+ logs,
220
+ treeLogLimit: TREE_LOG_LIMIT,
221
+ summary: (id) => summary(id),
222
+ digest,
223
+ unsettled: (root) => fencedRoot(root) ? "a rewind of it is not finished; send that rewind again" : recovering.has(root) ? "it is being reopened after a restart" : openingSessions.has(root) ? "it is opening" : promptsInFlight.get(root) ? "a prompt is being delivered" : void 0,
224
+ holdPrompts,
225
+ broadcast: (root, envelope) => {
226
+ for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
227
+ },
228
+ get registry() {
229
+ return registry;
230
+ },
231
+ get worktrees() {
232
+ return worktrees;
233
+ },
234
+ attachments,
235
+ crashPoint,
236
+ log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
237
+ startedAt
238
+ }) : void 0;
239
+ let restored = Promise.resolve();
240
+ const openingSessions = /* @__PURE__ */ new Map();
241
+ const recoveryErrors = /* @__PURE__ */ new Map();
242
+ const markOpening = (sessionId) => openingSessions.set(sessionId, (openingSessions.get(sessionId) ?? 0) + 1);
243
+ const clearOpening = (sessionId) => {
244
+ const count = (openingSessions.get(sessionId) ?? 0) - 1;
245
+ if (count > 0) openingSessions.set(sessionId, count);
246
+ else openingSessions.delete(sessionId);
247
+ };
248
+ function keepRecoveryError(sessionId, message) {
249
+ if (scheduler?.holds(sessionId)) recoveryErrors.set(sessionId, message);
250
+ }
251
+ function dropRecoveryError(sessionId) {
252
+ if (!scheduler?.holds(sessionId)) recoveryErrors.delete(sessionId);
253
+ }
254
+ const scheduler = schedules ? createScheduler({
255
+ store: schedules,
256
+ runtime,
257
+ deliver: deliverJob,
258
+ ready: () => restored,
259
+ session: (sessionId) => openingSessions.has(sessionId) ? { opening: true } : recoveryErrors.has(sessionId) ? { error: { message: `The session this job continues could not be opened again: ${recoveryErrors.get(sessionId)}`, code: "session_open_failed" } } : void 0,
260
+ settled: (sessionId) => dropRecoveryError(sessionId),
261
+ stopping: () => closing,
262
+ now: clock,
263
+ ...scheduleDeliveryTimeoutMs === void 0 ? {} : { deliveryTimeoutMs: scheduleDeliveryTimeoutMs }
264
+ }) : void 0;
265
+ restored = store ? restore() : Promise.resolve();
266
+ const deliver = (connection, envelope) => {
267
+ const message = { jsonrpc: "2.0", method: "event", params: envelope };
268
+ const bytes = frameBytes(message);
269
+ if (bytes > 512 * 1024 && envelope.cursor !== void 0) message.params = {
270
+ ...envelope,
271
+ event: { type: "item", item: { kind: "notice", id: `oversized:${envelope.cursor}`, level: "warning", text: `History event ${envelope.cursor} is too large to display (${bytes} bytes).` } }
272
+ };
273
+ connection.send(message);
274
+ };
79
275
  const watchers = /* @__PURE__ */ new Map();
80
276
  function projectOf(root) {
81
277
  return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
82
278
  }
279
+ const sameProject = (a, b) => {
280
+ if (a === void 0 || b === void 0) return a === b;
281
+ return a === b || projectKey(a) === projectKey(b);
282
+ };
83
283
  function tellWatchers(root, envelope, turn = false) {
84
284
  if (!watchers.size) return;
85
285
  const { cursor: _cursor, ...announced } = envelope;
@@ -87,10 +287,30 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
87
287
  for (const [connection, { projectRoot, turns }] of watchers) {
88
288
  if (turn && !turns) continue;
89
289
  if (attached.get(root)?.has(connection)) continue;
90
- if (projectRoot !== void 0 && project !== projectRoot) continue;
290
+ if (projectRoot !== void 0 && !sameProject(project, projectRoot)) continue;
91
291
  deliver(connection, announced);
92
292
  }
93
293
  }
294
+ function tellAttention(root, attention) {
295
+ if (!watchers.size) return;
296
+ const project = projectOf(root);
297
+ const envelope = { sessionId: root, epoch: `attention-${startedAt}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "attention", ...attention ? { attention } : {} } };
298
+ for (const [connection, watch] of watchers) {
299
+ if (!watch.attention) continue;
300
+ if (watch.projectRoot !== void 0 && !sameProject(project, watch.projectRoot)) continue;
301
+ deliver(connection, envelope);
302
+ }
303
+ }
304
+ const pendingAcks = /* @__PURE__ */ new Map();
305
+ function attentionOf(projectRoot) {
306
+ const found = [];
307
+ for (const record of records.values()) {
308
+ if (record.id !== record.rootId || !record.attention || record.archived) continue;
309
+ if (projectRoot !== void 0 && !sameProject(projectOf(record.id), projectRoot)) continue;
310
+ found.push({ sessionId: record.id, attention: record.attention });
311
+ }
312
+ return found;
313
+ }
94
314
  function save(record, changes = {}) {
95
315
  Object.assign(record, changes, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
96
316
  records.set(record.id, record);
@@ -115,17 +335,25 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
115
335
  if (event.type === "session.opened") {
116
336
  record ??= { version: 1, id: sessionId, rootId: root, status: "initializing", createdAt: now, updatedAt: now };
117
337
  const usage = event.session.usage ?? record.session?.usage;
118
- save(record, { rootId: root, session: { ...event.session, ...usage ? { usage } : {} }, status: "idle", lastError: void 0, activeTurnId: void 0 });
338
+ const parked = recovering.has(root) ? record.session?.parked : event.session.parked;
339
+ save(record, { rootId: root, session: { ...event.session, ...usage ? { usage } : {}, ...parked ? { parked } : {} }, status: "idle", lastError: void 0, activeTurnId: void 0 });
119
340
  return false;
120
341
  }
121
342
  if (!record) return false;
122
343
  if (event.type === "session.updated") save(record, { session: { ...record.session, ...event.session, ...event.session.parked ? {} : { parked: void 0 } } });
123
- else if (event.type === "turn.started") save(record, { status: "running", activeTurnId: event.turnId, archived: void 0 });
124
- else if (event.type === "turn.ended") save(record, { status: "idle", activeTurnId: void 0, ...event.state === "failed" ? { lastError: { message: event.error?.message ?? "Turn failed" } } : {} });
344
+ else if (event.type === "turn.started") save(record, { status: "running", activeTurnId: event.turnId, archived: void 0, ...sessionId === root ? { attention: void 0 } : {} });
345
+ else if (event.type === "turn.ended") save(record, {
346
+ status: "idle",
347
+ activeTurnId: void 0,
348
+ // A root's turn that completed or failed asks every client for a look until one acknowledges it (Paseo's checkAndSetAttention).
349
+ ...sessionId === root ? { attention: turnAttention(event) } : {},
350
+ ...record.session ? { session: { ...record.session, parked: event.state === "failed" ? runtime.snapshot(sessionId)?.parked : void 0 } } : {},
351
+ ...event.state === "failed" ? { lastError: { message: event.error?.message ?? "Turn failed" } } : {}
352
+ });
125
353
  else if (event.type === "usage" && record.session) record.session = { ...record.session, usage: event.usage };
126
354
  else if (event.type === "session.failed") save(record, { status: "error", lastError: event.error });
127
355
  else if (event.type === "session.closed") save(record, { status: record.status === "error" ? "error" : "closed", activeTurnId: void 0 });
128
- else if (event.type === "item" && sessionId === root && !record.title && event.item.kind === "user_message" && !event.item.clientMessageId?.startsWith("alp-")) {
356
+ else if (event.type === "item" && sessionId === root && !record.title && event.item.kind === "user_message" && fromUser(event.item)) {
129
357
  const title = titleFromPrompt(event.item.text);
130
358
  if (title) {
131
359
  save(record, { title });
@@ -134,6 +362,11 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
134
362
  }
135
363
  return false;
136
364
  }
365
+ function turnAttention(event) {
366
+ if (event.state === "canceled") return void 0;
367
+ const message = event.error?.message?.trim();
368
+ return { reason: event.state === "completed" ? "finished" : "error", at: (/* @__PURE__ */ new Date()).toISOString(), turnId: event.turnId, ...event.state === "failed" && message ? { message: event.error.message } : {} };
369
+ }
137
370
  function announceTitle(root, title) {
138
371
  const session = runtime.snapshot(root);
139
372
  if (!session || rootOf.get(root) !== root) return;
@@ -160,7 +393,11 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
160
393
  log2.push(envelope);
161
394
  if (log2.length > TREE_LOG_LIMIT) log2.splice(0, log2.length - TREE_LOG_LIMIT);
162
395
  logs.set(root, log2);
396
+ const before = records.get(root)?.attention;
163
397
  named = track(sessionId, root, event);
398
+ const after = records.get(root)?.attention;
399
+ if (sessionId === root && (event.type === "turn.started" || event.type === "turn.ended")) pendingAcks.delete(root);
400
+ if (after !== before) tellAttention(root, after);
164
401
  }
165
402
  for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
166
403
  if (event.type === "question" || event.type === "question.resolved") tellWatchers(root, envelope);
@@ -174,19 +411,23 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
174
411
  });
175
412
  async function restore() {
176
413
  await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: true });
414
+ await journal?.prune(LIFECYCLE_RETENTION_MS, { temporaries: true }).catch((error) => recoveryLog.warn("could not prune the lifecycle journal", { code: "ALPD_LIFECYCLE_PRUNE_FAILED", error }));
177
415
  const loaded = await store.list();
178
416
  await reconcileReceipts(loaded);
179
417
  const now = Date.now();
180
418
  const ended = { code: "daemon_restarted", message: "alpd stopped while this session was working" };
181
419
  const epoch = `restart-${startedAt}`;
182
420
  const continuing = new Set(runtime.recoverable().map((entry) => entry.assignmentId));
421
+ const pending = await schedules?.all({ status: "pending" }) ?? [];
422
+ for (const job of pending) scheduler?.hold(job);
423
+ const scheduled = new Set(pending.map((job) => job.sessionId));
183
424
  const reopen = [];
184
425
  const byRoot = trees(loaded);
185
426
  const removed = await expire(byRoot, now);
186
427
  for (const [root, tree] of byRoot) {
187
428
  const head = tree.find((record) => record.id === root);
188
429
  if (removed.has(root)) continue;
189
- if (head && resumable(head) && (head.status === "running" || tree.some((record) => continuing.has(record.id)))) reopen.push({ record: head, working: head.status === "running" });
430
+ 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" });
190
431
  if (tree.some((record) => LIVE.includes(record.status))) seen(root, await store.timeline(root));
191
432
  for (const record of tree) {
192
433
  records.set(record.id, record);
@@ -194,7 +435,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
194
435
  const envelope = (event) => ({ sessionId: record.id, epoch, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event });
195
436
  if (record.activeTurnId) keep(root, envelope({ type: "turn.ended", turnId: record.activeTurnId, state: "failed", error: { message: ended.message, code: ended.code } }));
196
437
  if (record.id === root) {
197
- save(record, record.status === "idle" ? { status: "closed", activeTurnId: void 0 } : { status: "error", lastError: ended, activeTurnId: void 0 });
438
+ if (!(record.status === "idle" && record.session?.parked)) save(record, record.status === "idle" ? { status: "closed", activeTurnId: void 0 } : { status: "error", lastError: ended, activeTurnId: void 0 });
198
439
  } else if (continuing.has(record.id) && reopen.some((entry) => entry.record.id === root)) {
199
440
  save(record, { status: "closed", activeTurnId: void 0 });
200
441
  } else {
@@ -208,12 +449,22 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
208
449
  }
209
450
  }
210
451
  }
452
+ if (conversation) await conversation.recover().catch((error) => recoveryLog.error("could not recover lifecycle operations", { code: "ALPD_LIFECYCLE_RECOVERY_FAILED", error }));
211
453
  const reopened = new Set(reopen.map((entry) => entry.record.id));
212
454
  for (const rootId of new Set(runtime.recoverable().map((entry) => entry.rootId))) {
213
455
  if (!reopened.has(rootId)) await runtime.abandon(rootId, "its root session cannot be reopened").catch(() => {
214
456
  });
215
457
  }
216
- for (const { record, working } of reopen) recovering.set(record.id, recoverTree(record, working));
458
+ for (const { record, working } of reopen) {
459
+ if (fencedRoot(record.id)) {
460
+ recoveryLog.warn(`${record.id} is not reopened: a rewind of it is not finished`, { code: "ALPD_REWIND_FENCED", sessionId: record.id });
461
+ continue;
462
+ }
463
+ markOpening(record.id);
464
+ recovering.set(record.id, recoverTree(record, working, () => {
465
+ clearOpening(record.id);
466
+ }));
467
+ }
217
468
  }
218
469
  function trees(list) {
219
470
  const byRoot = /* @__PURE__ */ new Map();
@@ -229,36 +480,49 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
229
480
  }
230
481
  const continuing = new Set(runtime.recoverable().map((entry) => entry.rootId));
231
482
  for (const [root, tree] of byRoot) {
232
- if (!tree.some((record) => record.id === root)) continue;
233
- if (tree.some((record) => LIVE.includes(record.status))) continue;
234
- if (now - Math.max(...tree.map((record) => Date.parse(record.updatedAt) || now)) <= RETENTION_MS) continue;
235
- if (tree.some((record) => now - (receiptWritten.get(record.id) ?? 0) <= RECEIPT_RETENTION_MS)) continue;
236
- if (continuing.has(root) || rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) continue;
237
- const ids = tree.map((record) => record.id);
238
- if (now - await store.writtenAt(ids) <= RETENTION_MS) continue;
239
- if (rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) continue;
240
- for (const id of ids) records.delete(id);
241
- cursors.delete(root);
242
- await store.remove(root, ids);
243
- if (runLogDir) await unlink(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`)).catch(() => {
244
- });
245
- removed.add(root);
483
+ const remove = async () => {
484
+ if (!tree.some((record) => record.id === root)) return;
485
+ if (tree.some((record) => LIVE.includes(record.status))) return;
486
+ if (now - Math.max(...tree.map((record) => Date.parse(record.updatedAt) || now)) <= RETENTION_MS) return;
487
+ if (tree.some((record) => now - (receiptWritten.get(record.id) ?? 0) <= RECEIPT_RETENTION_MS)) return;
488
+ if (continuing.has(root) || rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
489
+ if (scheduler?.holds(root)) return;
490
+ const ids = tree.map((record) => record.id);
491
+ if (now - await store.writtenAt(ids) <= RETENTION_MS) return;
492
+ if (rootOf.has(root) || attached.get(root)?.size || recovering.has(root)) return;
493
+ if (await conversation?.retainsFork(root)) return;
494
+ for (const id of ids) records.delete(id);
495
+ cursors.delete(root);
496
+ await store.remove(root, ids);
497
+ await attachments?.releaseSessions(ids).catch((error) => recoveryLog.warn("could not release the attachments of removed sessions", { code: "ALPD_ATTACHMENT_RELEASE_FAILED", error }));
498
+ if (runLogDir) await unlink(path.join(runLogDir, `${root.replace(/[^\w.-]/g, "_")}.jsonl`)).catch(() => {
499
+ });
500
+ removed.add(root);
501
+ };
502
+ if (conversation) await conversation.lifecycle.serial(root, remove);
503
+ else await remove();
246
504
  }
247
505
  if (removed.size) recoveryLog.info(`retention removed ${removed.size} session tree${removed.size > 1 ? "s" : ""} unused for ${RETENTION_MS / 864e5} days`, { code: "ALP_RETENTION_REMOVED", trees: removed.size });
248
506
  return removed;
249
507
  }
508
+ let sweeping = false;
250
509
  async function sweep() {
251
- if (closing || !store) return;
510
+ if (closing || !store || sweeping) return;
511
+ sweeping = true;
252
512
  try {
253
513
  await restored;
254
514
  await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
515
+ await journal?.prune(LIFECYCLE_RETENTION_MS);
255
516
  await expire(trees(records.values()));
256
517
  } catch (error) {
257
518
  recoveryLog.warn("retention sweep failed", { code: "ALP_RETENTION_FAILED", error });
519
+ } finally {
520
+ sweeping = false;
258
521
  }
259
522
  }
260
523
  const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : void 0;
261
524
  sweeper?.unref();
525
+ scheduler?.start(scheduleTickMs);
262
526
  async function reconcileReceipts(loaded) {
263
527
  const rootOfRecord = new Map(loaded.map((record) => [record.id, record.rootId]));
264
528
  const timelines = /* @__PURE__ */ new Map();
@@ -278,20 +542,30 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
278
542
  function resumable(record) {
279
543
  return record.rootId === record.id && !!record.spec && !!record.session?.persistent && !!record.session.threadId;
280
544
  }
281
- async function recoverTree(record, working) {
545
+ async function recoverTree(record, working, opened) {
282
546
  const session = record.session;
547
+ let openedOnce = false;
548
+ const open = () => {
549
+ if (openedOnce) return;
550
+ openedOnce = true;
551
+ opened?.();
552
+ };
283
553
  try {
554
+ if (worktrees && record.spec?.cwd) await worktrees.assertAvailable(record.spec.cwd);
284
555
  const stored = await treeLog(record.id);
285
556
  seen(record.id, stored);
286
557
  logs.set(record.id, [...stored]);
287
558
  await runtime.open(record.id, {
288
559
  ...record.spec,
289
560
  persist: true,
290
- restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
561
+ restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...record.base ? { base: record.base } : {} }
291
562
  }, { history: "skip", delegation: record.delegation ?? true });
292
- const outcomes = await runtime.recover(record.id, { continueRoot: working });
563
+ open();
564
+ const outcomes = await runtime.recover(record.id, { continueRoot: working, parkedRoot: session.parked });
293
565
  recoveryLog.info(`recovered ${record.id}: ${outcomes.map((outcome) => `${outcome.agent} ${outcome.outcome}`).join(", ") || "root"}`, { event: "recovered", sessionId: record.id, rootId: record.rootId });
294
566
  } catch (error) {
567
+ open();
568
+ keepRecoveryError(record.id, error?.message ?? String(error));
295
569
  recoveryLog.error(`could not recover ${record.id}`, { code: "ALP_RECOVERY_FAILED", sessionId: record.id, rootId: record.rootId, error });
296
570
  await runtime.abandon(record.id, error?.message ?? String(error)).catch(() => {
297
571
  });
@@ -300,7 +574,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
300
574
  setImmediate(() => void reap(record.id));
301
575
  }
302
576
  }
303
- function deliverOnce(sessionId, clientMessageId, fingerprint, send) {
577
+ function deliverOnce(sessionId, clientMessageId, fingerprint, send, { requireReceipt = false, prepare, abandon } = {}) {
304
578
  const key = digest(["prompt", sessionId, clientMessageId]);
305
579
  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" });
306
580
  const answer = (receipt, extra = {}) => ({ outcome: receipt.outcome ?? "accepted", ...receipt.error ? { error: receipt.error } : {}, ...extra });
@@ -319,12 +593,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
319
593
  if (existing.state === "pending" || existing.outcome === "unknown") throw unknown();
320
594
  return answer(existing, { duplicate: true, durable: !unsaved.has(key) });
321
595
  }
596
+ if (requireReceipt) throw unknown();
322
597
  const receipt = (state, changes = {}) => ({ version: 1, sessionId, clientMessageId, fingerprint, state, ...changes, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
323
598
  live(sessionId);
599
+ await prepare?.(key);
324
600
  crashPoint("prompt.before-receipt");
325
601
  try {
326
602
  await store.putReceipt(key, receipt("pending"));
327
603
  } catch (error) {
604
+ await abandon?.(key).catch(() => {
605
+ });
328
606
  throw persistenceFailed(`message ${clientMessageId}; it was not sent`, error);
329
607
  }
330
608
  crashPoint("prompt.after-receipt");
@@ -339,6 +617,8 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
339
617
  } catch (error) {
340
618
  await store.removeReceipt(key).catch(() => {
341
619
  });
620
+ await abandon?.(key).catch(() => {
621
+ });
342
622
  throw error;
343
623
  } finally {
344
624
  stop();
@@ -360,7 +640,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
360
640
  };
361
641
  const previous = delivering.get(key) ?? Promise.resolve();
362
642
  const result = previous.catch(() => {
363
- }).then(attempt);
643
+ }).then(() => gated(sessionId, attempt));
364
644
  delivering.set(key, result);
365
645
  void result.finally(() => {
366
646
  if (delivering.get(key) === result) delivering.delete(key);
@@ -368,17 +648,29 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
368
648
  });
369
649
  return result;
370
650
  }
651
+ async function deliverJob(job, content, messageId, send = (id, input) => runtime.prompt(id, input)) {
652
+ const clientMessageId = messageId || scheduleMessageId(job);
653
+ return deliverOnce(job.sessionId, clientMessageId, digest({ delivery: "auto", content }), async () => {
654
+ live(job.sessionId);
655
+ await send(job.sessionId, { clientMessageId, delivery: "auto", content });
656
+ }, { requireReceipt: job.attempts > 1 });
657
+ }
371
658
  async function persisted(root) {
372
659
  if (!store) return {};
373
660
  return { durable: (await store.drain({ records: [root], timelines: [root] })).length === 0 };
374
661
  }
375
662
  function forget(root) {
376
663
  if (runtime.snapshot(root)) return;
377
- for (const [id, candidate] of rootOf) if (candidate === root) rootOf.delete(id);
664
+ for (const [id, candidate] of rootOf) if (candidate === root) {
665
+ rootOf.delete(id);
666
+ recoveryErrors.delete(id);
667
+ }
668
+ recoveryErrors.delete(root);
378
669
  logs.delete(root);
379
670
  }
380
671
  async function reap(root) {
381
672
  if (closing || attached.get(root)?.size || recovering.has(root)) return false;
673
+ if (scheduler?.holds(root)) return false;
382
674
  const session = runtime.snapshot(root);
383
675
  if (!session || session.busy) return false;
384
676
  await runtime.close(root).catch(() => {
@@ -402,7 +694,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
402
694
  const session = live2 ?? record?.session;
403
695
  if (!session) return void 0;
404
696
  const status = live2 ? live2.activeTurnId ? "running" : "idle" : record?.status === "error" ? "error" : "closed";
405
- return { ...session, ...live2 ? {} : { busy: false, activeTurnId: void 0 }, status, title: record?.title, ...record?.archived ? { archived: true } : {}, lastError: record?.lastError, createdAt: record?.createdAt, updatedAt: record?.updatedAt };
697
+ return { ...session, ...live2 ? {} : { busy: false, activeTurnId: void 0 }, 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) : {} };
406
698
  }
407
699
  function rootRecord(sessionId) {
408
700
  if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
@@ -464,29 +756,122 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
464
756
  if (!session?.persistent || !session.threadId || !record.spec) throw new RpcError(ERROR.failed, "This session cannot be resumed");
465
757
  const agent = spec.agent ?? spec.restore?.agent;
466
758
  if (agent !== void 0 && agent !== session.agent) throw new RpcError(ERROR.failed, "Cannot resume a session as a different ALP agent");
467
- const stored = await treeLog(record.id);
468
- seen(record.id, stored);
469
- logs.set(record.id, [...stored]);
470
- attach(connection, record.id);
759
+ markOpening(record.id);
760
+ recoveryErrors.delete(record.id);
761
+ let applied = false;
471
762
  try {
763
+ if (worktrees) await worktrees.assertAvailable(record.spec.cwd);
764
+ const stored = await treeLog(record.id);
765
+ seen(record.id, stored);
766
+ logs.set(record.id, [...stored]);
767
+ attach(connection, record.id);
472
768
  const opened = await runtime.open(record.id, {
473
769
  ...record.spec,
474
770
  ...spec.mode !== void 0 ? { mode: spec.mode } : {},
475
771
  ...spec.thinking !== void 0 ? { thinking: spec.thinking } : {},
476
772
  persist: true,
477
- restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow }
773
+ restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow, ...record.base ? { base: record.base } : {} }
478
774
  }, { history: stored.length ? "skip" : history, delegation: record.delegation ?? delegation });
775
+ applied = true;
776
+ await persistAcceptedSpec(record.id, opened, { mode: spec.mode !== void 0, thinking: spec.thinking !== void 0 });
479
777
  if (history === "replay") replayHistory(connection, record.id, stored);
480
778
  return opened;
481
779
  } catch (error) {
780
+ if (applied) throw error;
482
781
  detach(connection, record.id);
782
+ keepRecoveryError(record.id, error?.message ?? String(error));
483
783
  throw error;
784
+ } finally {
785
+ clearOpening(record.id);
786
+ }
787
+ }
788
+ async function persistAcceptedSpec(id, accepted, fields) {
789
+ const record = records.get(id);
790
+ if (!record?.spec || !fields.mode && !fields.thinking) return;
791
+ record.spec = {
792
+ ...record.spec,
793
+ ...fields.mode ? { mode: accepted.mode } : {},
794
+ ...fields.thinking ? { thinking: accepted.thinking } : {}
795
+ };
796
+ record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
797
+ try {
798
+ await store?.put(record);
799
+ } catch (error) {
800
+ throw persistenceFailed(`the configuration of ${id}; the runtime already applied it`, error);
484
801
  }
485
802
  }
486
- const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
803
+ const registry = home ? createRegistry(home) : void 0;
804
+ const worktrees = home && registry && process.platform !== "win32" ? createWorkspaceWorktrees(
805
+ home,
806
+ registry,
807
+ async (directory, run) => {
808
+ if (!runtime.withWorkspaceMutation) throw new RegistryError(1005, "Runtime cannot prove safe worktree removal", { reason: "guard_unavailable" });
809
+ try {
810
+ return await runtime.withWorkspaceMutation(directory, run);
811
+ } catch (error) {
812
+ if (error?.data?.reason) throw new RegistryError(1004, "Workspace is in use or has retained assignment results", error.data);
813
+ throw error;
814
+ }
815
+ },
816
+ async (directory) => {
817
+ if (!runtime.registerWorkspace) throw new RegistryError(1005, "Runtime cannot register safe workspace ownership", { reason: "guard_unavailable" });
818
+ await runtime.registerWorkspace(directory);
819
+ },
820
+ // Owner-audited adoption (t-c1ba); no RPC exposes it yet, so the default stays refusal.
821
+ runtime.adoptWorkspace ? async (directory, verify) => {
822
+ try {
823
+ await runtime.adoptWorkspace(directory, verify);
824
+ } catch (error) {
825
+ if (error?.data?.reason && !(error instanceof RegistryError)) throw new RegistryError(1004, "Workspace is in use, has retained assignment results or changed identity", error.data);
826
+ throw error;
827
+ }
828
+ } : void 0
829
+ ) : void 0;
830
+ const workspaceDescriptor = async (w) => worktrees ? worktrees.describe(w) : w;
831
+ const gitReader = registry ? createGitReader({ registry, log: (message, fields) => log.warn(message, { code: "ALPD_GIT_READ_FAILED", ...fields }) }) : void 0;
832
+ const gitFacts = createGitReader({ log: (message, fields) => log.warn(message, { code: "ALPD_GIT_READ_FAILED", ...fields }) });
833
+ const terminals = home && registry ? createTerminalService({
834
+ home,
835
+ resolveWorkspace: (workspaceId) => registry.resolve(workspaceId),
836
+ log: { warn: (message, fields) => log.warn(message, fields), info: (message, fields) => log.info(message, fields) },
837
+ ...terminalOptions
838
+ }) : void 0;
839
+ const terminalCall = (run) => {
840
+ if (!terminals) throw new RpcError(ERROR.unavailable, "This alpd has no home: it serves no terminals", { reason: "terminal_unsupported" });
841
+ return run(terminals);
842
+ };
843
+ const attachmentCall = async (run) => {
844
+ if (!attachments) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not store attachments (capability attachments is not listed)");
845
+ try {
846
+ return await run(attachments);
847
+ } catch (error) {
848
+ if (error instanceof RpcError) throw error;
849
+ log.warn("attachment call failed", { code: "ALPD_ATTACHMENT_FAILED", error });
850
+ throw new RpcError(ERROR.failed, "alpd could not store the attachment; the upload was aborted", { reason: "persistence_failed" });
851
+ }
852
+ };
853
+ const gitCall = (run) => {
854
+ if (!gitReader) throw new RpcError(ERROR.unavailable, "Registry needs ALP_HOME");
855
+ return run(gitReader);
856
+ };
857
+ const operations = createOperations({
858
+ home,
859
+ templates,
860
+ knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])),
861
+ onGateChange: (root) => runtime.syncGates?.(root),
862
+ // A provider file saved: reread the ACP rows; one the user just enabled is probed for its models (t-d0b0).
863
+ learnedModels: (id) => modelCatalog?.acpModels(id) ?? [],
864
+ onProviderSaved: (id, enabled) => {
865
+ if (!modelCatalog) return;
866
+ void (enabled ? modelCatalog.refreshAcp([id]) : modelCatalog.loadAcp()).catch(() => {
867
+ });
868
+ }
869
+ });
487
870
  const extensionOwners = /* @__PURE__ */ new Map();
871
+ const findPages = createFindPages();
488
872
  const handlers = {
489
873
  "extension.register": async (connection, params) => {
874
+ agentRefused(connection, "extension.register");
490
875
  const method = params?.method;
491
876
  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");
492
877
  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");
@@ -544,17 +929,46 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
544
929
  return { rootId: root, entries };
545
930
  },
546
931
  "question.list"(_connection, { projectRoot } = {}) {
547
- return { questions: runtime.questions().filter((question) => projectRoot === void 0 || projectOf(question.rootId) === projectRoot) };
932
+ return { questions: runtime.questions().filter((question) => projectRoot === void 0 || sameProject(projectOf(question.rootId), projectRoot)) };
548
933
  },
549
934
  /**
550
935
  * The questions waiting now; from then on this connection is told of `question` and
551
936
  * `question.resolved` in every tree, or those of `projectRoot`, attached or not. Calling it
552
937
  * again replaces the filter; it lasts as long as the connection (ALPD §15). With `turns`, also
553
- * of `turn.ended` of every root (docs/protocol/alp-json-rpc-v1.md §12.2).
938
+ * of `turn.ended` of every root; with `attention`, also of each root's attention, now and as it
939
+ * changes (docs/protocol/alp-json-rpc-v1.md §12.2).
940
+ */
941
+ "question.watch"(connection, { projectRoot, turns, attention } = {}) {
942
+ watchers.set(connection, { projectRoot, turns: turns === true, attention: attention === true });
943
+ return {
944
+ questions: runtime.questions().filter((question) => projectRoot === void 0 || sameProject(projectOf(question.rootId), projectRoot)),
945
+ ...attention === true ? { attention: attentionOf(projectRoot) } : {}
946
+ };
947
+ },
948
+ /**
949
+ * Acknowledges a root's attention for every client, as Paseo's clear_agent_attention; with `at`,
950
+ * only the attention set then, so a look at an older turn end never hides a newer one (§12.2).
554
951
  */
555
- "question.watch"(connection, { projectRoot, turns } = {}) {
556
- watchers.set(connection, { projectRoot, turns: turns === true });
557
- return { questions: runtime.questions().filter((question) => projectRoot === void 0 || projectOf(question.rootId) === projectRoot) };
952
+ async "session.attention.clear"(_connection, { sessionId, at }) {
953
+ if (typeof sessionId !== "string") throw new RpcError(-32602, "sessionId is required");
954
+ if (at !== void 0 && typeof at !== "string") throw new RpcError(-32602, "at must be a string");
955
+ const record = records.get(sessionId);
956
+ if (!record) throw new RpcError(ERROR.notFound, `No session ${sessionId}`);
957
+ const attention = record.attention;
958
+ if (!attention || at !== void 0 && attention.at !== at) return { cleared: false };
959
+ const ack = {};
960
+ pendingAcks.set(record.id, ack);
961
+ record.attention = void 0;
962
+ try {
963
+ await store?.put(record);
964
+ } catch (error) {
965
+ if (pendingAcks.get(record.id) === ack && !record.attention) record.attention = attention;
966
+ throw persistenceFailed(`the attention of ${record.id}`, error);
967
+ } finally {
968
+ if (pendingAcks.get(record.id) === ack) pendingAcks.delete(record.id);
969
+ }
970
+ tellAttention(record.id, record.attention);
971
+ return { cleared: true };
558
972
  },
559
973
  /**
560
974
  * The files of a directory whose path matches a query, read-only and confined to it: no link
@@ -576,12 +990,27 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
576
990
  * read-only, confined to it, no link followed, blocked paths always refused, .gitignore'd ones
577
991
  * unless includeIgnored (docs/protocol/alp-json-rpc-v1.md §12.4, ALPD §15).
578
992
  */
579
- async "workspace.files.list"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
580
- return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
993
+ async "workspace.files.list"(_connection, { projectRoot, path: relative, includeIgnored, cursor, internalLinks } = {}) {
994
+ return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true, cursor, internalLinks: internalLinks === true }));
581
995
  },
582
996
  async "workspace.files.read"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
583
997
  return filesCall(projectRoot, () => readWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
584
998
  },
999
+ /**
1000
+ * Every name under projectRoot in pages of a snapshot kept for this connection, and a file's
1001
+ * preview in chunks (docs/protocol/alp-json-rpc-v1.md §12.11): what the Paseo bridge's Files
1002
+ * panel and suggestions read, confined as workspace.files.read is. The gateway exposes neither.
1003
+ */
1004
+ async "workspace.files.find"(connection, { projectRoot, query, kinds, matchMode, limit, cursor } = {}) {
1005
+ return filesCall(projectRoot, () => findPages(connection, projectRoot, { query, kinds, matchMode, limit, cursor }));
1006
+ },
1007
+ async "workspace.files.preview"(_connection, { projectRoot, path: relative, includeIgnored, internalLinks, maxBytes, offset, revision } = {}) {
1008
+ return filesCall(projectRoot, () => previewWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true, internalLinks: internalLinks === true, maxBytes, offset, revision }));
1009
+ },
1010
+ /** The host's directories for the folder to add as a project (§12.11): the owner's own names, never remote. */
1011
+ async "host.directories.search"(_connection, { query, limit } = {}) {
1012
+ return searchHostDirectories(query, { limit });
1013
+ },
585
1014
  /** The project board: live claims, decisions and findings (ALPD §18). */
586
1015
  async "board.list"(_connection, { projectRoot } = {}) {
587
1016
  if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, "An absolute projectRoot is required");
@@ -615,29 +1044,130 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
615
1044
  throw new RpcError(ERROR.failed, error?.message ?? String(error));
616
1045
  }
617
1046
  },
618
- "question.answer"(_connection, { questionId, text, dismiss = false, reason }) {
1047
+ async "question.answer"(connection, { questionId, text, dismiss = false, reason }) {
1048
+ 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" });
619
1049
  if (typeof questionId !== "string") throw new RpcError(-32602, "questionId is required");
620
1050
  if (dismiss !== true && typeof text !== "string") throw new RpcError(-32602, "text or dismiss is required");
621
1051
  const matches = runtime.questions().filter((question) => question.id === questionId || question.id.startsWith(questionId));
622
1052
  if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
623
- runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason } : { text });
1053
+ const channel = connection.client?.startsWith("alp-paseo") ? "paseo" : "web";
1054
+ const decided = runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1055
+ if (decided) await decided.catch((error) => {
1056
+ if (error?.code === "GATE_BUSY" || error?.code === "GATE_DECIDED") throw new RpcError(ERROR.conflict, error.message, { reason: "task_state" });
1057
+ throw fromCore(error);
1058
+ });
624
1059
  return { questionId: matches[0].id };
625
1060
  },
626
1061
  "daemon.shutdown": () => {
627
1062
  setImmediate(() => onShutdown?.());
628
1063
  return {};
629
1064
  },
630
- "catalog.get": () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
631
- async "session.create"(connection, { sessionId, spec, history = "skip", delegation = true, resume: resuming = false }) {
1065
+ "registry.owner": (_c, params) => registryCall(async () => {
1066
+ const result = params.operation ? await registry.mutate(params.operation, params.args ?? {}, { requestId: params.requestId, ifRevision: params.ifRevision }) : void 0;
1067
+ const { receipts: _receipts, ...metadata } = await registry.snapshot();
1068
+ return { ...result ? { result } : {}, registry: metadata };
1069
+ }),
1070
+ "registry.worktree": (_c, p) => registryCall(async () => worktrees ? worktrees.grants(p) : { mappings: [], workspaces: [] }),
1071
+ "workspace.worktree.options": (_c, p) => registryCall(async () => {
1072
+ const w = (await registry.snapshot()).workspaces.find((w2) => w2.id === p.workspaceId);
1073
+ if (!w) throw new RegistryError(1001, "No workspace", { reason: "not_found" });
1074
+ const grants = worktrees ? await worktrees.grants(p) : { mappings: [], workspaces: [] };
1075
+ return { mappingIds: grants.mappings.filter((m) => m.source === (w.canonical ?? w.directory)).map((m) => m.id) };
1076
+ }),
1077
+ "workspace.worktree.create": (_c, p) => registryCall(async () => {
1078
+ if (!worktrees) throw new RegistryError(1005, "Worktrees are unavailable on this platform", { reason: "worktrees_unsupported" });
1079
+ const result = await worktrees.mutate("create", p, p);
1080
+ return { ...result, workspace: await workspaceDescriptor(result.workspace) };
1081
+ }),
1082
+ "workspace.worktree.remove": (_c, p) => registryCall(async () => {
1083
+ if (!worktrees) throw new RegistryError(1005, "Worktrees are unavailable on this platform", { reason: "worktrees_unsupported" });
1084
+ const result = await worktrees.mutate("remove", p, p);
1085
+ return { ...result, workspace: await workspaceDescriptor(result.workspace) };
1086
+ }),
1087
+ "workspace.git.status": (_c, p) => gitCall((reader) => reader.status(p.workspaceId)),
1088
+ "workspace.git.diff": (_c, p) => gitCall((reader) => reader.diff({ workspaceId: p.workspaceId, compare: p.compare, path: p.path, cursor: p.cursor })),
1089
+ "workspace.git.facts": (c, p) => agentRefused(c, "workspace.git.facts") ?? gitFacts.facts(p.directory),
1090
+ "project.list": (_c, p) => registryList("projects", p),
1091
+ "workspace.list": (_c, p) => registryList("workspaces", p),
1092
+ "workspace.get": (_c, p) => registryCall(async () => {
1093
+ await registry.resolve(p.workspaceId, void 0, true);
1094
+ const r = await registry.snapshot();
1095
+ return { workspace: { ...await workspaceDescriptor(r.workspaces.find((w) => w.id === p.workspaceId)), revision: r.revision }, revision: r.revision };
1096
+ }),
1097
+ "project.register": (_c, p) => registryMutation("project.register", p),
1098
+ "project.remove": (_c, p) => registryMutation("project.remove", p),
1099
+ "workspace.update": (_c, p) => registryMutation("workspace.update", p),
1100
+ "catalog.get": () => catalogResult(),
1101
+ "catalog.refresh": async () => {
1102
+ if (!modelCatalog) throw new RpcError(ERROR.unavailable, "The live model catalog is not available");
1103
+ await Promise.all([modelCatalog.refresh(), modelCatalog.refreshAcp().catch(() => {
1104
+ })]);
1105
+ return catalogResult();
1106
+ },
1107
+ // attachment.* (§12.6): each call acts for its principal context; without the store (no home or
1108
+ // store, or Windows) alpd does not serve them, as for any method it does not know.
1109
+ // terminal.* (§12.10): each call acts for its principal context; input, resize and the stream
1110
+ // belong to the connection that attached the terminal.
1111
+ "terminal.create": (c, p) => agentRefused(c, "terminal.create") ?? terminalCall((service) => service.create(principalOf(p), p)),
1112
+ "terminal.watch": (c, p) => terminalCall((service) => service.watch(principalOf(p), c, p)),
1113
+ "terminal.unwatch": (c) => terminalCall((service) => service.unwatch(c)),
1114
+ "terminal.capture": (_c, p) => terminalCall((service) => service.capture(principalOf(p), p)),
1115
+ "terminal.list": (_c, p) => terminalCall((service) => service.list(principalOf(p), p)),
1116
+ "terminal.attach": (c, p) => agentRefused(c, "terminal.attach") ?? terminalCall((service) => service.attach(principalOf(p), c, p)),
1117
+ "terminal.input": (c, p) => agentRefused(c, "terminal.input") ?? terminalCall((service) => service.input(principalOf(p), c, p)),
1118
+ "terminal.resize": (c, p) => terminalCall((service) => service.resize(principalOf(p), c, p)),
1119
+ "terminal.close": (_c, p) => terminalCall((service) => service.close(principalOf(p), p)),
1120
+ "terminal.revoke": (_c, p) => terminalCall((service) => service.revoke(p.principalId)),
1121
+ "attachment.begin": (_c, p) => attachmentCall((store2) => store2.begin(principalOf(p), p)),
1122
+ "attachment.chunk": (_c, p) => attachmentCall((store2) => store2.chunk(principalOf(p), p)),
1123
+ "attachment.commit": (_c, p) => attachmentCall((store2) => store2.commit(principalOf(p), p)),
1124
+ "attachment.abort": (_c, p) => attachmentCall((store2) => store2.abort(principalOf(p), p)),
1125
+ "attachment.get": (_c, p) => attachmentCall((store2) => store2.get(principalOf(p), p)),
1126
+ "attachment.delete": (_c, p) => attachmentCall((store2) => store2.remove(principalOf(p), p)),
1127
+ async "session.create"(connection, { sessionId, workspaceId, spec, history = "skip", delegation = true, resume: resuming = false }) {
1128
+ if (workspaceId !== void 0) {
1129
+ if (!registry || typeof workspaceId !== "string") throw new RpcError(-32602, "Invalid workspaceId");
1130
+ try {
1131
+ spec = { ...spec, cwd: await registry.resolve(workspaceId, spec?.cwd) };
1132
+ } catch (e) {
1133
+ if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data);
1134
+ throw e;
1135
+ }
1136
+ const placements = (await registryCall(() => registry.snapshot())).sessions;
1137
+ const prior = Object.hasOwn(placements, sessionId) ? placements[sessionId] : void 0;
1138
+ if (prior && prior !== workspaceId) throw new RpcError(ERROR.conflict, "Session belongs to another workspace", { reason: "workspace_mismatch" });
1139
+ }
632
1140
  if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
1141
+ if (connection.agent && spec.restore !== void 0) {
1142
+ const { restore: _restore2, ...owned } = spec;
1143
+ spec = owned;
1144
+ }
1145
+ if (worktrees) await registryCall(() => worktrees.assertAvailable(spec.cwd));
633
1146
  if (sessionId !== void 0 && (typeof sessionId !== "string" || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, "Invalid session id");
634
1147
  if (history !== "replay" && history !== "skip") throw new RpcError(-32602, "history must be replay or skip");
635
1148
  const id = sessionId ?? `ses_${randomBytes(8).toString("hex")}`;
636
1149
  await recovering.get(id);
1150
+ while (holds.has(id)) await holds.get(id).open;
1151
+ refuseFenced(id);
1152
+ let reservedWorkspaceId;
1153
+ const reserve = async () => {
1154
+ if (!registry) return;
1155
+ const directory = runtime.snapshot(id)?.projectRoot ?? records.get(id)?.session?.projectRoot ?? records.get(id)?.spec?.cwd ?? spec.cwd;
1156
+ if (workspaceId) await registryCall(() => registry.resolve(workspaceId, directory));
1157
+ if (Object.hasOwn((await registry.snapshot()).sessions, id)) return;
1158
+ if (workspaceId) await registryCall(() => registry.mutate("placement.assign", { sessionId: id, workspaceId }, { requestId: `reserve:${randomBytes(12).toString("hex")}` }));
1159
+ else await registryCall(() => registry.mutate("placement.prepare", { sessions: [{ id, projectRoot: directory }] }, { requestId: `prepare:${randomBytes(12).toString("hex")}` }));
1160
+ reservedWorkspaceId = (await registry.snapshot()).sessions[id];
1161
+ };
1162
+ const rollback = async () => {
1163
+ if (!registry || !reservedWorkspaceId) return;
1164
+ await registryCall(() => registry.mutate("placement.remove", { sessionId: id, workspaceId: reservedWorkspaceId }, { requestId: `rollback:${randomBytes(12).toString("hex")}` }));
1165
+ };
637
1166
  const existing = runtime.snapshot(id);
638
1167
  if (existing) {
639
1168
  const agent = spec.agent ?? spec.restore?.agent;
640
1169
  if (existing.parentId || agent !== void 0 && agent !== existing.agent) throw new RpcError(ERROR.failed, "Session is already open");
1170
+ await reserve();
641
1171
  attach(connection, id);
642
1172
  announce(connection, id, history);
643
1173
  return { session: existing, attached: true };
@@ -645,8 +1175,14 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
645
1175
  const record = records.get(id);
646
1176
  if (!record && resuming) throw new RpcError(ERROR.notFound, `ALP session ${id} no longer exists in alpd`);
647
1177
  if (record) {
648
- const session = await resume(connection, record, spec, history, delegation);
649
- return { session, attached: false, resumed: true, ...await persisted(id) };
1178
+ await reserve();
1179
+ try {
1180
+ const session = await resume(connection, record, spec, history, delegation);
1181
+ return { session, attached: false, resumed: true, ...await persisted(id) };
1182
+ } catch (error) {
1183
+ if (!runtime.snapshot(id)) await rollback();
1184
+ throw error;
1185
+ }
650
1186
  }
651
1187
  const { restore: _restore, ...kept } = spec;
652
1188
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -658,14 +1194,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
658
1194
  if (records.get(id) === created) records.delete(id);
659
1195
  throw persistenceFailed(`session ${id}; it was not started`, error);
660
1196
  }
661
- attach(connection, id);
662
1197
  try {
1198
+ await reserve();
1199
+ attach(connection, id);
663
1200
  const session = await runtime.open(id, spec, { history, delegation });
664
1201
  return { session, attached: false, ...await persisted(id) };
665
1202
  } catch (error) {
666
1203
  detach(connection, id);
667
1204
  records.delete(id);
668
1205
  await store?.remove(id, [id]);
1206
+ await rollback();
669
1207
  throw error;
670
1208
  }
671
1209
  },
@@ -679,44 +1217,79 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
679
1217
  * events are replayed (ALPD §66); a cursor this tree never reached answers `reset: true`
680
1218
  * with the whole timeline. The replay and the live events that follow are in cursor order.
681
1219
  */
682
- async "session.attach"(connection, { sessionId, replay = true, after }) {
683
- if (after !== void 0 && (!Number.isSafeInteger(after) || after < 0)) throw new RpcError(-32602, "after must be a cursor");
684
- const found = known(sessionId);
1220
+ async "session.history"(_connection, { sessionId, before, limit, maxBytes }) {
1221
+ known(sessionId);
1222
+ if (!store) throw new RpcError(1005, "Durable history unavailable");
685
1223
  const root = rootOf.get(sessionId) ?? records.get(sessionId)?.rootId ?? sessionId;
686
- let stored = [];
687
- if (replay || store && !cursors.has(root)) {
688
- const memory = logs.get(root);
689
- const covered = !!memory?.length && (memory[0].cursor ?? 1) <= (after ?? 0) + 1;
690
- if (!covered) stored = store ? await store.timeline(root) : memory ?? [];
1224
+ try {
1225
+ return await store.history(root, sessionId, { before, limit, maxBytes });
1226
+ } catch (error) {
1227
+ if (error instanceof HistoryError) throw new RpcError(error.reason === "stale_cursor" ? 1004 : -32602, error.message, { reason: error.reason });
1228
+ throw error;
691
1229
  }
692
- const live2 = logs.get(root) ?? [];
693
- const tip = Math.max(cursors.get(root) ?? 0, stored.at(-1)?.cursor ?? 0, live2.at(-1)?.cursor ?? 0);
694
- const first = replay ? [...stored, ...live2].find((envelope) => envelope.cursor !== void 0)?.cursor : void 0;
695
- const reset = after !== void 0 && (after > tip || replay && after < tip && (first === void 0 || first > after + 1));
696
- const from = reset ? 0 : after ?? 0;
697
- attach(connection, root);
698
- if (replay) {
699
- let last = from;
700
- for (const envelope of stored) if ((envelope.cursor ?? 0) > last) {
701
- if (current(envelope)) deliver(connection, envelope);
702
- last = envelope.cursor ?? last;
1230
+ },
1231
+ async "session.attach"(connection, { sessionId, replay = true, after, generation }) {
1232
+ if (after !== void 0 && (!Number.isSafeInteger(after) || after < 0)) throw new RpcError(-32602, "after must be a cursor");
1233
+ known(sessionId);
1234
+ const root = rootIdOf(sessionId);
1235
+ for (; ; ) {
1236
+ while (holds.has(root)) await holds.get(root).open;
1237
+ refuseFenced(root);
1238
+ const revision = holdRevision;
1239
+ const found = known(sessionId);
1240
+ let stored = [];
1241
+ if (replay || store && !cursors.has(root)) {
1242
+ const memory = logs.get(root);
1243
+ const covered = !!memory?.length && (memory[0].cursor ?? 1) <= (after ?? 0) + 1;
1244
+ if (!covered) stored = store ? await store.timeline(root) : memory ?? [];
703
1245
  }
704
- for (const envelope of live2) if ((envelope.cursor ?? 0) > last) {
705
- if (current(envelope)) deliver(connection, envelope);
706
- last = envelope.cursor ?? last;
1246
+ if (holds.has(root) || revision !== holdRevision) continue;
1247
+ if (generation !== void 0) {
1248
+ const checkpoint = await store?.history(root, sessionId, { limit: 1 });
1249
+ if (holds.has(root) || revision !== holdRevision) continue;
1250
+ if (checkpoint?.generation !== generation) throw new RpcError(1004, "History generation changed", { reason: "stale_cursor" });
707
1251
  }
1252
+ const live2 = logs.get(root) ?? [];
1253
+ const tip = Math.max(cursors.get(root) ?? 0, stored.at(-1)?.cursor ?? 0, live2.at(-1)?.cursor ?? 0);
1254
+ if (generation !== void 0 && replay) {
1255
+ const covered = Math.max(after ?? 0, stored.at(-1)?.cursor ?? 0);
1256
+ const next = live2.find((envelope) => (envelope.cursor ?? 0) > covered)?.cursor;
1257
+ if (next !== void 0 && next > covered + 1 || next === void 0 && tip > covered) {
1258
+ throw new RpcError(1005, "History advanced beyond replay coverage; retry attach", { reason: "history_gap" });
1259
+ }
1260
+ }
1261
+ const first = replay ? [...stored, ...live2].find((envelope) => envelope.cursor !== void 0)?.cursor : void 0;
1262
+ const reset = after !== void 0 && (after > tip || replay && after < tip && (first === void 0 || first > after + 1) || !!conversation?.discarded(records.get(root), after));
1263
+ const from = reset ? 0 : after ?? 0;
1264
+ attach(connection, root);
1265
+ if (replay) {
1266
+ let last = from;
1267
+ for (const envelope of stored) if ((envelope.cursor ?? 0) > last) {
1268
+ if (current(envelope)) deliver(connection, envelope);
1269
+ last = envelope.cursor ?? last;
1270
+ }
1271
+ for (const envelope of live2) if ((envelope.cursor ?? 0) > last) {
1272
+ if (current(envelope)) deliver(connection, envelope);
1273
+ last = envelope.cursor ?? last;
1274
+ }
1275
+ }
1276
+ announceQuestions(connection, root);
1277
+ const gateProject = runtime.snapshot(root)?.projectRoot;
1278
+ if (gateProject) void runtime.syncGates?.(gateProject)?.catch(() => {
1279
+ });
1280
+ return { session: root === found.id ? found : summary(root), cursor: tip, ...reset ? { reset: true } : {} };
708
1281
  }
709
- announceQuestions(connection, root);
710
- return { session: root === found.id ? found : summary(root), cursor: tip, ...reset ? { reset: true } : {} };
711
1282
  },
712
1283
  async "session.release"(connection, { sessionId }) {
713
1284
  const root = rootOf.get(sessionId) ?? sessionId;
714
1285
  detach(connection, root);
715
1286
  return { closed: await reap(root) };
716
1287
  },
717
- async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content }) {
1288
+ async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content, ...context }) {
718
1289
  if (typeof clientMessageId !== "string" || !Array.isArray(content)) throw new RpcError(-32602, "clientMessageId and content are required");
719
1290
  if (delivery !== "auto" && delivery !== "steer") throw new RpcError(-32602, "delivery must be auto or steer");
1291
+ const refused = runtime.refusesPrompt?.(sessionId, content);
1292
+ if (refused) throw new RpcError(-32602, refused, { reason: "native_command_unsupported" });
720
1293
  const images = content.filter((part) => part?.type === "image");
721
1294
  if (images.length > PROMPT_IMAGES.maxCount) throw new RpcError(-32602, `A prompt takes at most ${PROMPT_IMAGES.maxCount} images`);
722
1295
  let total = 0;
@@ -726,22 +1299,108 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
726
1299
  if (bytes > PROMPT_IMAGES.maxBytes) throw new RpcError(-32602, `An image in a prompt is at most ${PROMPT_IMAGES.maxBytes} bytes`);
727
1300
  if (total > PROMPT_IMAGES.maxTotalBytes) throw new RpcError(-32602, `The images of a prompt are at most ${PROMPT_IMAGES.maxTotalBytes} bytes together`);
728
1301
  }
1302
+ const attached2 = content.filter((part) => part?.type === "attachment");
1303
+ let resolved = [];
1304
+ if (attached2.length) {
1305
+ if (!attachments || !store) throw new RpcError(ERROR.unavailable, "This alpd does not store attachments", { reason: "attachment_unsupported" });
1306
+ resolved = await attachments.resolve(principalOf(context), sessionId, attached2.map((part) => part.attachmentId));
1307
+ }
1308
+ let index = 0;
1309
+ const delivered = attached2.length ? content.map((part) => part?.type === "attachment" ? resolved[index++] : part) : content;
1310
+ const fingerprinted = attached2.length ? content.map((part) => part?.type === "attachment" ? { type: "attachment", attachmentId: part.attachmentId, sha256: resolved.find((entry) => entry.attachmentId === part.attachmentId).sha256 } : part) : content;
729
1311
  const send = async () => {
730
1312
  live(sessionId);
731
- await runtime.prompt(sessionId, { clientMessageId, delivery, content });
1313
+ await runtime.prompt(sessionId, { clientMessageId, delivery, content: delivered });
732
1314
  };
733
1315
  if (!store) {
734
- await send();
1316
+ await gated(sessionId, send);
735
1317
  return {};
736
1318
  }
737
- return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
1319
+ if (!attached2.length) return deliverOnce(sessionId, clientMessageId, digest({ delivery, content }), send);
1320
+ return deliverOnce(sessionId, clientMessageId, digest({ delivery, content: fingerprinted }), send, {
1321
+ prepare: async (key) => {
1322
+ if (!runtime.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" });
1323
+ await attachments.pin(`prompt:${key}`, sessionId, resolved.map((entry) => entry.attachmentId));
1324
+ },
1325
+ abandon: (key) => attachments.release(`prompt:${key}`)
1326
+ });
1327
+ },
1328
+ /** A new root from a root's conversation cut at a turn, or from a branch a rewind set aside (§12.7). */
1329
+ async "session.fork"(connection, params) {
1330
+ agentRefused(connection, "session.fork");
1331
+ if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not fork conversations (capability session.fork is not listed)");
1332
+ return conversation.fork({ ...params, principal: principalOf(params) });
1333
+ },
1334
+ /** The root's conversation from before a turn on, same id; the later turns stay a recoverable branch, files untouched (§12.7). */
1335
+ async "session.rewind"(connection, params) {
1336
+ agentRefused(connection, "session.rewind");
1337
+ if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not rewind conversations (capability session.rewind is not listed)");
1338
+ return conversation.rewind(params);
738
1339
  },
739
- async "session.interrupt"(_connection, { sessionId }) {
1340
+ /** Restarts a live root's native process on its own conversation at the idle barrier (§12.8). */
1341
+ async "session.reload"(connection, params) {
1342
+ agentRefused(connection, "session.reload");
1343
+ if (!conversation?.reloads) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not reload sessions (capability session.reload is not listed)");
1344
+ return conversation.reload(params);
1345
+ },
1346
+ /** Compacts a live root's context now or at its next turn boundary (t-0e56). */
1347
+ async "session.compact"(connection, { sessionId }) {
1348
+ agentRefused(connection, "session.compact");
1349
+ if (typeof sessionId !== "string" || !sessionId) throw new RpcError(-32602, "sessionId is required");
1350
+ if (!runtime.compact) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not compact sessions");
1351
+ try {
1352
+ return runtime.compact(sessionId);
1353
+ } catch (error) {
1354
+ const reason = error?.data?.reason;
1355
+ throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error), typeof reason === "string" ? { reason } : void 0);
1356
+ }
1357
+ },
1358
+ /** The slash commands and skills a live session's composer offers after "/" (t-f628). */
1359
+ async "session.commands"(_connection, { sessionId }) {
1360
+ if (typeof sessionId !== "string" || !sessionId) throw new RpcError(-32602, "sessionId is required");
1361
+ if (!runtime.commands) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd lists no commands (capability session.commands is not listed)");
1362
+ if (!runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: "not_found" });
1363
+ try {
1364
+ const listed = await runtime.commands(sessionId);
1365
+ const seen2 = /* @__PURE__ */ new Set();
1366
+ const commands = listed.filter((command) => /^[^\s\u0000-\u001f\u007f]{1,256}$/.test(command.name) && !seen2.has(command.name) && seen2.add(command.name)).slice(0, 1e3).map((command) => ({ name: command.name, description: command.description.slice(0, 4096), ...command.argumentHint ? { argumentHint: command.argumentHint.slice(0, 256) } : {}, kind: command.kind }));
1367
+ return { commands };
1368
+ } catch (error) {
1369
+ throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error));
1370
+ }
1371
+ },
1372
+ /** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
1373
+ async "session.resumeCommand"(_connection, { sessionId }) {
1374
+ if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd has no resume command (capability session.resumeCommand is not listed)");
1375
+ return conversation.resumeCommand(sessionId);
1376
+ },
1377
+ async "session.interrupt"(_connection, { sessionId, turnId }) {
1378
+ if (turnId !== void 0) {
1379
+ if (typeof turnId !== "string" || !turnId) throw new RpcError(-32602, "turnId must be a nonempty string");
1380
+ if (!runtime.interruptTurn) throw new RpcError(ERROR.unavailable, "This runtime cannot interrupt a specific turn");
1381
+ return { interrupted: await runtime.interruptTurn(sessionId, turnId) };
1382
+ }
740
1383
  await runtime.interrupt(sessionId);
741
1384
  return {};
742
1385
  },
743
- async "session.configure"(_connection, { sessionId, mode }) {
744
- return { session: await runtime.configure(sessionId, { mode }) };
1386
+ /**
1387
+ * A session's permissions mode while idle; with model, thinking or team, a live root's configuration
1388
+ * at the idle barrier through a restart on the same conversation (§12.9, capability session.configure.live).
1389
+ */
1390
+ async "session.configure"(_connection, params) {
1391
+ const { sessionId, mode } = params;
1392
+ if (params.model !== void 0 || params.thinking !== void 0 || params.team !== void 0) {
1393
+ 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" });
1394
+ return conversation.configure(params);
1395
+ }
1396
+ return { session: await runtime.configure(sessionId, { mode }, {
1397
+ onApplied: (accepted) => persistAcceptedSpec(sessionId, accepted, { mode: true })
1398
+ }) };
1399
+ },
1400
+ /** What a change of model, thinking, team or mode would run a live root with (§12.9). */
1401
+ async "session.configure.preview"(_connection, params) {
1402
+ if (!conversation?.configures) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not preview configurations (capability session.configure.live is not listed)");
1403
+ return { preview: await conversation.configurePreview(params) };
745
1404
  },
746
1405
  async "session.close"(_connection, { sessionId }) {
747
1406
  await runtime.close(sessionId);
@@ -766,14 +1425,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
766
1425
  async "session.archive"(_connection, { sessionId, archived = true }) {
767
1426
  const record = rootRecord(sessionId);
768
1427
  if (archived && runtime.snapshot(record.id)) await runtime.close(record.id);
769
- const before = record.archived;
770
- Object.assign(record, { archived: archived === true ? true : void 0 });
1428
+ const before = { archived: record.archived, attention: record.attention };
1429
+ Object.assign(record, { archived: archived === true ? true : void 0 }, archived === true ? { attention: void 0 } : {});
1430
+ if (archived === true) pendingAcks.delete(record.id);
771
1431
  try {
772
1432
  await store?.put(record);
773
1433
  } catch (error) {
774
- record.archived = before;
1434
+ Object.assign(record, before);
775
1435
  throw persistenceFailed(`the archive state of ${record.id}`, error);
776
1436
  }
1437
+ if (before.attention && !record.attention) tellAttention(record.id, void 0);
777
1438
  return { session: summary(record.id) };
778
1439
  },
779
1440
  "session.get"(_connection, { sessionId }) {
@@ -786,25 +1447,144 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
786
1447
  * a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
787
1448
  */
788
1449
  "session.list"(_connection, { projectRoot, projectRoots, rootsOnly = false, includeClosed = false, includeArchived = false, limit, cursor, query } = {}) {
789
- const projects = Array.isArray(projectRoots) ? new Set(projectRoots) : void 0;
1450
+ const cache = /* @__PURE__ */ new Map();
1451
+ const keyOf = (root) => {
1452
+ let key = cache.get(root);
1453
+ if (key === void 0) {
1454
+ key = projectKey(root);
1455
+ cache.set(root, key);
1456
+ }
1457
+ return key;
1458
+ };
1459
+ const wantedKey = projectRoot === void 0 ? void 0 : keyOf(projectRoot);
1460
+ const allowedKeys = Array.isArray(projectRoots) ? new Set(projectRoots.map(keyOf)) : void 0;
790
1461
  const after = cursor === void 0 ? void 0 : listCursor.decode(cursor);
791
1462
  const words = typeof query === "string" ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
792
- const ids = /* @__PURE__ */ new Set([...runtime.list().map((session) => session.id), ...records.keys()]);
793
- const sessions = [...ids].map(summary).filter((session) => !!session).filter((session) => includeClosed || session.status === "idle" || session.status === "running").filter((session) => includeArchived || !session.archived).filter((session) => !rootsOnly || !session.parentId).filter((session) => projectRoot === void 0 || session.projectRoot === projectRoot).filter((session) => !projects || projects.has(session.projectRoot)).filter((session) => !words.length || words.every((word) => `${session.title ?? ""}
1463
+ const live2 = runtime.list();
1464
+ const liveChildren = rootsOnly ? new Set(live2.filter((session) => !!session.parentId).map((session) => session.id)) : void 0;
1465
+ const ids = /* @__PURE__ */ new Set();
1466
+ for (const session of live2) {
1467
+ if (!rootsOnly || !session.parentId) ids.add(session.id);
1468
+ }
1469
+ for (const [id, record] of records) {
1470
+ if (!rootsOnly) {
1471
+ ids.add(id);
1472
+ } else if (record.id === record.rootId && !record.session?.parentId && !liveChildren.has(id)) {
1473
+ ids.add(id);
1474
+ }
1475
+ }
1476
+ const sessions = [...ids].map(summary).filter((session) => !!session).filter((session) => includeClosed || session.status === "idle" || session.status === "running").filter((session) => includeArchived || !session.archived).filter((session) => !rootsOnly || !session.parentId).filter((session) => wantedKey === void 0 || keyOf(session.projectRoot) === wantedKey).filter((session) => !allowedKeys || allowedKeys.has(keyOf(session.projectRoot))).filter((session) => !words.length || words.every((word) => `${session.title ?? ""}
794
1477
  ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(listCursor.key(a), listCursor.key(b))).filter((session) => !after || listCursor.compare(listCursor.key(session), after) > 0);
795
1478
  if (limit === void 0 || sessions.length <= limit) return { sessions };
796
1479
  const page = sessions.slice(0, limit);
797
1480
  return { sessions: page, nextCursor: listCursor.encode(listCursor.key(page.at(-1))) };
1481
+ },
1482
+ /**
1483
+ * A scheduled continuation of a root session: alpd opens the turn itself
1484
+ * when the time comes, without a user message. The target is a live root session of
1485
+ * the project; a session that is closed when the job is due fails the job, and the
1486
+ * reason is kept.
1487
+ */
1488
+ async "schedule.create"(_connection, { projectRoot, sessionId, dueAt, prompt, keepsSession } = {}) {
1489
+ if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
1490
+ if (typeof projectRoot !== "string" || typeof sessionId !== "string" || typeof dueAt !== "string" || typeof prompt !== "string") {
1491
+ throw new RpcError(RPC_ERROR.invalidParams, "projectRoot, sessionId, dueAt and prompt are required");
1492
+ }
1493
+ if (keepsSession !== void 0 && typeof keepsSession !== "boolean") throw new RpcError(RPC_ERROR.invalidParams, "keepsSession must be true or false");
1494
+ if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute path");
1495
+ const snapshot = runtime.snapshot(sessionId);
1496
+ if (!snapshot) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not open`);
1497
+ if (snapshot.parentId) throw new RpcError(RPC_ERROR.invalidParams, "A scheduled job continues a root session");
1498
+ if (projectKey(snapshot.projectRoot) !== projectKey(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, "That session does not belong to that project");
1499
+ 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 });
1500
+ scheduler?.holdSession(sessionId);
1501
+ try {
1502
+ const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt, keepsSession });
1503
+ scheduler?.hold(job);
1504
+ return { job };
1505
+ } catch (error) {
1506
+ throw scheduleFailed(error);
1507
+ } finally {
1508
+ scheduler?.releaseSession(sessionId);
1509
+ }
1510
+ },
1511
+ /** The jobs of this project, oldest first by the time they are due. */
1512
+ async "schedule.list"(_connection, { projectRoot, status } = {}) {
1513
+ if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
1514
+ requestedProject(projectRoot);
1515
+ try {
1516
+ return { jobs: await schedules.list({ projectRoot, status }) };
1517
+ } catch (error) {
1518
+ throw scheduleFailed(error);
1519
+ }
1520
+ },
1521
+ /** One job, with what became of it. */
1522
+ async "schedule.get"(_connection, { id, projectRoot } = {}) {
1523
+ if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
1524
+ if (typeof id !== "string") throw new RpcError(RPC_ERROR.invalidParams, "id is required");
1525
+ requestedProject(projectRoot);
1526
+ const job = await storeJob(id, projectRoot);
1527
+ if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
1528
+ return { job };
1529
+ },
1530
+ /** A job that will not run: cancelled before its time. */
1531
+ async "schedule.cancel"(_connection, { id, projectRoot } = {}) {
1532
+ if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
1533
+ if (typeof id !== "string") throw new RpcError(RPC_ERROR.invalidParams, "id is required");
1534
+ requestedProject(projectRoot);
1535
+ const job = await storeJob(id, projectRoot);
1536
+ if (!job) throw new RpcError(ERROR.notFound, `No scheduled job ${id}`);
1537
+ if (scheduler?.delivering(id)) throw new RpcError(ERROR.conflict, `Job ${id} is being delivered now`, { reason: "key_conflict" });
1538
+ try {
1539
+ const cancelled = await schedules.cancel(id, { projectRoot });
1540
+ scheduler?.release(cancelled);
1541
+ return { job: cancelled };
1542
+ } catch (error) {
1543
+ throw scheduleFailed(error);
1544
+ }
1545
+ }
1546
+ };
1547
+ const registryCall = async (run) => {
1548
+ if (!registry) throw new RpcError(ERROR.unavailable, "Registry needs ALP_HOME");
1549
+ try {
1550
+ return await run();
1551
+ } catch (e) {
1552
+ if (e instanceof RegistryError) throw new RpcError(e.code, e.message, e.data);
1553
+ throw new RpcError(ERROR.failed, e instanceof Error ? e.message : String(e), { reason: "persistence_failed" });
798
1554
  }
799
1555
  };
800
- for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
1556
+ const registryList = async (kind, params = {}) => registryCall(async () => {
1557
+ const r = await registry.snapshot();
1558
+ const allowed = params.projectRoots;
1559
+ let entries = r[kind].filter((e) => kind === "projects" ? params.includeRemoved || !e.removedAt : params.includeArchived || !e.archivedAt && !r.projects.find((p) => p.id === e.projectId)?.removedAt);
1560
+ if (allowed !== void 0) {
1561
+ entries = (await Promise.all(entries.map(async (e) => {
1562
+ const directory = kind === "projects" ? e.root : e.directory;
1563
+ const canonical = await fsRealpath(directory).catch(() => void 0);
1564
+ return canonical && (!e.canonical || canonical === e.canonical) && allowed.includes(canonical) ? e : void 0;
1565
+ }))).filter(Boolean);
1566
+ }
1567
+ const offset = params.cursor === void 0 ? 0 : Number(params.cursor);
1568
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new RpcError(-32602, "Invalid registry cursor");
1569
+ const limit = params.limit ?? 100;
1570
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) throw new RpcError(-32602, "Invalid registry limit");
1571
+ 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 };
1572
+ });
1573
+ const registryMutation = (method, p) => registryCall(async () => {
1574
+ if (!Number.isSafeInteger(p.ifRevision) || p.ifRevision < 0) throw new RpcError(-32602, "ifRevision is required");
1575
+ const { requestId, ifRevision, authorizedRoots, ...args } = p;
1576
+ const result = await registry.mutate(method, args, { requestId, ifRevision, allowedRoots: authorizedRoots });
1577
+ return result.workspace ? { ...result, workspace: await workspaceDescriptor(result.workspace) } : result;
1578
+ });
1579
+ runtime.bindSchedules?.(async (action, params) => handlers[`schedule.${action}`](void 0, params));
1580
+ for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (connection, params) => handler(params, { agent: connection.agent === true });
801
1581
  Object.setPrototypeOf(handlers, null);
802
1582
  const originalMethods = /* @__PURE__ */ new Set([...Object.keys(handlers), ...RPC_METHODS]);
803
1583
  const reservedNamespaces = new Set([...originalMethods].map((method) => method.split(".")[0]));
804
1584
  async function invokeExtended(owner, caller, method, params) {
805
1585
  if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, "too many pending extension calls");
806
1586
  const id = ++owner.nextId;
807
- const invocation = { jsonrpc: "2.0", id, method: "extension.invoke", params: { method, params } };
1587
+ const invocation = { jsonrpc: "2.0", id, method: "extension.invoke", params: { method, params, caller: { agent: caller.agent === true, ...caller.agentName !== void 0 ? { agentName: caller.agentName } : {} } } };
808
1588
  if (Buffer.byteLength(encodeFrame(invocation), "utf8") > MAX_FRAME) throw new RpcError(-32600, "ALP daemon frame exceeds size limit");
809
1589
  return new Promise((resolve, reject) => {
810
1590
  const timer = setTimeout(() => {
@@ -844,7 +1624,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
844
1624
  throw new RpcError(ERROR.failed, "alpd could not read the workspace file");
845
1625
  }
846
1626
  }
847
- const capabilities = [CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts] : [], ...operations.capabilities];
1627
+ 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];
848
1628
  function fits(response) {
849
1629
  if (frameBytes(response) <= MAX_FRAME) return response;
850
1630
  log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
@@ -886,8 +1666,20 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
886
1666
  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] });
887
1667
  const issues2 = validateParams(method, params);
888
1668
  if (issues2.length) throw invalidParams(issues2);
1669
+ const named = params?.principal?.agent;
1670
+ if (named !== void 0 && (typeof named !== "string" || !AGENT_NAME.test(named))) throw new RpcError(RPC_ERROR.invalidParams, "principal.agent must be an agent name", { reason: "invalid_params" });
889
1671
  connection.helloed = true;
890
- respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities } });
1672
+ connection.agent = connection.agent === true || Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY);
1673
+ if (typeof params?.client?.name === "string") connection.client = params.client.name;
1674
+ if (named !== void 0) {
1675
+ connection.agent = true;
1676
+ if (connection.agentName === void 0) {
1677
+ connection.agentName = named;
1678
+ log.info("an agent connection named itself", { code: "ALP_AGENT_CONNECTION", agentName: named, client: connection.client });
1679
+ } 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 });
1680
+ }
1681
+ const terminalLimits = await terminals?.advertised();
1682
+ 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 } : {} } });
891
1683
  return;
892
1684
  }
893
1685
  if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first", { reason: "hello_required" });
@@ -927,6 +1719,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
927
1719
  }
928
1720
  connections.delete(connection);
929
1721
  watchers.delete(connection);
1722
+ terminals?.disconnect(connection);
930
1723
  for (const root of [...connection.roots]) {
931
1724
  detach(connection, root);
932
1725
  void reap(root);
@@ -1062,6 +1855,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1062
1855
  },
1063
1856
  local() {
1064
1857
  const events = /* @__PURE__ */ new Set();
1858
+ const notifications = /* @__PURE__ */ new Set();
1065
1859
  const closes = /* @__PURE__ */ new Set();
1066
1860
  const pending = /* @__PURE__ */ new Map();
1067
1861
  let sequence = 0;
@@ -1076,6 +1870,10 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1076
1870
  for (const listener of events) listener(message.params);
1077
1871
  return;
1078
1872
  }
1873
+ if (typeof message.method === "string" && message.id === void 0) {
1874
+ for (const listener of notifications) listener(message.method, message.params);
1875
+ return;
1876
+ }
1079
1877
  const waiter = pending.get(message.id);
1080
1878
  if (!waiter) return;
1081
1879
  pending.delete(message.id);
@@ -1097,6 +1895,10 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1097
1895
  events.add(listener);
1098
1896
  return () => events.delete(listener);
1099
1897
  },
1898
+ onNotification(listener) {
1899
+ notifications.add(listener);
1900
+ return () => notifications.delete(listener);
1901
+ },
1100
1902
  onClose(listener) {
1101
1903
  closes.add(listener);
1102
1904
  return () => closes.delete(listener);
@@ -1129,8 +1931,12 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1129
1931
  };
1130
1932
  },
1131
1933
  async close() {
1934
+ unsubscribeCatalog?.();
1132
1935
  closing = true;
1133
1936
  if (sweeper) clearInterval(sweeper);
1937
+ await attachments?.close();
1938
+ await terminals?.shutdown();
1939
+ await scheduler?.stop();
1134
1940
  const stopped = new Promise((resolve) => server.close(() => resolve()));
1135
1941
  for (const connection of connections) connection.socket?.destroy();
1136
1942
  await stopped;