@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/dist/server.js CHANGED
@@ -16,7 +16,7 @@ import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
16
16
  import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
17
17
  import { RpcError } from "./rpc-error.js";
18
18
  import { createOperations } from "./operations.js";
19
- import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from "./files.js";
19
+ import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, searchWorkspaceFiles } from "./files.js";
20
20
  import { createGitReader } from "./git.js";
21
21
  import { createScheduleStore, projectKey } from "./schedules.js";
22
22
  import { createAttachmentStore } from "./attachments.js";
@@ -68,6 +68,11 @@ function digest(value) {
68
68
  return createHash("sha256").update(JSON.stringify(value, (_key, candidate) => candidate !== null && typeof candidate === "object" && !Array.isArray(candidate) ? Object.fromEntries(Object.entries(candidate).sort(([a], [b]) => a.localeCompare(b))) : candidate)).digest("hex");
69
69
  }
70
70
  var TREE_LOG_LIMIT = 2e4;
71
+ var AGENT_CAPABILITY = "principal.agent";
72
+ var agentRefused = (connection, method) => {
73
+ if (connection.agent) throw new RpcError(ERROR.forbidden, `${method} is the user's; this connection was opened by an ALP agent`, { reason: "user_only" });
74
+ return void 0;
75
+ };
71
76
  var SESSION_ID = /^[\w.:-]{1,128}$/;
72
77
  var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
73
78
  var RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -100,8 +105,26 @@ var listCursor = {
100
105
  return key;
101
106
  }
102
107
  };
103
- function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions }) {
108
+ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates, scheduleTickMs = SCHEDULE_TICK_MS, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions, modelCatalog }) {
104
109
  const connections = /* @__PURE__ */ new Set();
110
+ const catalogResult = () => {
111
+ const state = modelCatalog?.state();
112
+ return {
113
+ models,
114
+ modes,
115
+ thinkingOptions,
116
+ defaultModel: `codex:${DEFAULT_MODEL}`,
117
+ ...state ? { fetchedAt: state.fetchedAt, providers: Object.fromEntries(Object.entries(state.providers).map(([runtime2, provider]) => [runtime2, { status: provider.status, fetchedAt: provider.fetchedAt, ...provider.error ? { error: provider.error } : {} }])) } : {}
118
+ };
119
+ };
120
+ const unsubscribeCatalog = modelCatalog?.onUpdated((snapshot) => {
121
+ for (const connection of connections) if (connection.helloed) {
122
+ try {
123
+ connection.send({ jsonrpc: "2.0", method: "catalog.updated", params: { fetchedAt: snapshot.fetchedAt } });
124
+ } catch {
125
+ }
126
+ }
127
+ });
105
128
  const rootOf = /* @__PURE__ */ new Map();
106
129
  const attached = /* @__PURE__ */ new Map();
107
130
  const logs = /* @__PURE__ */ new Map();
@@ -247,6 +270,10 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
247
270
  function projectOf(root) {
248
271
  return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
249
272
  }
273
+ const sameProject = (a, b) => {
274
+ if (a === void 0 || b === void 0) return a === b;
275
+ return a === b || projectKey(a) === projectKey(b);
276
+ };
250
277
  function tellWatchers(root, envelope, turn = false) {
251
278
  if (!watchers.size) return;
252
279
  const { cursor: _cursor, ...announced } = envelope;
@@ -254,7 +281,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
254
281
  for (const [connection, { projectRoot, turns }] of watchers) {
255
282
  if (turn && !turns) continue;
256
283
  if (attached.get(root)?.has(connection)) continue;
257
- if (projectRoot !== void 0 && project !== projectRoot) continue;
284
+ if (projectRoot !== void 0 && !sameProject(project, projectRoot)) continue;
258
285
  deliver(connection, announced);
259
286
  }
260
287
  }
@@ -264,7 +291,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
264
291
  const envelope = { sessionId: root, epoch: `attention-${startedAt}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "attention", ...attention ? { attention } : {} } };
265
292
  for (const [connection, watch] of watchers) {
266
293
  if (!watch.attention) continue;
267
- if (watch.projectRoot !== void 0 && project !== watch.projectRoot) continue;
294
+ if (watch.projectRoot !== void 0 && !sameProject(project, watch.projectRoot)) continue;
268
295
  deliver(connection, envelope);
269
296
  }
270
297
  }
@@ -273,7 +300,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
273
300
  const found = [];
274
301
  for (const record of records.values()) {
275
302
  if (record.id !== record.rootId || !record.attention || record.archived) continue;
276
- if (projectRoot !== void 0 && projectOf(record.id) !== projectRoot) continue;
303
+ if (projectRoot !== void 0 && !sameProject(projectOf(record.id), projectRoot)) continue;
277
304
  found.push({ sessionId: record.id, attention: record.attention });
278
305
  }
279
306
  return found;
@@ -472,8 +499,10 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
472
499
  if (removed.size) recoveryLog.info(`retention removed ${removed.size} session tree${removed.size > 1 ? "s" : ""} unused for ${RETENTION_MS / 864e5} days`, { code: "ALP_RETENTION_REMOVED", trees: removed.size });
473
500
  return removed;
474
501
  }
502
+ let sweeping = false;
475
503
  async function sweep() {
476
- if (closing || !store) return;
504
+ if (closing || !store || sweeping) return;
505
+ sweeping = true;
477
506
  try {
478
507
  await restored;
479
508
  await store.pruneReceipts(RECEIPT_RETENTION_MS, { temporaries: false });
@@ -481,6 +510,8 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
481
510
  await expire(trees(records.values()));
482
511
  } catch (error) {
483
512
  recoveryLog.warn("retention sweep failed", { code: "ALP_RETENTION_FAILED", error });
513
+ } finally {
514
+ sweeping = false;
484
515
  }
485
516
  }
486
517
  const sweeper = store ? setInterval(() => void sweep(), retentionSweepMs) : void 0;
@@ -764,20 +795,35 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
764
795
  }
765
796
  }
766
797
  const registry = home ? createRegistry(home) : void 0;
767
- const worktrees = home && registry && process.platform !== "win32" ? createWorkspaceWorktrees(home, registry, async (directory, run) => {
768
- if (!runtime.withWorkspaceMutation) throw new RegistryError(1005, "Runtime cannot prove safe worktree removal", { reason: "guard_unavailable" });
769
- try {
770
- return await runtime.withWorkspaceMutation(directory, run);
771
- } catch (error) {
772
- if (error?.data?.reason) throw new RegistryError(1004, "Workspace is in use or has retained assignment results", error.data);
773
- throw error;
774
- }
775
- }, async (directory) => {
776
- if (!runtime.registerWorkspace) throw new RegistryError(1005, "Runtime cannot register safe workspace ownership", { reason: "guard_unavailable" });
777
- await runtime.registerWorkspace(directory);
778
- }) : void 0;
798
+ const worktrees = home && registry && process.platform !== "win32" ? createWorkspaceWorktrees(
799
+ home,
800
+ registry,
801
+ async (directory, run) => {
802
+ if (!runtime.withWorkspaceMutation) throw new RegistryError(1005, "Runtime cannot prove safe worktree removal", { reason: "guard_unavailable" });
803
+ try {
804
+ return await runtime.withWorkspaceMutation(directory, run);
805
+ } catch (error) {
806
+ if (error?.data?.reason) throw new RegistryError(1004, "Workspace is in use or has retained assignment results", error.data);
807
+ throw error;
808
+ }
809
+ },
810
+ async (directory) => {
811
+ if (!runtime.registerWorkspace) throw new RegistryError(1005, "Runtime cannot register safe workspace ownership", { reason: "guard_unavailable" });
812
+ await runtime.registerWorkspace(directory);
813
+ },
814
+ // Owner-audited adoption (t-c1ba); no RPC exposes it yet, so the default stays refusal.
815
+ runtime.adoptWorkspace ? async (directory, verify) => {
816
+ try {
817
+ await runtime.adoptWorkspace(directory, verify);
818
+ } catch (error) {
819
+ if (error?.data?.reason && !(error instanceof RegistryError)) throw new RegistryError(1004, "Workspace is in use, has retained assignment results or changed identity", error.data);
820
+ throw error;
821
+ }
822
+ } : void 0
823
+ ) : void 0;
779
824
  const workspaceDescriptor = async (w) => worktrees ? worktrees.describe(w) : w;
780
825
  const gitReader = registry ? createGitReader({ registry, log: (message, fields) => log.warn(message, { code: "ALPD_GIT_READ_FAILED", ...fields }) }) : void 0;
826
+ const gitFacts = createGitReader({ log: (message, fields) => log.warn(message, { code: "ALPD_GIT_READ_FAILED", ...fields }) });
781
827
  const terminals = home && registry ? createTerminalService({
782
828
  home,
783
829
  resolveWorkspace: (workspaceId) => registry.resolve(workspaceId),
@@ -788,16 +834,23 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
788
834
  if (!terminals) throw new RpcError(ERROR.unavailable, "This alpd has no home: it serves no terminals", { reason: "terminal_unsupported" });
789
835
  return run(terminals);
790
836
  };
791
- const attachmentCall = (run) => {
837
+ const attachmentCall = async (run) => {
792
838
  if (!attachments) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not store attachments (capability attachments is not listed)");
793
- return run(attachments);
839
+ try {
840
+ return await run(attachments);
841
+ } catch (error) {
842
+ if (error instanceof RpcError) throw error;
843
+ log.warn("attachment call failed", { code: "ALPD_ATTACHMENT_FAILED", error });
844
+ throw new RpcError(ERROR.failed, "alpd could not store the attachment; the upload was aborted", { reason: "persistence_failed" });
845
+ }
794
846
  };
795
847
  const gitCall = (run) => {
796
848
  if (!gitReader) throw new RpcError(ERROR.unavailable, "Registry needs ALP_HOME");
797
849
  return run(gitReader);
798
850
  };
799
- const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])) });
851
+ const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])), onGateChange: (root) => runtime.syncGates?.(root) });
800
852
  const extensionOwners = /* @__PURE__ */ new Map();
853
+ const findPages = createFindPages();
801
854
  const handlers = {
802
855
  "extension.register": async (connection, params) => {
803
856
  const method = params?.method;
@@ -857,7 +910,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
857
910
  return { rootId: root, entries };
858
911
  },
859
912
  "question.list"(_connection, { projectRoot } = {}) {
860
- return { questions: runtime.questions().filter((question) => projectRoot === void 0 || projectOf(question.rootId) === projectRoot) };
913
+ return { questions: runtime.questions().filter((question) => projectRoot === void 0 || sameProject(projectOf(question.rootId), projectRoot)) };
861
914
  },
862
915
  /**
863
916
  * The questions waiting now; from then on this connection is told of `question` and
@@ -869,7 +922,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
869
922
  "question.watch"(connection, { projectRoot, turns, attention } = {}) {
870
923
  watchers.set(connection, { projectRoot, turns: turns === true, attention: attention === true });
871
924
  return {
872
- questions: runtime.questions().filter((question) => projectRoot === void 0 || projectOf(question.rootId) === projectRoot),
925
+ questions: runtime.questions().filter((question) => projectRoot === void 0 || sameProject(projectOf(question.rootId), projectRoot)),
873
926
  ...attention === true ? { attention: attentionOf(projectRoot) } : {}
874
927
  };
875
928
  },
@@ -918,12 +971,27 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
918
971
  * read-only, confined to it, no link followed, blocked paths always refused, .gitignore'd ones
919
972
  * unless includeIgnored (docs/protocol/alp-json-rpc-v1.md §12.4, ALPD §15).
920
973
  */
921
- async "workspace.files.list"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
922
- return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
974
+ async "workspace.files.list"(_connection, { projectRoot, path: relative, includeIgnored, cursor, internalLinks } = {}) {
975
+ return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true, cursor, internalLinks: internalLinks === true }));
923
976
  },
924
977
  async "workspace.files.read"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
925
978
  return filesCall(projectRoot, () => readWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
926
979
  },
980
+ /**
981
+ * Every name under projectRoot in pages of a snapshot kept for this connection, and a file's
982
+ * preview in chunks (docs/protocol/alp-json-rpc-v1.md §12.11): what the Paseo bridge's Files
983
+ * panel and suggestions read, confined as workspace.files.read is. The gateway exposes neither.
984
+ */
985
+ async "workspace.files.find"(connection, { projectRoot, query, kinds, matchMode, limit, cursor } = {}) {
986
+ return filesCall(projectRoot, () => findPages(connection, projectRoot, { query, kinds, matchMode, limit, cursor }));
987
+ },
988
+ async "workspace.files.preview"(_connection, { projectRoot, path: relative, includeIgnored, internalLinks, maxBytes, offset, revision } = {}) {
989
+ return filesCall(projectRoot, () => previewWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true, internalLinks: internalLinks === true, maxBytes, offset, revision }));
990
+ },
991
+ /** The host's directories for the folder to add as a project (§12.11): the owner's own names, never remote. */
992
+ async "host.directories.search"(_connection, { query, limit } = {}) {
993
+ return searchHostDirectories(query, { limit });
994
+ },
927
995
  /** The project board: live claims, decisions and findings (ALPD §18). */
928
996
  async "board.list"(_connection, { projectRoot } = {}) {
929
997
  if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new RpcError(-32602, "An absolute projectRoot is required");
@@ -957,12 +1025,14 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
957
1025
  throw new RpcError(ERROR.failed, error?.message ?? String(error));
958
1026
  }
959
1027
  },
960
- "question.answer"(_connection, { questionId, text, dismiss = false, reason }) {
1028
+ "question.answer"(connection, { questionId, text, dismiss = false, reason }) {
1029
+ 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" });
961
1030
  if (typeof questionId !== "string") throw new RpcError(-32602, "questionId is required");
962
1031
  if (dismiss !== true && typeof text !== "string") throw new RpcError(-32602, "text or dismiss is required");
963
1032
  const matches = runtime.questions().filter((question) => question.id === questionId || question.id.startsWith(questionId));
964
1033
  if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
965
- runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason } : { text });
1034
+ const channel = connection.client?.startsWith("alp-paseo") ? "paseo" : "web";
1035
+ runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
966
1036
  return { questionId: matches[0].id };
967
1037
  },
968
1038
  "daemon.shutdown": () => {
@@ -974,23 +1044,26 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
974
1044
  const { receipts: _receipts, ...metadata } = await registry.snapshot();
975
1045
  return { ...result ? { result } : {}, registry: metadata };
976
1046
  }),
977
- "registry.worktree": (_c, p) => registryCall(() => worktrees.grants(p)),
1047
+ "registry.worktree": (_c, p) => registryCall(async () => worktrees ? worktrees.grants(p) : { mappings: [], workspaces: [] }),
978
1048
  "workspace.worktree.options": (_c, p) => registryCall(async () => {
979
1049
  const w = (await registry.snapshot()).workspaces.find((w2) => w2.id === p.workspaceId);
980
1050
  if (!w) throw new RegistryError(1001, "No workspace", { reason: "not_found" });
981
- const grants = await worktrees.grants(p);
1051
+ const grants = worktrees ? await worktrees.grants(p) : { mappings: [], workspaces: [] };
982
1052
  return { mappingIds: grants.mappings.filter((m) => m.source === (w.canonical ?? w.directory)).map((m) => m.id) };
983
1053
  }),
984
1054
  "workspace.worktree.create": (_c, p) => registryCall(async () => {
1055
+ if (!worktrees) throw new RegistryError(1005, "Worktrees are unavailable on this platform", { reason: "worktrees_unsupported" });
985
1056
  const result = await worktrees.mutate("create", p, p);
986
1057
  return { ...result, workspace: await workspaceDescriptor(result.workspace) };
987
1058
  }),
988
1059
  "workspace.worktree.remove": (_c, p) => registryCall(async () => {
1060
+ if (!worktrees) throw new RegistryError(1005, "Worktrees are unavailable on this platform", { reason: "worktrees_unsupported" });
989
1061
  const result = await worktrees.mutate("remove", p, p);
990
1062
  return { ...result, workspace: await workspaceDescriptor(result.workspace) };
991
1063
  }),
992
1064
  "workspace.git.status": (_c, p) => gitCall((reader) => reader.status(p.workspaceId)),
993
1065
  "workspace.git.diff": (_c, p) => gitCall((reader) => reader.diff({ workspaceId: p.workspaceId, compare: p.compare, path: p.path, cursor: p.cursor })),
1066
+ "workspace.git.facts": (c, p) => agentRefused(c, "workspace.git.facts") ?? gitFacts.facts(p.directory),
994
1067
  "project.list": (_c, p) => registryList("projects", p),
995
1068
  "workspace.list": (_c, p) => registryList("workspaces", p),
996
1069
  "workspace.get": (_c, p) => registryCall(async () => {
@@ -1001,15 +1074,23 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
1001
1074
  "project.register": (_c, p) => registryMutation("project.register", p),
1002
1075
  "project.remove": (_c, p) => registryMutation("project.remove", p),
1003
1076
  "workspace.update": (_c, p) => registryMutation("workspace.update", p),
1004
- "catalog.get": () => ({ models, modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}` }),
1077
+ "catalog.get": () => catalogResult(),
1078
+ "catalog.refresh": async () => {
1079
+ if (!modelCatalog) throw new RpcError(ERROR.unavailable, "The live model catalog is not available");
1080
+ await modelCatalog.refresh();
1081
+ return catalogResult();
1082
+ },
1005
1083
  // attachment.* (§12.6): each call acts for its principal context; without the store (no home or
1006
1084
  // store, or Windows) alpd does not serve them, as for any method it does not know.
1007
1085
  // terminal.* (§12.10): each call acts for its principal context; input, resize and the stream
1008
1086
  // belong to the connection that attached the terminal.
1009
- "terminal.create": (_c, p) => terminalCall((service) => service.create(principalOf(p), p)),
1087
+ "terminal.create": (c, p) => agentRefused(c, "terminal.create") ?? terminalCall((service) => service.create(principalOf(p), p)),
1088
+ "terminal.watch": (c, p) => terminalCall((service) => service.watch(principalOf(p), c, p)),
1089
+ "terminal.unwatch": (c) => terminalCall((service) => service.unwatch(c)),
1090
+ "terminal.capture": (_c, p) => terminalCall((service) => service.capture(principalOf(p), p)),
1010
1091
  "terminal.list": (_c, p) => terminalCall((service) => service.list(principalOf(p), p)),
1011
- "terminal.attach": (c, p) => terminalCall((service) => service.attach(principalOf(p), c, p)),
1012
- "terminal.input": (c, p) => terminalCall((service) => service.input(principalOf(p), c, p)),
1092
+ "terminal.attach": (c, p) => agentRefused(c, "terminal.attach") ?? terminalCall((service) => service.attach(principalOf(p), c, p)),
1093
+ "terminal.input": (c, p) => agentRefused(c, "terminal.input") ?? terminalCall((service) => service.input(principalOf(p), c, p)),
1013
1094
  "terminal.resize": (c, p) => terminalCall((service) => service.resize(principalOf(p), c, p)),
1014
1095
  "terminal.close": (_c, p) => terminalCall((service) => service.close(principalOf(p), p)),
1015
1096
  "terminal.revoke": (_c, p) => terminalCall((service) => service.revoke(p.principalId)),
@@ -1033,6 +1114,10 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
1033
1114
  if (prior && prior !== workspaceId) throw new RpcError(ERROR.conflict, "Session belongs to another workspace", { reason: "workspace_mismatch" });
1034
1115
  }
1035
1116
  if (!spec || typeof spec !== "object" || typeof spec.cwd !== "string") throw new RpcError(-32602, "spec.cwd is required");
1117
+ if (connection.agent && spec.restore !== void 0) {
1118
+ const { restore: _restore2, ...owned } = spec;
1119
+ spec = owned;
1120
+ }
1036
1121
  if (worktrees) await registryCall(() => worktrees.assertAvailable(spec.cwd));
1037
1122
  if (sessionId !== void 0 && (typeof sessionId !== "string" || !SESSION_ID.test(sessionId))) throw new RpcError(-32602, "Invalid session id");
1038
1123
  if (history !== "replay" && history !== "skip") throw new RpcError(-32602, "history must be replay or skip");
@@ -1165,6 +1250,9 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
1165
1250
  }
1166
1251
  }
1167
1252
  announceQuestions(connection, root);
1253
+ const gateProject = runtime.snapshot(root)?.projectRoot;
1254
+ if (gateProject) void runtime.syncGates?.(gateProject)?.catch(() => {
1255
+ });
1168
1256
  return { session: root === found.id ? found : summary(root), cursor: tip, ...reset ? { reset: true } : {} };
1169
1257
  }
1170
1258
  },
@@ -1226,6 +1314,16 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
1226
1314
  if (!conversation?.reloads) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not reload sessions (capability session.reload is not listed)");
1227
1315
  return conversation.reload(params);
1228
1316
  },
1317
+ /** Compacts a live root's context now or at its next turn boundary (t-0e56). */
1318
+ async "session.compact"(_connection, { sessionId }) {
1319
+ if (typeof sessionId !== "string" || !sessionId) throw new RpcError(-32602, "sessionId is required");
1320
+ if (!runtime.compact) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not compact sessions");
1321
+ try {
1322
+ return runtime.compact(sessionId);
1323
+ } catch (error) {
1324
+ throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error));
1325
+ }
1326
+ },
1229
1327
  /** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
1230
1328
  async "session.resumeCommand"(_connection, { sessionId }) {
1231
1329
  if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd has no resume command (capability session.resumeCommand is not listed)");
@@ -1304,11 +1402,33 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
1304
1402
  * a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
1305
1403
  */
1306
1404
  "session.list"(_connection, { projectRoot, projectRoots, rootsOnly = false, includeClosed = false, includeArchived = false, limit, cursor, query } = {}) {
1307
- const projects = Array.isArray(projectRoots) ? new Set(projectRoots) : void 0;
1405
+ const cache = /* @__PURE__ */ new Map();
1406
+ const keyOf = (root) => {
1407
+ let key = cache.get(root);
1408
+ if (key === void 0) {
1409
+ key = projectKey(root);
1410
+ cache.set(root, key);
1411
+ }
1412
+ return key;
1413
+ };
1414
+ const wantedKey = projectRoot === void 0 ? void 0 : keyOf(projectRoot);
1415
+ const allowedKeys = Array.isArray(projectRoots) ? new Set(projectRoots.map(keyOf)) : void 0;
1308
1416
  const after = cursor === void 0 ? void 0 : listCursor.decode(cursor);
1309
1417
  const words = typeof query === "string" ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
1310
- const ids = /* @__PURE__ */ new Set([...runtime.list().map((session) => session.id), ...records.keys()]);
1311
- const sessions = [...ids].map(summary).filter((session) => !!session).filter((session) => includeClosed || session.status === "idle" || session.status === "running").filter((session) => includeArchived || !session.archived).filter((session) => !rootsOnly || !session.parentId).filter((session) => projectRoot === void 0 || session.projectRoot === projectRoot).filter((session) => !projects || projects.has(session.projectRoot)).filter((session) => !words.length || words.every((word) => `${session.title ?? ""}
1418
+ const live2 = runtime.list();
1419
+ const liveChildren = rootsOnly ? new Set(live2.filter((session) => !!session.parentId).map((session) => session.id)) : void 0;
1420
+ const ids = /* @__PURE__ */ new Set();
1421
+ for (const session of live2) {
1422
+ if (!rootsOnly || !session.parentId) ids.add(session.id);
1423
+ }
1424
+ for (const [id, record] of records) {
1425
+ if (!rootsOnly) {
1426
+ ids.add(id);
1427
+ } else if (record.id === record.rootId && !record.session?.parentId && !liveChildren.has(id)) {
1428
+ ids.add(id);
1429
+ }
1430
+ }
1431
+ const sessions = [...ids].map(summary).filter((session) => !!session).filter((session) => includeClosed || session.status === "idle" || session.status === "running").filter((session) => includeArchived || !session.archived).filter((session) => !rootsOnly || !session.parentId).filter((session) => wantedKey === void 0 || keyOf(session.projectRoot) === wantedKey).filter((session) => !allowedKeys || allowedKeys.has(keyOf(session.projectRoot))).filter((session) => !words.length || words.every((word) => `${session.title ?? ""}
1312
1432
  ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(listCursor.key(a), listCursor.key(b))).filter((session) => !after || listCursor.compare(listCursor.key(session), after) > 0);
1313
1433
  if (limit === void 0 || sessions.length <= limit) return { sessions };
1314
1434
  const page = sessions.slice(0, limit);
@@ -1320,11 +1440,12 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1320
1440
  * the project; a session that is closed when the job is due fails the job, and the
1321
1441
  * reason is kept.
1322
1442
  */
1323
- async "schedule.create"(_connection, { projectRoot, sessionId, dueAt, prompt } = {}) {
1443
+ async "schedule.create"(_connection, { projectRoot, sessionId, dueAt, prompt, keepsSession } = {}) {
1324
1444
  if (!schedules) throw new RpcError(ERROR.failed, "alpd does not serve scheduled jobs");
1325
1445
  if (typeof projectRoot !== "string" || typeof sessionId !== "string" || typeof dueAt !== "string" || typeof prompt !== "string") {
1326
1446
  throw new RpcError(RPC_ERROR.invalidParams, "projectRoot, sessionId, dueAt and prompt are required");
1327
1447
  }
1448
+ if (keepsSession !== void 0 && typeof keepsSession !== "boolean") throw new RpcError(RPC_ERROR.invalidParams, "keepsSession must be true or false");
1328
1449
  if (!path.isAbsolute(projectRoot)) throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute path");
1329
1450
  const snapshot = runtime.snapshot(sessionId);
1330
1451
  if (!snapshot) throw new RpcError(ERROR.notFound, `Session ${sessionId} is not open`);
@@ -1333,7 +1454,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1333
1454
  if (!snapshot.persistent || !snapshot.threadId) log.warn(`a job on ${sessionId} cannot survive a restart of alpd: the session keeps no thread to resume`, { code: "ALP_SCHEDULE_SESSION_NOT_RESUMABLE", sessionId });
1334
1455
  scheduler?.holdSession(sessionId);
1335
1456
  try {
1336
- const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt });
1457
+ const job = await schedules.create({ projectRoot, sessionId, dueAt, prompt, keepsSession });
1337
1458
  scheduler?.hold(job);
1338
1459
  return { job };
1339
1460
  } catch (error) {
@@ -1411,7 +1532,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1411
1532
  return result.workspace ? { ...result, workspace: await workspaceDescriptor(result.workspace) } : result;
1412
1533
  });
1413
1534
  runtime.bindSchedules?.(async (action, params) => handlers[`schedule.${action}`](void 0, params));
1414
- for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
1535
+ for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (connection, params) => handler(params, { agent: connection.agent === true });
1415
1536
  Object.setPrototypeOf(handlers, null);
1416
1537
  const originalMethods = /* @__PURE__ */ new Set([...Object.keys(handlers), ...RPC_METHODS]);
1417
1538
  const reservedNamespaces = new Set([...originalMethods].map((method) => method.split(".")[0]));
@@ -1458,7 +1579,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1458
1579
  throw new RpcError(ERROR.failed, "alpd could not read the workspace file");
1459
1580
  }
1460
1581
  }
1461
- 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];
1582
+ 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];
1462
1583
  function fits(response) {
1463
1584
  if (frameBytes(response) <= MAX_FRAME) return response;
1464
1585
  log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
@@ -1501,8 +1622,10 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1501
1622
  const issues2 = validateParams(method, params);
1502
1623
  if (issues2.length) throw invalidParams(issues2);
1503
1624
  connection.helloed = true;
1625
+ connection.agent = connection.agent === true || Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY);
1626
+ if (typeof params?.client?.name === "string") connection.client = params.client.name;
1504
1627
  const terminalLimits = await terminals?.advertised();
1505
- 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 } : {} } });
1628
+ 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 } : {} } });
1506
1629
  return;
1507
1630
  }
1508
1631
  if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first", { reason: "hello_required" });
@@ -1754,9 +1877,10 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1754
1877
  };
1755
1878
  },
1756
1879
  async close() {
1880
+ unsubscribeCatalog?.();
1757
1881
  closing = true;
1758
1882
  if (sweeper) clearInterval(sweeper);
1759
- attachments?.close();
1883
+ await attachments?.close();
1760
1884
  await terminals?.shutdown();
1761
1885
  await scheduler?.stop();
1762
1886
  const stopped = new Promise((resolve) => server.close(() => resolve()));
package/dist/store.d.ts CHANGED
@@ -94,7 +94,9 @@ export type StoreHealth = {
94
94
  };
95
95
  };
96
96
  export type Store = ReturnType<typeof createStore>;
97
- export declare function createStore(root: string): {
97
+ export declare function createStore(root: string, options?: {
98
+ onWriteError?: (error: unknown) => void;
99
+ }): {
98
100
  /** The state directory this store keeps its files in. */
99
101
  root: string;
100
102
  put(record: SessionRecord): Promise<void>;
package/dist/store.js CHANGED
@@ -9,7 +9,7 @@ var log = createLogger({ component: "store" });
9
9
  var SAFE = /[^\w.:-]/g;
10
10
  var fileName = (id) => id.replace(SAFE, "_");
11
11
  var TAIL_CHUNK = 64 * 1024;
12
- function createStore(root) {
12
+ function createStore(root, options = {}) {
13
13
  const sessionsDir = path.join(root, "sessions");
14
14
  const timelineDir = path.join(root, "timeline");
15
15
  const historyIndexes = /* @__PURE__ */ new Map();
@@ -53,6 +53,7 @@ function createStore(root) {
53
53
  health.failures++;
54
54
  health.lastError = { at: (/* @__PURE__ */ new Date()).toISOString(), operation, message: error?.message ?? String(error) };
55
55
  log.error(`${operation} failed`, { code: "ALP_PERSISTENCE_WRITE_FAILED", operation, error, ...ids });
56
+ options.onWriteError?.(error);
56
57
  }
57
58
  );
58
59
  map.set(key, settled);
@@ -228,7 +229,7 @@ function createStore(root) {
228
229
  await appendFile(file, line, { mode: 384 });
229
230
  }, true, { rootId });
230
231
  },
231
- async history(rootId, sessionId, options = {}) {
232
+ async history(rootId, sessionId, options2 = {}) {
232
233
  await prepare();
233
234
  await appends.get(rootId);
234
235
  let index = historyIndexes.get(rootId);
@@ -236,7 +237,7 @@ function createStore(root) {
236
237
  index = createHistoryIndex(path.join(timelineDir, `${fileName(rootId)}.jsonl`));
237
238
  historyIndexes.set(rootId, index);
238
239
  }
239
- return index.page(sessionId, options);
240
+ return index.page(sessionId, options2);
240
241
  },
241
242
  /**
242
243
  * Rewinds a tree's timeline (§12.7), idempotently: the whole timeline moves to the branch file