@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
@@ -0,0 +1,198 @@
1
+ // packages/daemon/src/native-terminal.ts
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { existsSync, readFileSync, statSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+ import path from "node:path";
7
+ import { StringDecoder } from "node:string_decoder";
8
+ var sha = (value) => createHash("sha256").update(value).digest("hex");
9
+ function binary() {
10
+ const libc = process.platform === "linux" ? process.report?.getReport()?.header?.glibcVersionRuntime ? "glibc" : "musl" : void 0;
11
+ const slot = [process.platform, process.arch, libc].filter(Boolean).join("-");
12
+ const assets = globalThis[Symbol.for("alp.packaged")]?.assetDir?.();
13
+ const adjacent = assets ? path.join(assets, "terminal-native") : path.join(path.dirname(fileURLToPath(import.meta.url)), "terminal-native");
14
+ const dir = assets || existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../native");
15
+ const file = path.join(dir, "prebuilt", slot, "terminal-owner");
16
+ const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), "manifest.json"), "utf8"));
17
+ if (!statSync(file).isFile() || manifest.protocol !== 1 || manifest.slot !== slot || manifest.source !== sha(readFileSync(path.join(dir, "terminal-owner.c"))) || manifest.sha256 !== sha(readFileSync(file))) throw new Error("Native helper manifest mismatch");
18
+ return file;
19
+ }
20
+ function nativeCapabilityOf(probe, platform) {
21
+ if (probe.status === 0 && probe.stdout.trim() === "alp-terminal-owner:1") return { available: true };
22
+ if (platform === "linux" && probe.status === 0 && probe.stdout.trim() === "alp-terminal-owner:1:root-only") return { available: true, protection: "root-only", reason: "bound_signal_unavailable" };
23
+ return { available: false, reason: "native_capability_unavailable" };
24
+ }
25
+ function nativeTerminalCapability() {
26
+ try {
27
+ const probe = spawnSync(binary(), ["--capability"], { encoding: "utf8", timeout: 2e3, maxBuffer: 4096 });
28
+ return nativeCapabilityOf(probe, process.platform);
29
+ } catch {
30
+ return { available: false, reason: "native_prebuilt_unavailable" };
31
+ }
32
+ }
33
+ async function nativePtySpawn(file, args, options) {
34
+ if (options.signal?.aborted) throw new Error("Native terminal startup cancelled");
35
+ const child = spawn(binary(), [...options.protection === "root-only" ? ["--root-only"] : [], String(options.cols), String(options.rows), String(options.killGraceMs ?? 1e3), options.cwd, file, ...args], { env: options.env, stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"] });
36
+ const control = child.stdio[4];
37
+ const events = child.stdio[3];
38
+ const data = /* @__PURE__ */ new Set(), exits = /* @__PURE__ */ new Set();
39
+ const decoder = new StringDecoder("utf8");
40
+ let buffered = "", protocol = "", exit, pid = 0;
41
+ let readyResolve, readyReject, finish;
42
+ const ready = new Promise((resolve, reject) => {
43
+ readyResolve = resolve;
44
+ readyReject = reject;
45
+ });
46
+ const finished = new Promise((resolve) => {
47
+ finish = resolve;
48
+ });
49
+ let result, completed = false, closing = false, adapterFailed = false;
50
+ let controlBlocked = false, pendingResize;
51
+ const resizeCommand = (command) => {
52
+ if (closing || result) return;
53
+ if (controlBlocked) {
54
+ pendingResize = command;
55
+ return;
56
+ }
57
+ controlBlocked = !control.write(command);
58
+ };
59
+ control.on("drain", () => {
60
+ controlBlocked = false;
61
+ const next = pendingResize;
62
+ pendingResize = void 0;
63
+ if (next) resizeCommand(next);
64
+ });
65
+ const closeOwner = () => {
66
+ if (closing || result) return;
67
+ closing = true;
68
+ pendingResize = void 0;
69
+ control.destroy();
70
+ child.stdin?.end();
71
+ };
72
+ const fail = (reason) => {
73
+ adapterFailed = true;
74
+ readyReject(new Error(reason));
75
+ closeOwner();
76
+ };
77
+ const timer = setTimeout(() => fail("Native terminal startup timed out"), 5e3);
78
+ const complete = (value) => {
79
+ if (!completed) {
80
+ completed = true;
81
+ result = adapterFailed ? { ...value, uncertain: Math.max(1, value.uncertain) } : value;
82
+ finish(result);
83
+ }
84
+ };
85
+ child.on("error", (error) => {
86
+ fail(error.message);
87
+ complete({ observed: 0, live: 0, uncertain: 1 });
88
+ });
89
+ child.on("close", () => {
90
+ clearTimeout(timer);
91
+ if (!pid) readyReject(new Error("Native terminal refused startup"));
92
+ exit ??= { exitCode: null };
93
+ for (const listener of exits) listener(exit);
94
+ complete(result ?? { observed: 0, live: 0, uncertain: 1 });
95
+ });
96
+ child.stderr?.resume();
97
+ child.stdin?.on("error", () => {
98
+ });
99
+ control.on("error", () => {
100
+ });
101
+ child.stdout?.on("data", (chunk) => {
102
+ const text = decoder.write(chunk);
103
+ if (data.size) for (const listener of data) listener(text);
104
+ else if (Buffer.byteLength(buffered) + Buffer.byteLength(text) <= 1024 * 1024) buffered += text;
105
+ else fail("Native terminal output limit exceeded");
106
+ });
107
+ events.on("data", (chunk) => {
108
+ protocol += chunk.toString("utf8");
109
+ if (protocol.length > 8192) {
110
+ fail("Invalid native protocol");
111
+ return;
112
+ }
113
+ let newline;
114
+ while ((newline = protocol.indexOf("\n")) >= 0) {
115
+ const line = protocol.slice(0, newline);
116
+ protocol = protocol.slice(newline + 1);
117
+ try {
118
+ const value = JSON.parse(line);
119
+ if (value.ready && value.protocol === 1 && Number.isSafeInteger(value.ready) && value.ready > 1) {
120
+ pid = value.ready;
121
+ clearTimeout(timer);
122
+ readyResolve();
123
+ } else if ("exitCode" in value) {
124
+ exit = { exitCode: value.exitCode, signal: value.signal };
125
+ } else if (value.cleanup === true && ["observed", "live", "uncertain"].every((key) => Number.isSafeInteger(value[key]) && value[key] >= 0)) result = value;
126
+ else if (value.refused === "terminal_protection_ack_required" || value.refused === "terminal_unsupported") {
127
+ readyReject(Object.assign(new Error("Native terminal capability changed before startup"), { terminalReason: value.refused }));
128
+ } else if (value.error) fail(String(value.error));
129
+ else fail("Invalid native event");
130
+ } catch {
131
+ fail("Invalid native JSON");
132
+ }
133
+ }
134
+ });
135
+ const abort = () => fail("Native terminal startup cancelled");
136
+ options.signal?.addEventListener("abort", abort, { once: true });
137
+ if (options.signal?.aborted) abort();
138
+ try {
139
+ await ready;
140
+ } catch (error) {
141
+ const cleanupResult = await finished;
142
+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), { cleanupResult });
143
+ } finally {
144
+ options.signal?.removeEventListener("abort", abort);
145
+ }
146
+ return {
147
+ pid,
148
+ write(value) {
149
+ if (closing || result) return;
150
+ if ((child.stdin?.writableLength ?? 0) + Buffer.byteLength(value) > 1024 * 1024) {
151
+ fail("Native input limit exceeded");
152
+ return;
153
+ }
154
+ child.stdin?.write(value);
155
+ },
156
+ resize(cols, rows) {
157
+ if (Number.isInteger(cols) && Number.isInteger(rows) && cols > 0 && cols <= 1e3 && rows > 0 && rows <= 1e3) resizeCommand(`R ${cols} ${rows}
158
+ `);
159
+ },
160
+ kill() {
161
+ closeOwner();
162
+ },
163
+ cleanup() {
164
+ closeOwner();
165
+ return finished;
166
+ },
167
+ onData(listener) {
168
+ data.add(listener);
169
+ if (buffered) {
170
+ const value = buffered;
171
+ buffered = "";
172
+ queueMicrotask(() => {
173
+ if (data.has(listener)) listener(value);
174
+ });
175
+ }
176
+ return { dispose() {
177
+ data.delete(listener);
178
+ } };
179
+ },
180
+ onExit(listener) {
181
+ exits.add(listener);
182
+ if (exit && completed) {
183
+ const value = exit;
184
+ queueMicrotask(() => {
185
+ if (exits.has(listener)) listener(value);
186
+ });
187
+ }
188
+ return { dispose() {
189
+ exits.delete(listener);
190
+ } };
191
+ }
192
+ };
193
+ }
194
+ export {
195
+ nativeCapabilityOf,
196
+ nativePtySpawn,
197
+ nativeTerminalCapability
198
+ };
@@ -12,9 +12,19 @@ export type OperationsOptions = {
12
12
  templates?: Record<string, string>;
13
13
  /** Project roots the daemon knows from its session records, for a team save's sync. */
14
14
  knownProjects?: () => Iterable<string>;
15
+ /** A gate changed through task.gate.resolve: the runtime syncs the project's gate cards and mail. */
16
+ onGateChange?: (projectRoot: string) => Promise<void> | void;
15
17
  };
16
- type Handler = (params: any) => Promise<unknown>;
17
- export declare function createOperations({ home, templates, knownProjects }?: OperationsOptions): {
18
+ /** `caller.agent`: the connection said in daemon.hello that an ALP agent started it (t-ca1f). */
19
+ export type Caller = {
20
+ agent?: boolean;
21
+ };
22
+ type Handler = (params: any, caller?: Caller) => Promise<unknown>;
23
+ /** Core refusals (AlpError codes) as protocol errors; `context` decides what an ambiguous one means. */
24
+ export declare function fromCore(error: any, context?: {
25
+ notFound?: 'not_found' | 'invalid_entry';
26
+ }): unknown;
27
+ export declare function createOperations({ home, templates, knownProjects, onGateChange }?: OperationsOptions): {
18
28
  handlers: {
19
29
  [x: string]: Handler;
20
30
  };
@@ -3,11 +3,11 @@ import { createHash, createHmac, randomBytes } from "node:crypto";
3
3
  import { lstat, stat } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { CAPABILITY, ERROR, RPC_ERROR } from "@anhlp/alp-protocol";
6
- import { closeTask, createTask, epicReport, loadTasks, reopenTask, resolveGate } from "@anhlp/alp-core/tasks";
6
+ import { closeTask, createTask, epicReport, loadTasks, rejectGate, reopenTask, resolveGate } from "@anhlp/alp-core/tasks";
7
7
  import { taskRows } from "@anhlp/alp-core/task-rows";
8
8
  import { deleteEntry, duplicateEntry, getEntry, listEntries, renameEntry, saveEntry, setGivenSkills } from "@anhlp/alp-core/library-edit";
9
9
  import { listTeams } from "@anhlp/alp-core/teams";
10
- import { MODELS } from "@anhlp/alp-core/models";
10
+ import { catalogEntries } from "@anhlp/alp-runtime/index";
11
11
  import { listProviders } from "@anhlp/alp-core/providers";
12
12
  import { languageSetting, setLanguage, LANGUAGE_CHARS } from "@anhlp/alp-core/user-settings";
13
13
  import { syncProjectSettings } from "@anhlp/alp-core/init";
@@ -39,6 +39,8 @@ function fromCore(error, context = {}) {
39
39
  case "TASK_TAKEN":
40
40
  case "TASK_UNVERIFIED":
41
41
  return failure(ERROR.conflict, "task_state", message);
42
+ case "GATE_USER_ONLY":
43
+ return failure(ERROR.forbidden, "user_only", message);
42
44
  case "TASKS_LOCKED":
43
45
  return failure(ERROR.unavailable, "busy", message);
44
46
  case "IN_USE":
@@ -102,7 +104,7 @@ function unredact(kind, content, previous) {
102
104
  if (found !== void 0) throw failure(RPC_ERROR.invalidParams, "secret_marker", `${found || "content"} holds a secret marker where no secret is kept`);
103
105
  return next;
104
106
  }
105
- function createOperations({ home, templates, knownProjects = () => [] } = {}) {
107
+ function createOperations({ home, templates, knownProjects = () => [], onGateChange } = {}) {
106
108
  const revisionKey = randomBytes(32);
107
109
  const toWire = (revision) => revision == null ? null : `r${createHmac("sha256", revisionKey).update(revision).digest("base64url").slice(0, 22)}`;
108
110
  let writes = Promise.resolve();
@@ -133,9 +135,9 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
133
135
  throw error;
134
136
  }
135
137
  }
136
- const guard = (handler, context) => async (params) => {
138
+ const guard = (handler, context) => async (params, caller) => {
137
139
  try {
138
- return await handler(params);
140
+ return await handler(params, caller);
139
141
  } catch (error) {
140
142
  throw fromCore(error, context);
141
143
  }
@@ -167,21 +169,29 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
167
169
  });
168
170
  return result;
169
171
  }),
170
- "task.update": guard(async ({ projectRoot, id, action, note, ifRev }) => {
172
+ "task.update": guard(async ({ projectRoot, id, action, note, ifRev }, caller) => {
171
173
  const root = await project(projectRoot);
172
174
  const options = ifRev !== void 0 ? { ifRev } : void 0;
173
175
  if (action === "reopen") {
174
176
  const task2 = await reopenTask(root, id, { ...note ? { note } : {} }, "user", options);
175
177
  return { id: task2.id, status: task2.status, rev: task2.rev };
176
178
  }
177
- const task = await closeTask(root, id, { reason: "done", ...note ? { summary: note } : {} }, "user", options);
179
+ const task = await closeTask(root, id, { reason: "done", ...note ? { summary: note } : {}, agent: caller?.agent === true, channel: "web" }, "user", options);
178
180
  const { tasks } = await loadTasks(root);
179
181
  const landed = tasks.some((entry) => entry.parent === task.id) ? epicReport(task.id, tasks).text.split("\n")[0] : void 0;
180
182
  return { id: task.id, status: task.status, rev: task.rev, ...landed ? { landed } : {} };
181
183
  }),
182
- "task.gate.resolve": guard(async ({ projectRoot, id, gate, note, ifRev }) => {
184
+ // Approves a gate, or with reject records the user's rejection and leaves it open. Either way
185
+ // the runtime is told, so main gets the decision by mail (at least once) and the gate's card settles.
186
+ "task.gate.resolve": guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = "web" }, caller) => {
183
187
  const root = await project(projectRoot);
184
- const task = await resolveGate(root, id, gate, { by: "user", ...note ? { note } : {}, ...ifRev !== void 0 ? { ifRev } : {} });
188
+ if (caller?.agent) {
189
+ const { tasks } = await loadTasks(root);
190
+ if (tasks.find((task2) => task2.id === id)?.gates.find((entry) => entry.id === gate)?.kind === "human") throw failure(ERROR.forbidden, "user_only", "Only the user decides a human gate; this connection was opened by an ALP agent");
191
+ }
192
+ const guarded = ifRev !== void 0 ? { ifRev } : {};
193
+ const task = reject === true ? await rejectGate(root, id, gate, { by: "user", channel, ...note ? { reason: note } : {}, ...guarded }) : await resolveGate(root, id, gate, { by: "user", channel, ...note ? { note } : {}, ...choice !== void 0 ? { choice } : {}, ...guarded });
194
+ await onGateChange?.(root);
185
195
  return { id: task.id, status: task.status, rev: task.rev };
186
196
  })
187
197
  };
@@ -250,7 +260,7 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
250
260
  })),
251
261
  "library.skills.set": guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: "invalid_entry" }),
252
262
  "library.models": guard(async () => {
253
- const models = MODELS.map((model) => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} \xB7 ${model.label}`, efforts: model.efforts, ...model.effort ? { effort: model.effort } : {} }));
263
+ const models = catalogEntries.map((model) => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} \xB7 ${model.label}`, efforts: model.efforts, ...model.effort ? { effort: model.effort } : {} }));
254
264
  for (const provider of await listProviders(home)) {
255
265
  if (provider.enabled === false || provider.kind === "antigravity") continue;
256
266
  models.push({ id: `acp:${provider.id}`, label: `${provider.label} \xB7 Provider default`, efforts: [] });
@@ -271,5 +281,6 @@ function createOperations({ home, templates, knownProjects = () => [] } = {}) {
271
281
  };
272
282
  }
273
283
  export {
274
- createOperations
284
+ createOperations,
285
+ fromCore
275
286
  };
package/dist/registry.js CHANGED
@@ -331,7 +331,7 @@ function createRegistry(home, options = {}) {
331
331
  if (!includeArchived && !live(r, w)) fail("not_found", "Workspace is archived", 1001);
332
332
  if (Object.values(r.worktreeJournal ?? {}).some((j) => j.intent.id === workspaceId)) fail("reconciliation_required", "Workspace mutation requires reconciliation");
333
333
  const canonical = await identity(w.directory);
334
- if (w.canonical && canonical !== w.canonical) fail("identity_changed", "Workspace directory identity changed", 1003);
334
+ if (canonical !== (w.canonical ?? w.directory)) fail("identity_changed", "Workspace directory identity changed", 1003);
335
335
  if (cwd !== void 0 && await identity(cwd) !== canonical) fail("cwd_mismatch", "cwd and workspaceId must agree", -32602);
336
336
  return canonical;
337
337
  }
package/dist/scheduler.js CHANGED
@@ -30,6 +30,7 @@ function createScheduler({ store, runtime, deliver, ready, session, settled, sto
30
30
  const waiting = /* @__PURE__ */ new Map();
31
31
  const held = /* @__PURE__ */ new Map();
32
32
  const opening = /* @__PURE__ */ new Map();
33
+ const busy = /* @__PURE__ */ new Map();
33
34
  const heldSessions = /* @__PURE__ */ new Map();
34
35
  const delivering = /* @__PURE__ */ new Set();
35
36
  const unwritten = /* @__PURE__ */ new Set();
@@ -39,6 +40,7 @@ function createScheduler({ store, runtime, deliver, ready, session, settled, sto
39
40
  let timer;
40
41
  const hold = (job) => {
41
42
  if (!held.has(job.id)) held.set(job.id, { sessionId: job.sessionId, at: ++sequence });
43
+ if (job.keepsSession === false) return;
42
44
  const ids = waiting.get(job.sessionId) ?? /* @__PURE__ */ new Set();
43
45
  ids.add(job.id);
44
46
  waiting.set(job.sessionId, ids);
@@ -46,6 +48,7 @@ function createScheduler({ store, runtime, deliver, ready, session, settled, sto
46
48
  const releaseId = (id) => {
47
49
  const entry = held.get(id);
48
50
  opening.delete(id);
51
+ busy.delete(id);
49
52
  if (!entry) return;
50
53
  held.delete(id);
51
54
  const ids = waiting.get(entry.sessionId);
@@ -132,13 +135,16 @@ function createScheduler({ store, runtime, deliver, ready, session, settled, sto
132
135
  if (snapshot.parentId) return fail(current, "The session this job continues is not a root session", "not_a_root");
133
136
  if (projectKey(snapshot.projectRoot) !== projectKey(current.projectRoot)) return fail(current, "The session this job continues belongs to another project", "other_project");
134
137
  const waitBusy = async () => {
135
- const overdue = now() - Date.parse(current.dueAt);
136
- if (overdue > graceMs) return fail(current, `The session was still busy ${duration(overdue)} after the job was due`, "session_busy");
138
+ const since = busy.get(current.id) ?? now();
139
+ busy.set(current.id, since);
140
+ const waited = now() - since;
141
+ if (waited > graceMs) return fail(current, `The session was still busy after waiting ${duration(waited)}`, "session_busy");
137
142
  const note = { message: "The session is busy; the job waits for its turn to end", code: "session_busy" };
138
143
  await store.change(current.id, (job2) => job2.status === "pending" && job2.lastError?.code !== note.code ? { lastError: note } : void 0).catch((error) => log.warn(`could not record the wait of job ${current.id}`, { code: "ALP_SCHEDULE_WRITE_FAILED", jobId: current.id, error }));
139
144
  return "waiting";
140
145
  };
141
146
  if (snapshot.activeTurnId || runtime.starting?.(current.sessionId)) return waitBusy();
147
+ busy.delete(current.id);
142
148
  const dispatch = async (send) => {
143
149
  delivering.add(current.id);
144
150
  try {
@@ -29,11 +29,12 @@ export declare function createScheduleStore(root: string, { now }?: {
29
29
  * A new job waiting for its time. The id is drawn here, so two jobs never
30
30
  * share one and a job's own id names its delivery.
31
31
  */
32
- create({ projectRoot, sessionId, prompt, dueAt }: {
32
+ create({ projectRoot, sessionId, prompt, dueAt, keepsSession }: {
33
33
  projectRoot: string;
34
34
  sessionId: string;
35
35
  prompt: string;
36
36
  dueAt: string;
37
+ keepsSession?: boolean;
37
38
  }): Promise<ScheduleRecord>;
38
39
  /** The job of that id, or undefined when there is none. */
39
40
  get(id: string, { projectRoot }?: {
package/dist/schedules.js CHANGED
@@ -42,7 +42,7 @@ function readJob(text, name) {
42
42
  const isTime = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value));
43
43
  const isDueAt = (value) => typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.test(value) && !Number.isNaN(Date.parse(value));
44
44
  const isError = (value) => typeof value === "object" && value !== null && typeof value.message === "string" && (value.code === void 0 || typeof value.code === "string");
45
- const sound = record?.version === SCHEDULE_VERSION && typeof record.id === "string" && SCHEDULE_ID.test(record.id) && name === `${record.id}.json` && isStatus(record.status) && typeof record.projectRoot === "string" && record.projectRoot && typeof record.sessionId === "string" && record.sessionId && typeof record.prompt === "string" && isDueAt(record.dueAt) && isTime(record.createdAt) && isTime(record.updatedAt) && (record.attemptedAt === void 0 || isTime(record.attemptedAt)) && (record.deliveredAt === void 0 || isTime(record.deliveredAt)) && (record.failedAt === void 0 || isTime(record.failedAt)) && (record.cancelledAt === void 0 || isTime(record.cancelledAt)) && (record.lateByMs === void 0 || Number.isSafeInteger(record.lateByMs) && record.lateByMs >= 0) && (record.attempts === void 0 || Number.isSafeInteger(record.attempts) && record.attempts >= 0) && (record.lastError === void 0 || isError(record.lastError));
45
+ const sound = record?.version === SCHEDULE_VERSION && typeof record.id === "string" && SCHEDULE_ID.test(record.id) && name === `${record.id}.json` && isStatus(record.status) && typeof record.projectRoot === "string" && record.projectRoot && typeof record.sessionId === "string" && record.sessionId && typeof record.prompt === "string" && isDueAt(record.dueAt) && isTime(record.createdAt) && isTime(record.updatedAt) && (record.attemptedAt === void 0 || isTime(record.attemptedAt)) && (record.deliveredAt === void 0 || isTime(record.deliveredAt)) && (record.failedAt === void 0 || isTime(record.failedAt)) && (record.cancelledAt === void 0 || isTime(record.cancelledAt)) && (record.lateByMs === void 0 || Number.isSafeInteger(record.lateByMs) && record.lateByMs >= 0) && (record.attempts === void 0 || Number.isSafeInteger(record.attempts) && record.attempts >= 0) && (record.lastError === void 0 || isError(record.lastError)) && (record.keepsSession === void 0 || record.keepsSession === false);
46
46
  if (!sound) {
47
47
  log.warn(`skipped invalid job ${name}`, { code: "ALP_SCHEDULE_UNREADABLE", file: name });
48
48
  return void 0;
@@ -62,7 +62,8 @@ function readJob(text, name) {
62
62
  ...record.failedAt === void 0 ? {} : { failedAt: record.failedAt },
63
63
  ...record.cancelledAt === void 0 ? {} : { cancelledAt: record.cancelledAt },
64
64
  ...record.lateByMs === void 0 ? {} : { lateByMs: record.lateByMs },
65
- ...record.lastError === void 0 ? {} : { lastError: { message: record.lastError.message, ...record.lastError.code === void 0 ? {} : { code: record.lastError.code } } }
65
+ ...record.lastError === void 0 ? {} : { lastError: { message: record.lastError.message, ...record.lastError.code === void 0 ? {} : { code: record.lastError.code } } },
66
+ ...record.keepsSession === false ? { keepsSession: false } : {}
66
67
  };
67
68
  }
68
69
  function without(value) {
@@ -104,7 +105,7 @@ function createScheduleStore(root, { now = () => Date.now() } = {}) {
104
105
  * A new job waiting for its time. The id is drawn here, so two jobs never
105
106
  * share one and a job's own id names its delivery.
106
107
  */
107
- async create({ projectRoot, sessionId, prompt, dueAt }) {
108
+ async create({ projectRoot, sessionId, prompt, dueAt, keepsSession }) {
108
109
  if (typeof projectRoot !== "string" || !projectRoot) throw new ScheduleStoreError("INVALID_SCHEDULE", "A job needs the project it continues");
109
110
  if (!path.isAbsolute(projectRoot)) throw new ScheduleStoreError("INVALID_SCHEDULE", "A job needs the absolute path of the project it continues");
110
111
  if (typeof sessionId !== "string" || !sessionId) throw new ScheduleStoreError("INVALID_SCHEDULE", "A job needs the session it continues");
@@ -123,7 +124,8 @@ function createScheduleStore(root, { now = () => Date.now() } = {}) {
123
124
  status: "pending",
124
125
  attempts: 0,
125
126
  createdAt: at,
126
- updatedAt: at
127
+ updatedAt: at,
128
+ ...keepsSession === false ? { keepsSession: false } : {}
127
129
  });
128
130
  },
129
131
  /** The job of that id, or undefined when there is none. */
package/dist/server.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { ERROR } from '@anhlp/alp-protocol';
2
- import { type AlpRuntime } from '@anhlp/alp-runtime/index';
2
+ import { type ModelCatalog, type AlpRuntime } from '@anhlp/alp-runtime/index';
3
3
  import type { Store } from './store.js';
4
4
  import type { SessionSummary } from '@anhlp/alp-protocol/session';
5
5
  import { type OperationsOptions } from './operations.js';
@@ -27,7 +27,9 @@ export type DaemonServer = {
27
27
  /** A session as clients list it: its last snapshot plus lifecycle (ALPD §18). The protocol owns the
28
28
  * shape so every viewer agrees; re-exported here to keep `@anhlp/alp-daemon/server`'s API. */
29
29
  export type { SessionSummary };
30
- export declare function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs, home, templates, scheduleTickMs, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions }: {
30
+ export declare function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs, home, templates, scheduleTickMs, scheduleDeliveryTimeoutMs, attachmentOptions, terminalOptions, modelCatalog }: {
31
+ /** The live model catalog (t-e5ee); without it catalog.get answers the static rows and catalog.refresh is unavailable. */
32
+ modelCatalog?: ModelCatalog;
31
33
  runtime: AlpRuntime;
32
34
  socketPath: string;
33
35
  version: string;