@anhlp/alp-daemon 0.0.1-beta.4 → 0.0.1-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +26 -1
  2. package/dist/alpd.js +11047 -3021
  3. package/dist/attachments.d.ts +25 -49
  4. package/dist/attachments.js +45 -8
  5. package/dist/build-manifest.json +14 -1
  6. package/dist/conversation.js +18 -2
  7. package/dist/disk.d.ts +67 -0
  8. package/dist/disk.js +152 -0
  9. package/dist/files.d.ts +141 -2
  10. package/dist/files.js +377 -68
  11. package/dist/git.d.ts +8 -2
  12. package/dist/git.js +111 -12
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.js +3 -0
  15. package/dist/main.js +37 -11
  16. package/dist/native-terminal.d.ts +45 -0
  17. package/dist/native-terminal.js +198 -0
  18. package/dist/operations.d.ts +8 -2
  19. package/dist/operations.js +20 -10
  20. package/dist/registry.js +1 -1
  21. package/dist/scheduler.js +8 -2
  22. package/dist/schedules.d.ts +2 -1
  23. package/dist/schedules.js +6 -4
  24. package/dist/server.d.ts +4 -2
  25. package/dist/server.js +166 -42
  26. package/dist/store.d.ts +3 -1
  27. package/dist/store.js +4 -3
  28. package/dist/terminal-native/README.md +201 -0
  29. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  30. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  31. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  32. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  33. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  34. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  35. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  36. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  37. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  38. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  39. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  40. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  41. package/dist/terminal-native/terminal-owner.c +389 -0
  42. package/dist/terminal-screen.d.ts +24 -0
  43. package/dist/terminal-screen.js +99 -0
  44. package/dist/terminals.d.ts +43 -7
  45. package/dist/terminals.js +222 -139
  46. package/dist/windows-terminal.d.ts +29 -0
  47. package/dist/windows-terminal.js +122 -0
  48. package/dist/worktrees.d.ts +25 -1
  49. package/dist/worktrees.js +74 -2
  50. package/native/README.md +201 -0
  51. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  52. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  53. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  54. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  55. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  56. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  57. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  58. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  59. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  60. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  61. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  62. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  63. package/native/terminal-owner.c +389 -0
  64. package/package.json +11 -7
  65. package/src/attachments.ts +46 -8
  66. package/src/conversation.ts +22 -2
  67. package/src/disk.ts +175 -0
  68. package/src/files.ts +505 -80
  69. package/src/git.ts +113 -18
  70. package/src/index.ts +1 -0
  71. package/src/main.ts +30 -11
  72. package/src/native-terminal.ts +122 -0
  73. package/src/operations.ts +27 -11
  74. package/src/registry.ts +1 -1
  75. package/src/scheduler.ts +13 -3
  76. package/src/schedules.ts +5 -2
  77. package/src/server.ts +157 -35
  78. package/src/store.ts +2 -1
  79. package/src/terminal-screen.ts +74 -0
  80. package/src/terminals.ts +205 -155
  81. package/src/windows-terminal.ts +123 -0
  82. package/src/worktrees.ts +97 -2
package/src/registry.ts CHANGED
@@ -229,7 +229,7 @@ export function createRegistry(home: string, options: { write?: typeof writeFile
229
229
  if (!includeArchived && !live(r, w)) fail('not_found', 'Workspace is archived', 1001);
230
230
  if (Object.values(r.worktreeJournal ?? {}).some(j => j.intent.id === workspaceId)) fail('reconciliation_required', 'Workspace mutation requires reconciliation');
231
231
  const canonical = await identity(w.directory);
232
- if (w.canonical && canonical !== w.canonical) fail('identity_changed', 'Workspace directory identity changed', 1003);
232
+ if (canonical !== (w.canonical ?? w.directory)) fail('identity_changed', 'Workspace directory identity changed', 1003);
233
233
  if (cwd !== undefined && await identity(cwd) !== canonical) fail('cwd_mismatch', 'cwd and workspaceId must agree', -32602);
234
234
  return canonical;
235
235
  },
package/src/scheduler.ts CHANGED
@@ -100,6 +100,8 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
100
100
  const held = new Map<string, { sessionId: string; at: number }>();
101
101
  /** The jobs that wait for a session to be opened again, with the moment the wait began. */
102
102
  const opening = new Map<string, number>();
103
+ /** The jobs that wait for a busy turn to end, with the moment the wait began. */
104
+ const busy = new Map<string, number>();
103
105
  /** The sessions a job is being created for: they are held before the job is written. */
104
106
  const heldSessions = new Map<string, number>();
105
107
  /** The jobs being delivered right now; a cancel that arrives is refused. */
@@ -114,6 +116,8 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
114
116
 
115
117
  const hold = (job: ScheduleJob) => {
116
118
  if (!held.has(job.id)) held.set(job.id, { sessionId: job.sessionId, at: ++sequence });
119
+ // A job that does not keep its session open is tracked, but no session waits for it.
120
+ if (job.keepsSession === false) return;
117
121
  const ids = waiting.get(job.sessionId) ?? new Set<string>();
118
122
  ids.add(job.id);
119
123
  waiting.set(job.sessionId, ids);
@@ -121,6 +125,7 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
121
125
  const releaseId = (id: string) => {
122
126
  const entry = held.get(id);
123
127
  opening.delete(id);
128
+ busy.delete(id);
124
129
  if (!entry) return;
125
130
  held.delete(id);
126
131
  const ids = waiting.get(entry.sessionId);
@@ -247,9 +252,12 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
247
252
  if (snapshot.parentId) return fail(current, 'The session this job continues is not a root session', 'not_a_root');
248
253
  if (projectKey(snapshot.projectRoot) !== projectKey(current.projectRoot)) return fail(current, 'The session this job continues belongs to another project', 'other_project');
249
254
  const waitBusy = async (): Promise<'waiting' | 'failed'> => {
250
- // The session is working. The job waits for the turn to end; it never steers it.
251
- const overdue = now() - Date.parse(current.dueAt);
252
- if (overdue > graceMs) return fail(current, `The session was still busy ${duration(overdue)} after the job was due`, 'session_busy');
255
+ // The session is working. The wait is bounded from the moment it began: how
256
+ // late the job is says nothing about how long a running turn takes to end.
257
+ const since = busy.get(current.id) ?? now();
258
+ busy.set(current.id, since);
259
+ const waited = now() - since;
260
+ if (waited > graceMs) return fail(current, `The session was still busy after waiting ${duration(waited)}`, 'session_busy');
253
261
  // Only the note is written, and only when it says something new: a cancel that
254
262
  // happened meanwhile is not overwritten, and the file is not rewritten every tick.
255
263
  const note = { message: 'The session is busy; the job waits for its turn to end', code: 'session_busy' };
@@ -258,6 +266,8 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
258
266
  return 'waiting';
259
267
  };
260
268
  if (snapshot.activeTurnId || runtime.starting?.(current.sessionId)) return waitBusy();
269
+ // The session is idle: the wait for a busy turn is over.
270
+ busy.delete(current.id);
261
271
  const dispatch = async (send?: AlpRuntime['prompt']): Promise<'delivered' | 'failed' | 'waiting' | 'skipped'> => {
262
272
  // From here the job is being delivered: a cancel that arrives now is refused, so
263
273
  // the job and the record cannot disagree about what happened.
package/src/schedules.ts CHANGED
@@ -96,7 +96,8 @@ function readJob(text: string, name: string): ScheduleRecord | undefined {
96
96
  && (record.cancelledAt === undefined || isTime(record.cancelledAt))
97
97
  && (record.lateByMs === undefined || (Number.isSafeInteger(record.lateByMs) && record.lateByMs >= 0))
98
98
  && (record.attempts === undefined || (Number.isSafeInteger(record.attempts) && record.attempts >= 0))
99
- && (record.lastError === undefined || isError(record.lastError));
99
+ && (record.lastError === undefined || isError(record.lastError))
100
+ && (record.keepsSession === undefined || record.keepsSession === false);
100
101
  if (!sound) {
101
102
  log.warn(`skipped invalid job ${name}`, { code: 'ALP_SCHEDULE_UNREADABLE', file: name });
102
103
  return undefined;
@@ -118,6 +119,7 @@ function readJob(text: string, name: string): ScheduleRecord | undefined {
118
119
  ...(record.cancelledAt === undefined ? {} : { cancelledAt: record.cancelledAt }),
119
120
  ...(record.lateByMs === undefined ? {} : { lateByMs: record.lateByMs }),
120
121
  ...(record.lastError === undefined ? {} : { lastError: { message: record.lastError.message, ...(record.lastError.code === undefined ? {} : { code: record.lastError.code }) } }),
122
+ ...(record.keepsSession === false ? { keepsSession: false as const } : {}),
121
123
  };
122
124
  }
123
125
 
@@ -162,7 +164,7 @@ export function createScheduleStore(root: string, { now = () => Date.now() } = {
162
164
  * A new job waiting for its time. The id is drawn here, so two jobs never
163
165
  * share one and a job's own id names its delivery.
164
166
  */
165
- async create({ projectRoot, sessionId, prompt, dueAt }: { projectRoot: string; sessionId: string; prompt: string; dueAt: string }): Promise<ScheduleRecord> {
167
+ async create({ projectRoot, sessionId, prompt, dueAt, keepsSession }: { projectRoot: string; sessionId: string; prompt: string; dueAt: string; keepsSession?: boolean }): Promise<ScheduleRecord> {
166
168
  if (typeof projectRoot !== 'string' || !projectRoot) throw new ScheduleStoreError('INVALID_SCHEDULE', 'A job needs the project it continues');
167
169
  // A project is named by its absolute path: a relative one would be read against
168
170
  // the daemon's own directory, which is another project.
@@ -185,6 +187,7 @@ export function createScheduleStore(root: string, { now = () => Date.now() } = {
185
187
  attempts: 0,
186
188
  createdAt: at,
187
189
  updatedAt: at,
190
+ ...(keepsSession === false ? { keepsSession: false as const } : {}),
188
191
  });
189
192
  },
190
193
 
package/src/server.ts CHANGED
@@ -12,13 +12,13 @@ import { createLogger } from '@anhlp/alp-core/log';
12
12
  import { AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from '@anhlp/alp-protocol';
13
13
  import { validateParams } from '@anhlp/alp-protocol/contract';
14
14
  export { ERROR } from '@anhlp/alp-protocol';
15
- import { DEFAULT_MODEL, models, modes, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
15
+ import { DEFAULT_MODEL, models, modes, type ModelCatalog, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
16
16
  import type { Receipt, SessionRecord, SessionStatus, Store, UnreadableReceipt } from './store.js';
17
17
  import type { PromptContent, SessionSummary } from '@anhlp/alp-protocol/session';
18
18
  import type { ScheduleJob, TurnAttention } from '@anhlp/alp-protocol/index';
19
19
  import { RpcError } from './rpc-error.js';
20
20
  import { createOperations, type OperationsOptions } from './operations.js';
21
- import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from './files.js';
21
+ import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, searchWorkspaceFiles } from './files.js';
22
22
  import { createGitReader } from './git.js';
23
23
  import { createScheduleStore, projectKey } from './schedules.js';
24
24
  import { createAttachmentStore, type AttachmentRuntime, type AttachmentStoreOptions, type Principal } from './attachments.js';
@@ -117,6 +117,10 @@ function digest(value: unknown) {
117
117
  type Connection = {
118
118
  socket?: net.Socket;
119
119
  helloed: boolean;
120
+ /** It said in daemon.hello that an ALP agent started it (t-ca1f): refused what only the user may do. */
121
+ agent?: boolean;
122
+ /** The client name daemon.hello gave: a gate card answered from alp-paseo* is recorded as paseo, else web. */
123
+ client?: string;
120
124
  roots: Set<string>;
121
125
  send(message: unknown): void;
122
126
  nextId: number;
@@ -125,6 +129,13 @@ type Connection = {
125
129
 
126
130
  /** Retained events per live tree, for attach and replay. */
127
131
  const TREE_LOG_LIMIT = 20_000;
132
+ /** The daemon.hello capability a process an ALP agent started announces (t-ca1f; the client's handshake sends it). */
133
+ const AGENT_CAPABILITY = 'principal.agent';
134
+ /** A shell alpd opens carries no ALP_AGENT_SESSION, so an agent's connection may not open, attach to or type into one (t-ca1f). */
135
+ const agentRefused = (connection: { agent?: boolean }, method: string): undefined => {
136
+ if (connection.agent) throw new RpcError(ERROR.forbidden, `${method} is the user's; this connection was opened by an ALP agent`, { reason: 'user_only' });
137
+ return undefined;
138
+ };
128
139
  const SESSION_ID = /^[\w.:-]{1,128}$/;
129
140
  const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
130
141
  const RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
@@ -198,7 +209,9 @@ export type DaemonServer = {
198
209
  * shape so every viewer agrees; re-exported here to keep `@anhlp/alp-daemon/server`'s API. */
199
210
  export type { SessionSummary };
200
211
 
201
- export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions }: {
212
+ export function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions, modelCatalog }: {
213
+ /** The live model catalog (t-e5ee); without it catalog.get answers the static rows and catalog.refresh is unavailable. */
214
+ modelCatalog?: ModelCatalog;
202
215
  runtime: AlpRuntime;
203
216
  socketPath: string;
204
217
  version: string;
@@ -225,6 +238,15 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
225
238
  terminalOptions?: Partial<Pick<TerminalServiceOptions, 'limits' | 'now' | 'spawn' | 'processes' | 'sweepMs' | 'killGraceMs' | 'maxBufferedBytes' | 'platform'>>;
226
239
  }): DaemonServer {
227
240
  const connections = new Set<Connection>();
241
+ const catalogResult = () => {
242
+ const state = modelCatalog?.state();
243
+ return { models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}`,
244
+ ...(state ? { fetchedAt: state.fetchedAt, providers: Object.fromEntries(Object.entries(state.providers).map(([runtime, provider]) => [runtime, { status: provider!.status, fetchedAt: provider!.fetchedAt, ...(provider!.error ? { error: provider!.error } : {}) }])) } : {}) };
245
+ };
246
+ // Every helloed connection learns that the catalog changed, and re-reads it (catalog.updated).
247
+ const unsubscribeCatalog = modelCatalog?.onUpdated(snapshot => {
248
+ for (const connection of connections) if (connection.helloed) { try { connection.send({ jsonrpc: '2.0', method: 'catalog.updated', params: { fetchedAt: snapshot.fetchedAt } }); } catch { /* a gone connection */ } }
249
+ });
228
250
  /** Root of every live session. */
229
251
  const rootOf = new Map<string, string>();
230
252
  const attached = new Map<string, Set<Connection>>();
@@ -403,6 +425,11 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
403
425
  return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
404
426
  }
405
427
 
428
+ const sameProject = (a?: string, b?: string) => {
429
+ if (a === undefined || b === undefined) return a === b;
430
+ return a === b || projectKey(a) === projectKey(b);
431
+ };
432
+
406
433
  /**
407
434
  * Tells watchers not attached to the tree of a question asked or resolved there, or, for those
408
435
  * that asked for `turns`, of the end of a root's turn. Their copy has no `cursor`: it is not part
@@ -415,7 +442,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
415
442
  for (const [connection, { projectRoot, turns }] of watchers) {
416
443
  if (turn && !turns) continue;
417
444
  if (attached.get(root)?.has(connection)) continue;
418
- if (projectRoot !== undefined && project !== projectRoot) continue;
445
+ if (projectRoot !== undefined && !sameProject(project, projectRoot)) continue;
419
446
  deliver(connection, announced);
420
447
  }
421
448
  }
@@ -431,7 +458,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
431
458
  const envelope: Envelope = { sessionId: root, epoch: `attention-${startedAt}`, seq: 0, ts: new Date().toISOString(), event: { type: 'attention', ...(attention ? { attention } : {}) } };
432
459
  for (const [connection, watch] of watchers) {
433
460
  if (!watch.attention) continue;
434
- if (watch.projectRoot !== undefined && project !== watch.projectRoot) continue;
461
+ if (watch.projectRoot !== undefined && !sameProject(project, watch.projectRoot)) continue;
435
462
  deliver(connection, envelope);
436
463
  }
437
464
  }
@@ -448,7 +475,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
448
475
  const found: Array<{ sessionId: string; attention: TurnAttention }> = [];
449
476
  for (const record of records.values()) {
450
477
  if (record.id !== record.rootId || !record.attention || record.archived) continue;
451
- if (projectRoot !== undefined && projectOf(record.id) !== projectRoot) continue;
478
+ if (projectRoot !== undefined && !sameProject(projectOf(record.id), projectRoot)) continue;
452
479
  found.push({ sessionId: record.id, attention: record.attention });
453
480
  }
454
481
  return found;
@@ -691,8 +718,10 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
691
718
  }
692
719
 
693
720
  /** Retention while alpd runs: receipts past their window, then expired trees; temporary files stay, as writes may be under way. */
721
+ let sweeping = false;
694
722
  async function sweep() {
695
- if (closing || !store) return;
723
+ if (closing || !store || sweeping) return;
724
+ sweeping = true;
696
725
  try {
697
726
  await restored;
698
727
  await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
@@ -700,6 +729,8 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
700
729
  await expire(trees(records.values()));
701
730
  } catch (error) {
702
731
  recoveryLog.warn('retention sweep failed', { code: 'ALP_RETENTION_FAILED', error });
732
+ } finally {
733
+ sweeping = false;
703
734
  }
704
735
  }
705
736
  const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : undefined;
@@ -1049,10 +1080,17 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1049
1080
  const worktrees = home && registry && process.platform !== 'win32' ? createWorkspaceWorktrees(home, registry, async (directory, run) => {
1050
1081
  if (!runtime.withWorkspaceMutation) throw new RegistryError(1005, 'Runtime cannot prove safe worktree removal', { reason: 'guard_unavailable' });
1051
1082
  try { return await runtime.withWorkspaceMutation(directory, run); } catch (error: any) { if (error?.data?.reason) throw new RegistryError(1004, 'Workspace is in use or has retained assignment results', error.data); throw error; }
1052
- }, async directory => { if (!runtime.registerWorkspace) throw new RegistryError(1005, 'Runtime cannot register safe workspace ownership', { reason: 'guard_unavailable' }); await runtime.registerWorkspace(directory); }) : undefined;
1083
+ }, async directory => { if (!runtime.registerWorkspace) throw new RegistryError(1005, 'Runtime cannot register safe workspace ownership', { reason: 'guard_unavailable' }); await runtime.registerWorkspace(directory); },
1084
+ // Owner-audited adoption (t-c1ba); no RPC exposes it yet, so the default stays refusal.
1085
+ runtime.adoptWorkspace ? async (directory, verify) => {
1086
+ try { await runtime.adoptWorkspace!(directory, verify); } catch (error: any) { if (error?.data?.reason && !(error instanceof RegistryError)) throw new RegistryError(1004, 'Workspace is in use, has retained assignment results or changed identity', error.data); throw error; }
1087
+ } : undefined) : undefined;
1053
1088
  const workspaceDescriptor = async (w: any) => worktrees ? worktrees.describe(w) : w;
1054
1089
  // workspace.git.status and workspace.git.diff (§12.5): read-only, by registry workspaceId.
1055
1090
  const gitReader = registry ? createGitReader({ registry, log: (message, fields) => log.warn(message, { code: 'ALPD_GIT_READ_FAILED', ...fields }) }) : undefined;
1091
+ // workspace.git.facts (§12.5): the owner's host directory, registered or not; no registry, so
1092
+ // never a gateway's (prohibited there) nor an agent's connection's.
1093
+ const gitFacts = createGitReader({ log: (message, fields) => log.warn(message, { code: 'ALPD_GIT_READ_FAILED', ...fields }) });
1056
1094
  // Terminals (§12.10): a real PTY shell as the daemon's account, only while the host opted in
1057
1095
  // (<ALP_HOME>/terminal.json); bound to the caller's principal and the workspace's directory.
1058
1096
  const terminals = home && registry ? createTerminalService({
@@ -1065,16 +1103,24 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1065
1103
  if (!terminals) throw new RpcError(ERROR.unavailable, 'This alpd has no home: it serves no terminals', { reason: 'terminal_unsupported' });
1066
1104
  return run(terminals);
1067
1105
  };
1068
- const attachmentCall = <T>(run: (store: NonNullable<typeof attachments>) => Promise<T>) => {
1106
+ const attachmentCall = async <T>(run: (store: NonNullable<typeof attachments>) => Promise<T>) => {
1069
1107
  if (!attachments) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not store attachments (capability attachments is not listed)');
1070
- return run(attachments);
1108
+ try {
1109
+ return await run(attachments);
1110
+ } catch (error) {
1111
+ if (error instanceof RpcError) throw error;
1112
+ log.warn('attachment call failed', { code: 'ALPD_ATTACHMENT_FAILED', error });
1113
+ throw new RpcError(ERROR.failed, 'alpd could not store the attachment; the upload was aborted', { reason: 'persistence_failed' });
1114
+ }
1071
1115
  };
1072
1116
  const gitCall = <T>(run: (reader: NonNullable<typeof gitReader>) => Promise<T>) => {
1073
1117
  if (!gitReader) throw new RpcError(ERROR.unavailable, 'Registry needs ALP_HOME');
1074
1118
  return run(gitReader);
1075
1119
  };
1076
- const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap(record => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
1120
+ const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap(record => record.session?.projectRoot ? [record.session.projectRoot] : [])), onGateChange: root => runtime.syncGates?.(root) });
1077
1121
  const extensionOwners = new Map<string, Connection>();
1122
+ /** workspace.files.find's snapshots, each for the connection that asked. */
1123
+ const findPages = createFindPages();
1078
1124
  const handlers: Record<string, (connection: Connection, params: any) => Promise<unknown> | unknown> = {
1079
1125
  'extension.register': async (connection, params) => {
1080
1126
  const method = params?.method;
@@ -1128,7 +1174,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1128
1174
  },
1129
1175
 
1130
1176
  'question.list'(_connection, { projectRoot } = {}) {
1131
- return { questions: runtime.questions().filter(question => projectRoot === undefined || projectOf(question.rootId) === projectRoot) };
1177
+ return { questions: runtime.questions().filter(question => projectRoot === undefined || sameProject(projectOf(question.rootId), projectRoot)) };
1132
1178
  },
1133
1179
 
1134
1180
  /**
@@ -1142,7 +1188,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1142
1188
  // No await between registering and listing: an event either is in the list or follows it.
1143
1189
  watchers.set(connection, { projectRoot, turns: turns === true, attention: attention === true });
1144
1190
  return {
1145
- questions: runtime.questions().filter(question => projectRoot === undefined || projectOf(question.rootId) === projectRoot),
1191
+ questions: runtime.questions().filter(question => projectRoot === undefined || sameProject(projectOf(question.rootId), projectRoot)),
1146
1192
  ...(attention === true ? { attention: attentionOf(projectRoot) } : {}),
1147
1193
  };
1148
1194
  },
@@ -1196,13 +1242,30 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1196
1242
  * read-only, confined to it, no link followed, blocked paths always refused, .gitignore'd ones
1197
1243
  * unless includeIgnored (docs/protocol/alp-json-rpc-v1.md §12.4, ALPD §15).
1198
1244
  */
1199
- async 'workspace.files.list'(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
1200
- return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
1245
+ async 'workspace.files.list'(_connection, { projectRoot, path: relative, includeIgnored, cursor, internalLinks } = {}) {
1246
+ return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true, cursor, internalLinks: internalLinks === true }));
1201
1247
  },
1202
1248
  async 'workspace.files.read'(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
1203
1249
  return filesCall(projectRoot, () => readWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
1204
1250
  },
1205
1251
 
1252
+ /**
1253
+ * Every name under projectRoot in pages of a snapshot kept for this connection, and a file's
1254
+ * preview in chunks (docs/protocol/alp-json-rpc-v1.md §12.11): what the Paseo bridge's Files
1255
+ * panel and suggestions read, confined as workspace.files.read is. The gateway exposes neither.
1256
+ */
1257
+ async 'workspace.files.find'(connection, { projectRoot, query, kinds, matchMode, limit, cursor } = {}) {
1258
+ return filesCall(projectRoot, () => findPages(connection, projectRoot, { query, kinds, matchMode, limit, cursor }));
1259
+ },
1260
+ async 'workspace.files.preview'(_connection, { projectRoot, path: relative, includeIgnored, internalLinks, maxBytes, offset, revision } = {}) {
1261
+ return filesCall(projectRoot, () => previewWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true, internalLinks: internalLinks === true, maxBytes, offset, revision }));
1262
+ },
1263
+
1264
+ /** The host's directories for the folder to add as a project (§12.11): the owner's own names, never remote. */
1265
+ async 'host.directories.search'(_connection, { query, limit } = {}) {
1266
+ return searchHostDirectories(query, { limit });
1267
+ },
1268
+
1206
1269
  /** The project board: live claims, decisions and findings (ALPD §18). */
1207
1270
  async 'board.list'(_connection, { projectRoot } = {}) {
1208
1271
  if (typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, 'An absolute projectRoot is required');
@@ -1235,13 +1298,16 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1235
1298
  }
1236
1299
  },
1237
1300
 
1238
- 'question.answer'(_connection, { questionId, text, dismiss = false, reason }) {
1301
+ 'question.answer'(connection, { questionId, text, dismiss = false, reason }) {
1302
+ // An answer speaks for the user (a gate card's answer decides the gate): never from a connection an ALP agent opened (t-ca1f).
1303
+ if (connection.agent) throw new RpcError(ERROR.forbidden, 'Only the user answers a question; this connection was opened by an ALP agent', { reason: 'user_only' });
1239
1304
  if (typeof questionId !== 'string') throw new RpcError(-32602, 'questionId is required');
1240
1305
  if (dismiss !== true && typeof text !== 'string') throw new RpcError(-32602, 'text or dismiss is required');
1241
1306
  // A unique prefix is enough, as in the CLI.
1242
1307
  const matches = runtime.questions().filter(question => question.id === questionId || question.id.startsWith(questionId));
1243
1308
  if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
1244
- runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason } : { text });
1309
+ const channel = connection.client?.startsWith('alp-paseo') ? 'paseo' as const : 'web' as const;
1310
+ runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1245
1311
  return { questionId: matches[0].id };
1246
1312
  },
1247
1313
 
@@ -1255,12 +1321,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1255
1321
  const { receipts: _receipts, ...metadata } = await registry!.snapshot();
1256
1322
  return { ...(result ? { result } : {}), registry: metadata };
1257
1323
  }),
1258
- 'registry.worktree': (_c, p) => registryCall(() => worktrees!.grants(p)),
1259
- 'workspace.worktree.options': (_c, p) => registryCall(async () => { const w = (await registry!.snapshot()).workspaces.find(w => w.id === p.workspaceId); if (!w) throw new RegistryError(1001, 'No workspace', { reason: 'not_found' }); const grants = await worktrees!.grants(p); return { mappingIds: grants.mappings.filter(m => m.source === (w.canonical ?? w.directory)).map(m => m.id) }; }),
1260
- 'workspace.worktree.create': (_c, p) => registryCall(async () => { const result = await worktrees!.mutate('create', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
1261
- 'workspace.worktree.remove': (_c, p) => registryCall(async () => { const result = await worktrees!.mutate('remove', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
1324
+ 'registry.worktree': (_c, p) => registryCall(async () => worktrees ? worktrees.grants(p) : { mappings: [], workspaces: [] }),
1325
+ 'workspace.worktree.options': (_c, p) => registryCall(async () => { const w = (await registry!.snapshot()).workspaces.find(w => w.id === p.workspaceId); if (!w) throw new RegistryError(1001, 'No workspace', { reason: 'not_found' }); const grants = worktrees ? await worktrees.grants(p) : { mappings: [], workspaces: [] }; return { mappingIds: grants.mappings.filter(m => m.source === (w.canonical ?? w.directory)).map(m => m.id) }; }),
1326
+ 'workspace.worktree.create': (_c, p) => registryCall(async () => { if (!worktrees) throw new RegistryError(1005, 'Worktrees are unavailable on this platform', { reason: 'worktrees_unsupported' }); const result = await worktrees.mutate('create', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
1327
+ 'workspace.worktree.remove': (_c, p) => registryCall(async () => { if (!worktrees) throw new RegistryError(1005, 'Worktrees are unavailable on this platform', { reason: 'worktrees_unsupported' }); const result = await worktrees.mutate('remove', p, p); return { ...result, workspace: await workspaceDescriptor(result.workspace) }; }),
1262
1328
  'workspace.git.status': (_c, p) => gitCall(reader => reader.status(p.workspaceId)),
1263
1329
  'workspace.git.diff': (_c, p) => gitCall(reader => reader.diff({ workspaceId: p.workspaceId, compare: p.compare, path: p.path, cursor: p.cursor })),
1330
+ 'workspace.git.facts': (c, p) => agentRefused(c, 'workspace.git.facts') ?? gitFacts.facts(p.directory),
1264
1331
  'project.list': (_c, p) => registryList('projects', p),
1265
1332
  'workspace.list': (_c, p) => registryList('workspaces', p),
1266
1333
  'workspace.get': (_c, p) => registryCall(async () => {
@@ -1271,15 +1338,23 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1271
1338
  'project.register': (_c, p) => registryMutation('project.register', p),
1272
1339
  'project.remove': (_c, p) => registryMutation('project.remove', p),
1273
1340
  'workspace.update': (_c, p) => registryMutation('workspace.update', p),
1274
- 'catalog.get': () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
1341
+ 'catalog.get': () => catalogResult(),
1342
+ 'catalog.refresh': async () => {
1343
+ if (!modelCatalog) throw new RpcError(ERROR.unavailable, 'The live model catalog is not available');
1344
+ await modelCatalog.refresh();
1345
+ return catalogResult();
1346
+ },
1275
1347
  // attachment.* (§12.6): each call acts for its principal context; without the store (no home or
1276
1348
  // store, or Windows) alpd does not serve them, as for any method it does not know.
1277
1349
  // terminal.* (§12.10): each call acts for its principal context; input, resize and the stream
1278
1350
  // belong to the connection that attached the terminal.
1279
- 'terminal.create': (_c, p) => terminalCall(service => service.create(principalOf(p), p)),
1351
+ 'terminal.create': (c, p) => agentRefused(c, 'terminal.create') ?? terminalCall(service => service.create(principalOf(p), p)),
1352
+ 'terminal.watch': (c, p) => terminalCall(service => service.watch(principalOf(p), c, p)),
1353
+ 'terminal.unwatch': (c) => terminalCall(service => service.unwatch(c)),
1354
+ 'terminal.capture': (_c, p) => terminalCall(service => service.capture(principalOf(p), p)),
1280
1355
  'terminal.list': (_c, p) => terminalCall(service => service.list(principalOf(p), p)),
1281
- 'terminal.attach': (c, p) => terminalCall(service => service.attach(principalOf(p), c, p)),
1282
- 'terminal.input': (c, p) => terminalCall(service => service.input(principalOf(p), c, p)),
1356
+ 'terminal.attach': (c, p) => agentRefused(c, 'terminal.attach') ?? terminalCall(service => service.attach(principalOf(p), c, p)),
1357
+ 'terminal.input': (c, p) => agentRefused(c, 'terminal.input') ?? terminalCall(service => service.input(principalOf(p), c, p)),
1283
1358
  'terminal.resize': (c, p) => terminalCall(service => service.resize(principalOf(p), c, p)),
1284
1359
  'terminal.close': (_c, p) => terminalCall(service => service.close(principalOf(p), p)),
1285
1360
  'terminal.revoke': (_c, p) => terminalCall(service => service.revoke(p.principalId)),
@@ -1299,6 +1374,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1299
1374
  if (prior && prior !== workspaceId) throw new RpcError(ERROR.conflict, 'Session belongs to another workspace', { reason: 'workspace_mismatch' });
1300
1375
  }
1301
1376
  if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
1377
+ // spec.restore opens a named native thread (or a Claude base) as this root's conversation: the
1378
+ // owner's alone. A connection an ALP agent opened never passes it on (a gateway refuses it).
1379
+ if (connection.agent && spec.restore !== undefined) {
1380
+ const { restore: _restore, ...owned } = spec;
1381
+ spec = owned;
1382
+ }
1302
1383
  if (worktrees) await registryCall(() => worktrees.assertAvailable(spec.cwd));
1303
1384
  if (sessionId !== undefined && (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, 'Invalid session id');
1304
1385
  if (history !== 'replay' && history !== 'skip') throw new RpcError(-32602, 'history must be replay or skip');
@@ -1430,6 +1511,9 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1430
1511
  for (const envelope of live) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
1431
1512
  }
1432
1513
  announceQuestions(connection, root);
1514
+ // Gate cards are rebuilt from the project's tasks: one changed while nobody watched shows or settles now.
1515
+ const gateProject = runtime.snapshot(root)?.projectRoot;
1516
+ if (gateProject) void runtime.syncGates?.(gateProject)?.catch(() => {});
1433
1517
  return { session: root === found.id ? found : summary(root), cursor: tip, ...(reset ? { reset: true } : {}) };
1434
1518
  }
1435
1519
  },
@@ -1502,6 +1586,14 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1502
1586
  return conversation.reload(params);
1503
1587
  },
1504
1588
 
1589
+ /** Compacts a live root's context now or at its next turn boundary (t-0e56). */
1590
+ async 'session.compact'(_connection, { sessionId }) {
1591
+ if (typeof sessionId !== 'string' || !sessionId) throw new RpcError(-32602, 'sessionId is required');
1592
+ if (!runtime.compact) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not compact sessions');
1593
+ try { return runtime.compact(sessionId); }
1594
+ catch (error) { throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error)); }
1595
+ },
1596
+
1505
1597
  /** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
1506
1598
  async 'session.resumeCommand'(_connection, { sessionId }) {
1507
1599
  if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd has no resume command (capability session.resumeCommand is not listed)');
@@ -1582,16 +1674,41 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1582
1674
  * a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
1583
1675
  */
1584
1676
  'session.list'(_connection, { projectRoot, projectRoots, rootsOnly = false, includeClosed = false, includeArchived = false, limit, cursor, query } = {}): { sessions: SessionSummary[]; nextCursor?: string } {
1585
- const projects = Array.isArray(projectRoots) ? new Set<string>(projectRoots) : undefined;
1677
+ const cache = new Map<string, string>();
1678
+ const keyOf = (root: string) => {
1679
+ let key = cache.get(root);
1680
+ if (key === undefined) {
1681
+ key = projectKey(root);
1682
+ cache.set(root, key);
1683
+ }
1684
+ return key;
1685
+ };
1686
+ // Projects are matched by their canonical identity (projectKey), so sessions created
1687
+ // under a symlink (or /var -> /private/var on macOS) are listed when queried by their
1688
+ // canonical path, and vice versa.
1689
+ const wantedKey = projectRoot === undefined ? undefined : keyOf(projectRoot);
1690
+ const allowedKeys = Array.isArray(projectRoots) ? new Set<string>(projectRoots.map(keyOf)) : undefined;
1586
1691
  const after = cursor === undefined ? undefined : listCursor.decode(cursor);
1587
1692
  const words = typeof query === 'string' ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
1588
- const ids = new Set([...runtime.list().map(session => session.id), ...records.keys()]);
1693
+ const live = runtime.list();
1694
+ const liveChildren = rootsOnly ? new Set(live.filter(session => !!session.parentId).map(session => session.id)) : undefined;
1695
+ const ids = new Set<string>();
1696
+ for (const session of live) {
1697
+ if (!rootsOnly || !session.parentId) ids.add(session.id);
1698
+ }
1699
+ for (const [id, record] of records) {
1700
+ if (!rootsOnly) {
1701
+ ids.add(id);
1702
+ } else if (record.id === record.rootId && !record.session?.parentId && !liveChildren!.has(id)) {
1703
+ ids.add(id);
1704
+ }
1705
+ }
1589
1706
  const sessions = [...ids].map(summary).filter((session): session is SessionSummary => !!session)
1590
1707
  .filter(session => includeClosed || session.status === 'idle' || session.status === 'running')
1591
1708
  .filter(session => includeArchived || !session.archived)
1592
1709
  .filter(session => !rootsOnly || !session.parentId)
1593
- .filter(session => projectRoot === undefined || session.projectRoot === projectRoot)
1594
- .filter(session => !projects || projects.has(session.projectRoot))
1710
+ .filter(session => wantedKey === undefined || keyOf(session.projectRoot) === wantedKey)
1711
+ .filter(session => !allowedKeys || allowedKeys.has(keyOf(session.projectRoot)))
1595
1712
  .filter(session => !words.length || words.every(word => `${session.title ?? ''}\n${session.id}`.toLowerCase().includes(word)))
1596
1713
  .sort((a, b) => listCursor.compare(listCursor.key(a), listCursor.key(b)))
1597
1714
  .filter(session => !after || listCursor.compare(listCursor.key(session), after) > 0);
@@ -1606,11 +1723,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1606
1723
  * the project; a session that is closed when the job is due fails the job, and the
1607
1724
  * reason is kept.
1608
1725
  */
1609
- async 'schedule.create'(_connection, { projectRoot, sessionId, dueAt, prompt } = {}) {
1726
+ async 'schedule.create'(_connection, { projectRoot, sessionId, dueAt, prompt, keepsSession } = {}) {
1610
1727
  if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
1611
1728
  if (typeof projectRoot !== 'string' || typeof sessionId !== 'string' || typeof dueAt !== 'string' || typeof prompt !== 'string') {
1612
1729
  throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot, sessionId, dueAt and prompt are required');
1613
1730
  }
1731
+ if (keepsSession !== undefined && typeof keepsSession !== 'boolean') throw new RpcError(RPC_ERROR.invalidParams, 'keepsSession must be true or false');
1614
1732
  if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot must be an absolute path');
1615
1733
  const snapshot = runtime.snapshot(sessionId);
1616
1734
  if (!snapshot) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not open`);
@@ -1623,7 +1741,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1623
1741
  // in between; the job's own hold takes over once it exists.
1624
1742
  scheduler?.holdSession(sessionId);
1625
1743
  try {
1626
- const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt });
1744
+ const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt, keepsSession });
1627
1745
  scheduler?.hold(job);
1628
1746
  return { job };
1629
1747
  } catch (error) {
@@ -1706,7 +1824,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1706
1824
  return result.workspace ? { ...result, workspace: await workspaceDescriptor(result.workspace) } : result;
1707
1825
  });
1708
1826
  runtime.bindSchedules?.(async (action, params) => handlers[`schedule.${action}`](undefined as any, params));
1709
- for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
1827
+ for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (connection, params) => handler(params, { agent: connection.agent === true });
1710
1828
  Object.setPrototypeOf(handlers, null);
1711
1829
  // Every v1 method name stays the daemon's, served here or not, so no extension takes one.
1712
1830
  const originalMethods = new Set([...Object.keys(handlers), ...RPC_METHODS]);
@@ -1764,7 +1882,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1764
1882
  }
1765
1883
 
1766
1884
  /** What this daemon lists in daemon.hello: only features it serves now (docs/protocol/alp-json-rpc-v1.md §6). */
1767
- const capabilities = [...(runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : []), CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...(store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : []), ...(schedules ? [CAPABILITY.schedule] : []), ...(registry ? ['workspace.registry', CAPABILITY.workspaceGit] : []), ...(worktrees ? ['workspace.worktree'] : []), ...(attachments ? [CAPABILITY.attachments] : []), ...(conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : []), ...(conversation?.reloads ? [CAPABILITY.sessionReload] : []), ...(conversation?.configures ? [CAPABILITY.sessionConfigureLive] : []), ...(conversation ? [CAPABILITY.sessionResumeCommand] : []), ...operations.capabilities];
1885
+ const capabilities = [...(runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : []), CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.workspaceFilesBrowse, CAPABILITY.hostDirectories, CAPABILITY.promptImages, ...(store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : []), ...(schedules ? [CAPABILITY.schedule] : []), ...(registry ? ['workspace.registry', CAPABILITY.workspaceGit] : []), CAPABILITY.workspaceGitFacts, ...(worktrees ? ['workspace.worktree'] : []), ...(attachments ? [CAPABILITY.attachments] : []), ...(conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : []), ...(conversation?.reloads ? [CAPABILITY.sessionReload] : []), ...(conversation?.configures ? [CAPABILITY.sessionConfigureLive] : []), ...(conversation ? [CAPABILITY.sessionResumeCommand] : []), ...(modelCatalog ? [CAPABILITY.catalogLive] : []), ...operations.capabilities];
1768
1886
 
1769
1887
  /** A response too large for the wire becomes an error the client can read. */
1770
1888
  function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
@@ -1815,9 +1933,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1815
1933
  const issues = validateParams(method, params)!;
1816
1934
  if (issues.length) throw invalidParams(issues);
1817
1935
  connection.helloed = true;
1936
+ // Sticky: a later hello never sheds it.
1937
+ connection.agent = connection.agent === true || (Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY));
1938
+ if (typeof params?.client?.name === 'string') connection.client = params.client.name;
1818
1939
  // Terminals are listed only while the host's switch is on (and the PTY module loads).
1819
1940
  const terminalLimits = await terminals?.advertised();
1820
- respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities: terminalLimits ? [...capabilities, CAPABILITY.terminal] : capabilities, ...(attachments ? { attachmentLimits: attachments.limits } : {}), ...(terminalLimits ? { terminalLimits } : {}) } });
1941
+ respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities: terminalLimits ? [...capabilities, CAPABILITY.terminal, CAPABILITY.terminalCapture, CAPABILITY.terminalWatch] : capabilities, ...(attachments ? { attachmentLimits: attachments.limits } : {}), ...(terminalLimits ? { terminalLimits } : {}) } });
1821
1942
  return;
1822
1943
  }
1823
1944
  if (!connection.helloed) throw new RpcError(ERROR.protocol, 'daemon.hello is required first', { reason: 'hello_required' });
@@ -2034,9 +2155,10 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
2034
2155
  },
2035
2156
 
2036
2157
  async close() {
2158
+ unsubscribeCatalog?.();
2037
2159
  closing = true;
2038
2160
  if (sweeper) clearInterval(sweeper);
2039
- attachments?.close();
2161
+ await attachments?.close();
2040
2162
  // Every terminal ends with alpd, its whole process tree killed.
2041
2163
  await terminals?.shutdown();
2042
2164
  // The tick that runs now is waited for: a delivery under way finishes, so its
package/src/store.ts CHANGED
@@ -91,7 +91,7 @@ const TAIL_CHUNK = 64 * 1024;
91
91
 
92
92
  export type Store = ReturnType<typeof createStore>;
93
93
 
94
- export function createStore(root: string) {
94
+ export function createStore(root: string, options: { onWriteError?: (error: unknown) => void } = {}) {
95
95
  const sessionsDir = path.join(root, 'sessions');
96
96
  const timelineDir = path.join(root, 'timeline');
97
97
  const historyIndexes = new Map<string, ReturnType<typeof createHistoryIndex>>();
@@ -136,6 +136,7 @@ export function createStore(root: string) {
136
136
  health.failures++;
137
137
  health.lastError = { at: new Date().toISOString(), operation, message: error?.message ?? String(error) };
138
138
  log.error(`${operation} failed`, { code: 'ALP_PERSISTENCE_WRITE_FAILED', operation, error, ...ids });
139
+ options.onWriteError?.(error);
139
140
  });
140
141
  map.set(key, settled);
141
142
  void settled.then(() => { if (map.get(key) === settled) map.delete(key); });