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

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 +10768 -2592
  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 +57 -12
  16. package/dist/native-terminal.d.ts +45 -0
  17. package/dist/native-terminal.js +198 -0
  18. package/dist/operations.d.ts +12 -2
  19. package/dist/operations.js +22 -11
  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 +171 -43
  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 +53 -13
  72. package/src/native-terminal.ts +122 -0
  73. package/src/operations.ts +28 -12
  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 +164 -36
  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/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
- import { createOperations, type OperationsOptions } from './operations.js';
21
- import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from './files.js';
20
+ import { createOperations, fromCore, type OperationsOptions } from './operations.js';
21
+ import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, searchWorkspaceFiles } from './files.js';
22
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,22 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1235
1298
  }
1236
1299
  },
1237
1300
 
1238
- 'question.answer'(_connection, { questionId, text, dismiss = false, reason }) {
1301
+ async '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
+ // A gate card's answer settles once its decision is written; one that decides nothing is refused (t-595d).
1311
+ const decided = runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1312
+ if (decided) await decided.catch((error: any) => {
1313
+ // Another answer is being recorded, or another channel decided first: as task.gate.resolve says it.
1314
+ if (error?.code === 'GATE_BUSY' || error?.code === 'GATE_DECIDED') throw new RpcError(ERROR.conflict, error.message, { reason: 'task_state' });
1315
+ throw fromCore(error);
1316
+ });
1245
1317
  return { questionId: matches[0].id };
1246
1318
  },
1247
1319
 
@@ -1255,12 +1327,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1255
1327
  const { receipts: _receipts, ...metadata } = await registry!.snapshot();
1256
1328
  return { ...(result ? { result } : {}), registry: metadata };
1257
1329
  }),
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) }; }),
1330
+ 'registry.worktree': (_c, p) => registryCall(async () => worktrees ? worktrees.grants(p) : { mappings: [], workspaces: [] }),
1331
+ '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) }; }),
1332
+ '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) }; }),
1333
+ '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
1334
  'workspace.git.status': (_c, p) => gitCall(reader => reader.status(p.workspaceId)),
1263
1335
  'workspace.git.diff': (_c, p) => gitCall(reader => reader.diff({ workspaceId: p.workspaceId, compare: p.compare, path: p.path, cursor: p.cursor })),
1336
+ 'workspace.git.facts': (c, p) => agentRefused(c, 'workspace.git.facts') ?? gitFacts.facts(p.directory),
1264
1337
  'project.list': (_c, p) => registryList('projects', p),
1265
1338
  'workspace.list': (_c, p) => registryList('workspaces', p),
1266
1339
  'workspace.get': (_c, p) => registryCall(async () => {
@@ -1271,15 +1344,23 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1271
1344
  'project.register': (_c, p) => registryMutation('project.register', p),
1272
1345
  'project.remove': (_c, p) => registryMutation('project.remove', p),
1273
1346
  'workspace.update': (_c, p) => registryMutation('workspace.update', p),
1274
- 'catalog.get': () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
1347
+ 'catalog.get': () => catalogResult(),
1348
+ 'catalog.refresh': async () => {
1349
+ if (!modelCatalog) throw new RpcError(ERROR.unavailable, 'The live model catalog is not available');
1350
+ await modelCatalog.refresh();
1351
+ return catalogResult();
1352
+ },
1275
1353
  // attachment.* (§12.6): each call acts for its principal context; without the store (no home or
1276
1354
  // store, or Windows) alpd does not serve them, as for any method it does not know.
1277
1355
  // terminal.* (§12.10): each call acts for its principal context; input, resize and the stream
1278
1356
  // belong to the connection that attached the terminal.
1279
- 'terminal.create': (_c, p) => terminalCall(service => service.create(principalOf(p), p)),
1357
+ 'terminal.create': (c, p) => agentRefused(c, 'terminal.create') ?? terminalCall(service => service.create(principalOf(p), p)),
1358
+ 'terminal.watch': (c, p) => terminalCall(service => service.watch(principalOf(p), c, p)),
1359
+ 'terminal.unwatch': (c) => terminalCall(service => service.unwatch(c)),
1360
+ 'terminal.capture': (_c, p) => terminalCall(service => service.capture(principalOf(p), p)),
1280
1361
  '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)),
1362
+ 'terminal.attach': (c, p) => agentRefused(c, 'terminal.attach') ?? terminalCall(service => service.attach(principalOf(p), c, p)),
1363
+ 'terminal.input': (c, p) => agentRefused(c, 'terminal.input') ?? terminalCall(service => service.input(principalOf(p), c, p)),
1283
1364
  'terminal.resize': (c, p) => terminalCall(service => service.resize(principalOf(p), c, p)),
1284
1365
  'terminal.close': (_c, p) => terminalCall(service => service.close(principalOf(p), p)),
1285
1366
  'terminal.revoke': (_c, p) => terminalCall(service => service.revoke(p.principalId)),
@@ -1299,6 +1380,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1299
1380
  if (prior && prior !== workspaceId) throw new RpcError(ERROR.conflict, 'Session belongs to another workspace', { reason: 'workspace_mismatch' });
1300
1381
  }
1301
1382
  if (!spec || typeof spec !== 'object' || typeof spec.cwd !== 'string') throw new RpcError(-32602, 'spec.cwd is required');
1383
+ // spec.restore opens a named native thread (or a Claude base) as this root's conversation: the
1384
+ // owner's alone. A connection an ALP agent opened never passes it on (a gateway refuses it).
1385
+ if (connection.agent && spec.restore !== undefined) {
1386
+ const { restore: _restore, ...owned } = spec;
1387
+ spec = owned;
1388
+ }
1302
1389
  if (worktrees) await registryCall(() => worktrees.assertAvailable(spec.cwd));
1303
1390
  if (sessionId !== undefined && (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, 'Invalid session id');
1304
1391
  if (history !== 'replay' && history !== 'skip') throw new RpcError(-32602, 'history must be replay or skip');
@@ -1430,6 +1517,9 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1430
1517
  for (const envelope of live) if ((envelope.cursor ?? 0) > last) { if (current(envelope)) deliver(connection, envelope); last = envelope.cursor ?? last; }
1431
1518
  }
1432
1519
  announceQuestions(connection, root);
1520
+ // Gate cards are rebuilt from the project's tasks: one changed while nobody watched shows or settles now.
1521
+ const gateProject = runtime.snapshot(root)?.projectRoot;
1522
+ if (gateProject) void runtime.syncGates?.(gateProject)?.catch(() => {});
1433
1523
  return { session: root === found.id ? found : summary(root), cursor: tip, ...(reset ? { reset: true } : {}) };
1434
1524
  }
1435
1525
  },
@@ -1502,6 +1592,14 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1502
1592
  return conversation.reload(params);
1503
1593
  },
1504
1594
 
1595
+ /** Compacts a live root's context now or at its next turn boundary (t-0e56). */
1596
+ async 'session.compact'(_connection, { sessionId }) {
1597
+ if (typeof sessionId !== 'string' || !sessionId) throw new RpcError(-32602, 'sessionId is required');
1598
+ if (!runtime.compact) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not compact sessions');
1599
+ try { return runtime.compact(sessionId); }
1600
+ catch (error) { throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error)); }
1601
+ },
1602
+
1505
1603
  /** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
1506
1604
  async 'session.resumeCommand'(_connection, { sessionId }) {
1507
1605
  if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd has no resume command (capability session.resumeCommand is not listed)');
@@ -1582,16 +1680,41 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1582
1680
  * a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
1583
1681
  */
1584
1682
  '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;
1683
+ const cache = new Map<string, string>();
1684
+ const keyOf = (root: string) => {
1685
+ let key = cache.get(root);
1686
+ if (key === undefined) {
1687
+ key = projectKey(root);
1688
+ cache.set(root, key);
1689
+ }
1690
+ return key;
1691
+ };
1692
+ // Projects are matched by their canonical identity (projectKey), so sessions created
1693
+ // under a symlink (or /var -> /private/var on macOS) are listed when queried by their
1694
+ // canonical path, and vice versa.
1695
+ const wantedKey = projectRoot === undefined ? undefined : keyOf(projectRoot);
1696
+ const allowedKeys = Array.isArray(projectRoots) ? new Set<string>(projectRoots.map(keyOf)) : undefined;
1586
1697
  const after = cursor === undefined ? undefined : listCursor.decode(cursor);
1587
1698
  const words = typeof query === 'string' ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
1588
- const ids = new Set([...runtime.list().map(session => session.id), ...records.keys()]);
1699
+ const live = runtime.list();
1700
+ const liveChildren = rootsOnly ? new Set(live.filter(session => !!session.parentId).map(session => session.id)) : undefined;
1701
+ const ids = new Set<string>();
1702
+ for (const session of live) {
1703
+ if (!rootsOnly || !session.parentId) ids.add(session.id);
1704
+ }
1705
+ for (const [id, record] of records) {
1706
+ if (!rootsOnly) {
1707
+ ids.add(id);
1708
+ } else if (record.id === record.rootId && !record.session?.parentId && !liveChildren!.has(id)) {
1709
+ ids.add(id);
1710
+ }
1711
+ }
1589
1712
  const sessions = [...ids].map(summary).filter((session): session is SessionSummary => !!session)
1590
1713
  .filter(session => includeClosed || session.status === 'idle' || session.status === 'running')
1591
1714
  .filter(session => includeArchived || !session.archived)
1592
1715
  .filter(session => !rootsOnly || !session.parentId)
1593
- .filter(session => projectRoot === undefined || session.projectRoot === projectRoot)
1594
- .filter(session => !projects || projects.has(session.projectRoot))
1716
+ .filter(session => wantedKey === undefined || keyOf(session.projectRoot) === wantedKey)
1717
+ .filter(session => !allowedKeys || allowedKeys.has(keyOf(session.projectRoot)))
1595
1718
  .filter(session => !words.length || words.every(word => `${session.title ?? ''}\n${session.id}`.toLowerCase().includes(word)))
1596
1719
  .sort((a, b) => listCursor.compare(listCursor.key(a), listCursor.key(b)))
1597
1720
  .filter(session => !after || listCursor.compare(listCursor.key(session), after) > 0);
@@ -1606,11 +1729,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1606
1729
  * the project; a session that is closed when the job is due fails the job, and the
1607
1730
  * reason is kept.
1608
1731
  */
1609
- async 'schedule.create'(_connection, { projectRoot, sessionId, dueAt, prompt } = {}) {
1732
+ async 'schedule.create'(_connection, { projectRoot, sessionId, dueAt, prompt, keepsSession } = {}) {
1610
1733
  if (!schedules) throw new RpcError(ERROR.failed, 'alpd does not serve scheduled jobs');
1611
1734
  if (typeof projectRoot !== 'string' || typeof sessionId !== 'string' || typeof dueAt !== 'string' || typeof prompt !== 'string') {
1612
1735
  throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot, sessionId, dueAt and prompt are required');
1613
1736
  }
1737
+ if (keepsSession !== undefined && typeof keepsSession !== 'boolean') throw new RpcError(RPC_ERROR.invalidParams, 'keepsSession must be true or false');
1614
1738
  if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, 'projectRoot must be an absolute path');
1615
1739
  const snapshot = runtime.snapshot(sessionId);
1616
1740
  if (!snapshot) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not open`);
@@ -1623,7 +1747,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1623
1747
  // in between; the job's own hold takes over once it exists.
1624
1748
  scheduler?.holdSession(sessionId);
1625
1749
  try {
1626
- const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt });
1750
+ const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt, keepsSession });
1627
1751
  scheduler?.hold(job);
1628
1752
  return { job };
1629
1753
  } catch (error) {
@@ -1706,7 +1830,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1706
1830
  return result.workspace ? { ...result, workspace: await workspaceDescriptor(result.workspace) } : result;
1707
1831
  });
1708
1832
  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);
1833
+ for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (connection, params) => handler(params, { agent: connection.agent === true });
1710
1834
  Object.setPrototypeOf(handlers, null);
1711
1835
  // Every v1 method name stays the daemon's, served here or not, so no extension takes one.
1712
1836
  const originalMethods = new Set([...Object.keys(handlers), ...RPC_METHODS]);
@@ -1764,7 +1888,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1764
1888
  }
1765
1889
 
1766
1890
  /** 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];
1891
+ 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
1892
 
1769
1893
  /** A response too large for the wire becomes an error the client can read. */
1770
1894
  function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
@@ -1815,9 +1939,12 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1815
1939
  const issues = validateParams(method, params)!;
1816
1940
  if (issues.length) throw invalidParams(issues);
1817
1941
  connection.helloed = true;
1942
+ // Sticky: a later hello never sheds it.
1943
+ connection.agent = connection.agent === true || (Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY));
1944
+ if (typeof params?.client?.name === 'string') connection.client = params.client.name;
1818
1945
  // Terminals are listed only while the host's switch is on (and the PTY module loads).
1819
1946
  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 } : {}) } });
1947
+ 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
1948
  return;
1822
1949
  }
1823
1950
  if (!connection.helloed) throw new RpcError(ERROR.protocol, 'daemon.hello is required first', { reason: 'hello_required' });
@@ -2034,9 +2161,10 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
2034
2161
  },
2035
2162
 
2036
2163
  async close() {
2164
+ unsubscribeCatalog?.();
2037
2165
  closing = true;
2038
2166
  if (sweeper) clearInterval(sweeper);
2039
- attachments?.close();
2167
+ await attachments?.close();
2040
2168
  // Every terminal ends with alpd, its whole process tree killed.
2041
2169
  await terminals?.shutdown();
2042
2170
  // 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); });
@@ -0,0 +1,74 @@
1
+ import headless from '@xterm/headless';
2
+ import { ERROR } from '@anhlp/alp-protocol';
3
+ import { RpcError } from './rpc-error.js';
4
+
5
+ // Exact xterm 6.0.0, also used by Paseo 0.12. No raw replay reconstruction: one parser from spawn.
6
+ // Bound both queued work and lifetime input (including OSC/combining payloads hidden from rows).
7
+ export const SCREEN_LIMITS = Object.freeze({ scrollback: 1000, pendingBytes: 1024 * 1024, pendingOperations: 256, inputBytes: 8 * 1024 * 1024, resultBytes: 1024 * 1024, retained: 16 });
8
+ export class TerminalScreen {
9
+ #term: InstanceType<typeof headless.Terminal> | undefined;
10
+ #pending = 0;
11
+ #input = 0;
12
+ #operations = 0;
13
+ #waiters = new Set<() => void>();
14
+ constructor(cols: number, rows: number) {
15
+ this.#term = new headless.Terminal({ cols, rows, scrollback: SCREEN_LIMITS.scrollback, allowProposedApi: true, logLevel: 'off' });
16
+ }
17
+ get available() { return this.#term !== undefined; }
18
+ #unavailable() { return new RpcError(ERROR.unavailable, 'Terminal capture is unavailable: its bounded screen was released or exceeded its resource limit', { reason: 'terminal_capture_unavailable' }); }
19
+ #queue(term: InstanceType<typeof headless.Terminal>, data: string, callback: () => void) {
20
+ if (this.#operations >= SCREEN_LIMITS.pendingOperations) { this.dispose(); return; }
21
+ this.#operations++;
22
+ try {
23
+ term.write(data, () => { this.#operations--; callback(); });
24
+ } catch { this.#operations--; this.dispose(); }
25
+ }
26
+ write(data: string) {
27
+ const term = this.#term;
28
+ if (!term) return;
29
+ const bytes = Buffer.byteLength(data);
30
+ this.#input += bytes;
31
+ if (this.#input > SCREEN_LIMITS.inputBytes || this.#pending + bytes > SCREEN_LIMITS.pendingBytes) { this.dispose(); return; }
32
+ this.#pending += bytes;
33
+ this.#queue(term, data, () => { this.#pending -= bytes; });
34
+ }
35
+ resize(cols: number, rows: number) {
36
+ const term = this.#term;
37
+ // Keep resize between the old output and output caused by the new PTY size.
38
+ if (term) this.#queue(term, '', () => { if (this.#term === term) term.resize(cols, rows); });
39
+ }
40
+ capture(options: { start?: number; end?: number; stripAnsi?: boolean } = {}): Promise<{ lines: string[]; totalLines: number }> {
41
+ const term = this.#term;
42
+ if (!term) return Promise.reject(this.#unavailable());
43
+ return new Promise((resolve, reject) => {
44
+ const released = () => reject(this.#unavailable());
45
+ this.#waiters.add(released);
46
+ // The callback is a parser barrier, not a delay or a ring-buffer approximation.
47
+ this.#queue(term, '', () => {
48
+ this.#waiters.delete(released);
49
+ if (this.#term !== term) { reject(this.#unavailable()); return; }
50
+ const buffer = term.buffer.active;
51
+ const totalLines = buffer.length;
52
+ const index = (value: number | undefined, fallback: number) => value === undefined ? fallback : Math.max(0, Math.min(totalLines - 1, value < 0 ? totalLines + value : value));
53
+ const start = index(options.start, 0);
54
+ const end = index(options.end, totalLines - 1);
55
+ const lines: string[] = [];
56
+ let bytes = 0;
57
+ for (let i = start; i <= end; i++) {
58
+ // Cell text, like Paseo: styling escapes are not regenerated when stripAnsi=false.
59
+ const line = buffer.getLine(i)?.translateToString(true).trimEnd() ?? '';
60
+ bytes += Buffer.byteLength(JSON.stringify(line)) + 1;
61
+ if (bytes > SCREEN_LIMITS.resultBytes - 128) { reject(new RpcError(ERROR.unavailable, 'Terminal capture exceeds the response limit; select a smaller line range', { reason: 'terminal_capture_too_large' })); return; }
62
+ lines.push(line);
63
+ }
64
+ resolve({ lines, totalLines });
65
+ });
66
+ });
67
+ }
68
+ dispose() {
69
+ this.#term?.dispose();
70
+ this.#term = undefined;
71
+ for (const waiter of this.#waiters) waiter();
72
+ this.#waiters.clear();
73
+ }
74
+ }