@anhlp/alp-daemon 0.0.0-beta.2 → 0.0.1-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +4 -0
  2. package/dist/THIRD-PARTY-NOTICES.txt +27 -2
  3. package/dist/alpd.js +39374 -17503
  4. package/dist/attachments.d.ts +187 -0
  5. package/dist/attachments.js +856 -0
  6. package/dist/build-manifest.json +41 -2
  7. package/dist/conversation.d.ts +119 -0
  8. package/dist/conversation.js +688 -0
  9. package/dist/disk.d.ts +67 -0
  10. package/dist/disk.js +152 -0
  11. package/dist/files.d.ts +156 -3
  12. package/dist/files.js +402 -59
  13. package/dist/git.d.ts +98 -0
  14. package/dist/git.js +1246 -0
  15. package/dist/gitignore.d.ts +5 -0
  16. package/dist/gitignore.js +26 -7
  17. package/dist/history.d.ts +24 -0
  18. package/dist/history.js +149 -0
  19. package/dist/index.d.ts +7 -0
  20. package/dist/index.js +21 -1
  21. package/dist/lifecycle.d.ts +101 -0
  22. package/dist/lifecycle.js +239 -0
  23. package/dist/main.js +146 -21
  24. package/dist/model-catalog.d.ts +2 -0
  25. package/dist/model-catalog.js +44 -0
  26. package/dist/native-entry.d.ts +2 -0
  27. package/dist/native-entry.js +3 -0
  28. package/dist/native-register.d.ts +1 -0
  29. package/dist/native-register.js +13 -0
  30. package/dist/native-terminal.d.ts +45 -0
  31. package/dist/native-terminal.js +201 -0
  32. package/dist/operations.d.ts +20 -3
  33. package/dist/operations.js +62 -21
  34. package/dist/registry.d.ts +89 -0
  35. package/dist/registry.js +343 -0
  36. package/dist/scheduler.d.ts +96 -0
  37. package/dist/scheduler.js +298 -0
  38. package/dist/schedules.d.ts +70 -0
  39. package/dist/schedules.js +246 -0
  40. package/dist/server.d.ts +14 -2
  41. package/dist/server.js +903 -97
  42. package/dist/store.d.ts +72 -2
  43. package/dist/store.js +111 -4
  44. package/dist/terminal-native/README.md +201 -0
  45. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  46. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  48. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  49. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  50. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  51. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  52. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  53. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  54. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  55. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  56. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  57. package/dist/terminal-native/terminal-owner.c +389 -0
  58. package/dist/terminal-screen.d.ts +24 -0
  59. package/dist/terminal-screen.js +99 -0
  60. package/dist/terminals.d.ts +203 -0
  61. package/dist/terminals.js +570 -0
  62. package/dist/windows-terminal.d.ts +32 -0
  63. package/dist/windows-terminal.js +79 -0
  64. package/dist/worktrees.d.ts +65 -0
  65. package/dist/worktrees.js +318 -0
  66. package/native/README.md +201 -0
  67. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  68. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  69. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  70. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  71. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  72. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  73. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  74. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  75. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  76. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  77. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  78. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  79. package/native/terminal-owner.c +389 -0
  80. package/package.json +71 -8
  81. package/src/attachments.ts +908 -0
  82. package/src/conversation.ts +857 -0
  83. package/src/disk.ts +175 -0
  84. package/src/files.ts +535 -71
  85. package/src/git.ts +1220 -0
  86. package/src/gitignore.ts +25 -8
  87. package/src/history.ts +118 -0
  88. package/src/index.ts +7 -0
  89. package/src/lifecycle.ts +283 -0
  90. package/src/main.ts +154 -23
  91. package/src/model-catalog.ts +36 -0
  92. package/src/native-entry.ts +5 -0
  93. package/src/native-register.ts +21 -0
  94. package/src/native-terminal.ts +127 -0
  95. package/src/operations.ts +53 -22
  96. package/src/registry.ts +238 -0
  97. package/src/scheduler.ts +438 -0
  98. package/src/schedules.ts +297 -0
  99. package/src/server.ts +1019 -109
  100. package/src/store.ts +117 -4
  101. package/src/terminal-screen.ts +74 -0
  102. package/src/terminals.ts +653 -0
  103. package/src/windows-terminal.ts +74 -0
  104. package/src/worktrees.ts +382 -0
@@ -0,0 +1,298 @@
1
+ // packages/daemon/src/scheduler.ts
2
+ import { createLogger } from "@anhlp/alp-core/log";
3
+ import { projectKey } from "./schedules.js";
4
+ var log = createLogger({ component: "alpd.schedule" });
5
+ var SCHEDULE_GRACE_MS = 60 * 60 * 1e3;
6
+ var SCHEDULE_TICK_MS = 1e4;
7
+ var DELIVERY_TIMEOUT_MS = 2 * 60 * 1e3;
8
+ function duration(ms) {
9
+ const seconds = Math.max(0, Math.round(ms / 1e3));
10
+ if (seconds < 60) return `${seconds} second${seconds === 1 ? "" : "s"}`;
11
+ const minutes = Math.floor(seconds / 60);
12
+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"}`;
13
+ const hours = Math.floor(minutes / 60);
14
+ const rest = minutes % 60;
15
+ const hour = `${hours} hour${hours === 1 ? "" : "s"}`;
16
+ return rest ? `${hour} ${rest} minute${rest === 1 ? "" : "s"}` : hour;
17
+ }
18
+ function renderPrompt(job) {
19
+ const due = new Date(job.dueAt).toISOString();
20
+ const late = job.lateByMs && job.lateByMs > 0 ? ` and running ${duration(job.lateByMs)} late` : "";
21
+ return `This is a scheduled continuation (job ${job.id}), due ${due}${late}.
22
+ Before delegating a quota-reset continuation, recheck actual provider availability using the fresh runtime usage snapshot. The scheduled time does not guarantee quota; unavailable or missing usage data is not proof of availability.
23
+
24
+ ${job.prompt}`;
25
+ }
26
+ function clientMessageId(job) {
27
+ return `alp-job-${job.id}`;
28
+ }
29
+ function createScheduler({ store, runtime, deliver, ready, session, settled, stopping, now = () => Date.now(), graceMs = SCHEDULE_GRACE_MS, deliveryTimeoutMs = DELIVERY_TIMEOUT_MS }) {
30
+ const waiting = /* @__PURE__ */ new Map();
31
+ const held = /* @__PURE__ */ new Map();
32
+ const opening = /* @__PURE__ */ new Map();
33
+ const busy = /* @__PURE__ */ new Map();
34
+ const heldSessions = /* @__PURE__ */ new Map();
35
+ const delivering = /* @__PURE__ */ new Set();
36
+ const unwritten = /* @__PURE__ */ new Set();
37
+ let sequence = 0;
38
+ let ticking = false;
39
+ let running;
40
+ let timer;
41
+ const hold = (job) => {
42
+ if (!held.has(job.id)) held.set(job.id, { sessionId: job.sessionId, at: ++sequence });
43
+ if (job.keepsSession === false) return;
44
+ const ids = waiting.get(job.sessionId) ?? /* @__PURE__ */ new Set();
45
+ ids.add(job.id);
46
+ waiting.set(job.sessionId, ids);
47
+ };
48
+ const releaseId = (id) => {
49
+ const entry = held.get(id);
50
+ opening.delete(id);
51
+ busy.delete(id);
52
+ if (!entry) return;
53
+ held.delete(id);
54
+ const ids = waiting.get(entry.sessionId);
55
+ if (!ids) return;
56
+ ids.delete(id);
57
+ if (!ids.size) waiting.delete(entry.sessionId);
58
+ };
59
+ const release = (job) => {
60
+ releaseId(job.id);
61
+ settled?.(job.sessionId);
62
+ };
63
+ async function refresh() {
64
+ const at = sequence;
65
+ const jobs = await store.all({ status: "pending" });
66
+ const pending = new Set(jobs.filter((job) => !unwritten.has(job.id)).map((job) => job.id));
67
+ for (const job of jobs) if (!unwritten.has(job.id)) hold(job);
68
+ for (const [id, entry] of [...held]) {
69
+ if (entry.at > at || pending.has(id)) continue;
70
+ releaseId(id);
71
+ settled?.(entry.sessionId);
72
+ }
73
+ }
74
+ async function fail(job, message, code) {
75
+ const at = new Date(now()).toISOString();
76
+ const reason = { message, ...code ? { code } : {} };
77
+ const saved = await store.change(job.id, (current) => current.status === "pending" ? { status: "failed", failedAt: at, lastError: reason } : void 0).catch((error) => {
78
+ unwritten.add(job.id);
79
+ log.warn(`could not record the failure of job ${job.id}; it stays pending on disk and is not tried again until the next alpd`, { code: "ALP_SCHEDULE_WRITE_FAILED", jobId: job.id, error });
80
+ return void 0;
81
+ });
82
+ if (!saved) {
83
+ release(job);
84
+ log.warn(`job ${job.id} failed: ${message} (the job file was not changed)`, { code: "ALP_SCHEDULE_FAILED", jobId: job.id, sessionId: job.sessionId, reason: code });
85
+ return "failed";
86
+ }
87
+ release(saved);
88
+ log.warn(`job ${job.id} failed: ${message}`, { code: "ALP_SCHEDULE_FAILED", jobId: job.id, sessionId: job.sessionId, reason: code });
89
+ return "failed";
90
+ }
91
+ async function done(job) {
92
+ const at = new Date(now()).toISOString();
93
+ const saved = await store.change(job.id, (current) => current.status === "pending" ? { status: "delivered", deliveredAt: at, lastError: void 0 } : void 0).catch((error) => {
94
+ unwritten.add(job.id);
95
+ log.warn(`could not record the delivery of job ${job.id}; it stays pending on disk and is not tried again until the next alpd`, { code: "ALP_SCHEDULE_WRITE_FAILED", jobId: job.id, error });
96
+ return void 0;
97
+ });
98
+ if (!saved) {
99
+ release(job);
100
+ log.warn(`job ${job.id} was delivered, but its file was not changed`, { code: "ALP_SCHEDULE_DELIVERED", jobId: job.id, sessionId: job.sessionId });
101
+ return "delivered";
102
+ }
103
+ release(saved);
104
+ log.info(`job ${job.id} delivered to ${job.sessionId}${job.lateByMs ? ` (${duration(job.lateByMs)} late)` : ""}`, { code: "ALP_SCHEDULE_DELIVERED", jobId: job.id, sessionId: job.sessionId });
105
+ return "delivered";
106
+ }
107
+ async function fire(job) {
108
+ const current = await store.get(job.id);
109
+ if (!current || current.status !== "pending") {
110
+ release(job);
111
+ return "skipped";
112
+ }
113
+ if (stopping?.()) return "skipped";
114
+ if (unwritten.has(current.id)) {
115
+ release(current);
116
+ return "skipped";
117
+ }
118
+ let attempt;
119
+ const snapshot = runtime.snapshot(current.sessionId);
120
+ const known = session?.(current.sessionId);
121
+ if (known?.opening) {
122
+ const since = opening.get(current.id) ?? now();
123
+ opening.set(current.id, since);
124
+ const waited = now() - since;
125
+ if (waited > graceMs) return fail(current, `The session was not open again within ${duration(waited)}`, "session_not_open");
126
+ const note = { message: "The session is being opened again; the job waits for it", code: "session_opening" };
127
+ 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 }));
128
+ return "waiting";
129
+ }
130
+ if (!snapshot) {
131
+ if (known?.error) return fail(current, known.error.message, known.error.code ?? "session_open_failed");
132
+ return fail(current, "The session this job continues is closed", "session_closed");
133
+ }
134
+ opening.delete(current.id);
135
+ if (snapshot.parentId) return fail(current, "The session this job continues is not a root session", "not_a_root");
136
+ if (projectKey(snapshot.projectRoot) !== projectKey(current.projectRoot)) return fail(current, "The session this job continues belongs to another project", "other_project");
137
+ const refused = runtime.refusesPrompt?.(current.sessionId, [{ type: "text", text: current.prompt }]);
138
+ if (refused) return fail(current, refused, "native_command_unsupported");
139
+ const waitBusy = async () => {
140
+ const since = busy.get(current.id) ?? now();
141
+ busy.set(current.id, since);
142
+ const waited = now() - since;
143
+ if (waited > graceMs) return fail(current, `The session was still busy after waiting ${duration(waited)}`, "session_busy");
144
+ const note = { message: "The session is busy; the job waits for its turn to end", code: "session_busy" };
145
+ 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 }));
146
+ return "waiting";
147
+ };
148
+ if (snapshot.activeTurnId || runtime.starting?.(current.sessionId)) return waitBusy();
149
+ busy.delete(current.id);
150
+ const dispatch = async (send) => {
151
+ delivering.add(current.id);
152
+ try {
153
+ const attemptedAtMs = current.attemptedAt ? Date.parse(current.attemptedAt) : now();
154
+ const lateByMs = current.lateByMs ?? Math.max(0, attemptedAtMs - Date.parse(current.dueAt));
155
+ const fields = { attemptedAt: new Date(attemptedAtMs).toISOString(), lateByMs, attempts: (current.attempts ?? 0) + 1, lastError: void 0 };
156
+ const persisted = await store.change(current.id, (job2) => job2.status === "pending" ? fields : void 0);
157
+ if (!persisted || persisted.status !== "pending") {
158
+ release(persisted ?? current);
159
+ return "skipped";
160
+ }
161
+ attempt = persisted;
162
+ const written = attempt;
163
+ const content = [{ type: "text", text: renderPrompt(written) }];
164
+ const delivery = deliver(written, content, clientMessageId(written), send);
165
+ void delivery.catch((error) => log.warn(`the delivery of job ${written.id} failed after it timed out`, { code: "ALP_SCHEDULE_DELIVERY_FAILED", jobId: written.id, error }));
166
+ let timer2;
167
+ const answer = await Promise.race([
168
+ delivery,
169
+ new Promise((resolve) => {
170
+ timer2 = setTimeout(() => resolve({ outcome: "failed", error: { message: `The session did not acknowledge the prompt within ${duration(deliveryTimeoutMs)}; execution outcome is unknown. The outstanding request was not cancelled and may still start a turn. Do not recreate automatically`, code: "delivery_timeout" } }), deliveryTimeoutMs);
171
+ timer2.unref?.();
172
+ })
173
+ ]).finally(() => {
174
+ if (timer2) clearTimeout(timer2);
175
+ });
176
+ if (answer.error?.code === "delivery_timeout") {
177
+ const result = await fail(attempt, answer.error.message, "delivery_timeout");
178
+ void delivery.then(async (late) => {
179
+ const message = late.outcome === "accepted" ? "The provider acknowledged the prompt after the delivery timeout; a turn may have executed. No retry was sent." : `The delivery answered after the timeout: ${late.error?.message ?? late.outcome}. No retry was sent.`;
180
+ log.warn(`job ${written.id}: ${message}`, { code: "ALP_SCHEDULE_LATE_ACK", jobId: written.id });
181
+ await store.change(written.id, (job2) => job2.status === "failed" && job2.lastError?.code === "delivery_timeout" ? { lastError: { code: late.outcome === "accepted" ? "delivery_accepted_late" : "delivery_timeout", message } } : void 0);
182
+ }).catch((error) => log.warn(`could not record late acknowledgement for job ${written.id}`, { code: "ALP_SCHEDULE_WRITE_FAILED", jobId: written.id, error }));
183
+ return result;
184
+ }
185
+ if (answer.outcome === "accepted") return done(attempt);
186
+ if (answer.outcome === "unknown") return fail(attempt, answer.error?.message ?? "alpd cannot tell whether the prompt reached the agent", answer.error?.code ?? "outcome_unknown");
187
+ return fail(attempt, answer.error?.message ?? "The session refused the prompt", answer.error?.code ?? "refused");
188
+ } catch (error) {
189
+ return fail(attempt ?? current, error?.message ?? String(error), error?.data?.reason ?? "delivery_failed");
190
+ } finally {
191
+ delivering.delete(current.id);
192
+ }
193
+ };
194
+ if (current.attempts || !runtime.withIdlePrompt) return dispatch();
195
+ const admission = await runtime.withIdlePrompt(current.sessionId, (send) => dispatch((_id, input) => send(input)));
196
+ return admission.busy ? waitBusy() : admission.value;
197
+ }
198
+ async function runTick() {
199
+ if (ticking) return { delivered: 0, failed: 0, waiting: 0 };
200
+ if (stopping?.()) return { delivered: 0, failed: 0, waiting: 0 };
201
+ ticking = true;
202
+ const outcome = { delivered: 0, failed: 0, waiting: 0 };
203
+ try {
204
+ await ready?.();
205
+ for (const job of await store.due(now())) {
206
+ let result = "skipped";
207
+ try {
208
+ result = await fire(job);
209
+ } catch (error) {
210
+ log.error(`job ${job.id} could not be delivered`, { code: "ALP_SCHEDULE_DELIVERY_FAILED", jobId: job.id, error });
211
+ }
212
+ if (result === "delivered") outcome.delivered++;
213
+ else if (result === "failed") outcome.failed++;
214
+ else if (result === "waiting") outcome.waiting++;
215
+ }
216
+ await refresh();
217
+ } catch (error) {
218
+ log.error("the scheduler could not deliver its jobs", { code: "ALP_SCHEDULE_TICK_FAILED", error });
219
+ } finally {
220
+ ticking = false;
221
+ }
222
+ return outcome;
223
+ }
224
+ async function tick() {
225
+ if (running) return running;
226
+ const pass = runTick();
227
+ running = pass;
228
+ try {
229
+ return await pass;
230
+ } finally {
231
+ if (running === pass) running = void 0;
232
+ }
233
+ }
234
+ return {
235
+ /** Whether a job waits for this session; such a session is kept open. */
236
+ holds(sessionId) {
237
+ return (heldSessions.get(sessionId) ?? 0) > 0 || (waiting.get(sessionId)?.size ?? 0) > 0;
238
+ },
239
+ /** A job that is just being created waits for its session, before it is written. */
240
+ holdSession(sessionId) {
241
+ heldSessions.set(sessionId, (heldSessions.get(sessionId) ?? 0) + 1);
242
+ },
243
+ /** The job is written; its own hold takes over. */
244
+ releaseSession(sessionId) {
245
+ const count = (heldSessions.get(sessionId) ?? 0) - 1;
246
+ if (count > 0) heldSessions.set(sessionId, count);
247
+ else heldSessions.delete(sessionId);
248
+ },
249
+ /** Whether a job is being delivered right now; a cancel of it is refused. */
250
+ delivering(jobId) {
251
+ return delivering.has(jobId);
252
+ },
253
+ /** A job that was just created waits for its session. */
254
+ hold,
255
+ /** A job that will not run any more waits for nothing. */
256
+ release,
257
+ /** Reads the job files again. */
258
+ refresh,
259
+ /** One pass of the tick. */
260
+ tick,
261
+ /** The tick, every `everyMs`; the first pass waits for the daemon's start-up. */
262
+ start(everyMs = SCHEDULE_TICK_MS) {
263
+ if (timer) return;
264
+ timer = setInterval(() => {
265
+ void tick();
266
+ }, everyMs);
267
+ timer.unref();
268
+ void refresh().catch((error) => log.warn("could not read the job files", { code: "ALP_SCHEDULE_READ_FAILED", error }));
269
+ },
270
+ /**
271
+ * The tick stops, and the pass that runs now is waited for, up to a grace: a
272
+ * delivery that outlives the grace is left to the next alpd, whose receipt of
273
+ * the message says whether it went through.
274
+ */
275
+ async stop() {
276
+ if (timer) clearInterval(timer);
277
+ timer = void 0;
278
+ if (!running) return;
279
+ let grace;
280
+ try {
281
+ await Promise.race([running, new Promise((resolve) => {
282
+ grace = setTimeout(resolve, 5e3);
283
+ })]);
284
+ } finally {
285
+ if (grace) clearTimeout(grace);
286
+ }
287
+ }
288
+ };
289
+ }
290
+ export {
291
+ DELIVERY_TIMEOUT_MS,
292
+ SCHEDULE_GRACE_MS,
293
+ SCHEDULE_TICK_MS,
294
+ clientMessageId,
295
+ createScheduler,
296
+ duration,
297
+ renderPrompt
298
+ };
@@ -0,0 +1,70 @@
1
+ import type { ScheduleJob, ScheduleStatus } from '@anhlp/alp-protocol/index';
2
+ /** The version of a job file; a file of another version is not read. */
3
+ export declare const SCHEDULE_VERSION = 1;
4
+ /** The id of a job: `sch_` and sixteen hex digits. */
5
+ export declare const SCHEDULE_ID: RegExp;
6
+ /** The most a job's prompt may hold, in characters. */
7
+ export declare const PROMPT_CHARS = 8000;
8
+ export type ScheduleStore = ReturnType<typeof createScheduleStore>;
9
+ /**
10
+ * The key a project is compared by: the directory it really names. A client that names
11
+ * the same directory in another spelling (a trailing slash, a doubled separator, a
12
+ * symlinked parent, a different case on a case-insensitive volume) must see the same
13
+ * jobs; the job of a project is the job of that directory.
14
+ */
15
+ export declare function projectKey(root: string): string;
16
+ /** A refusal of the job store: what it refused, and why. */
17
+ export declare class ScheduleStoreError extends Error {
18
+ code: 'INVALID_SCHEDULE' | 'SCHEDULE_NOT_FOUND' | 'SCHEDULE_NOT_PENDING';
19
+ constructor(code: 'INVALID_SCHEDULE' | 'SCHEDULE_NOT_FOUND' | 'SCHEDULE_NOT_PENDING', message: string);
20
+ }
21
+ /** A job as it is written and read back: the wire shape, and nothing else. */
22
+ export type ScheduleRecord = ScheduleJob;
23
+ export declare function createScheduleStore(root: string, { now }?: {
24
+ now?: (() => number) | undefined;
25
+ }): {
26
+ /** The directory the jobs live in. */
27
+ directory(): string;
28
+ /**
29
+ * A new job waiting for its time. The id is drawn here, so two jobs never
30
+ * share one and a job's own id names its delivery.
31
+ */
32
+ create({ projectRoot, sessionId, prompt, dueAt, keepsSession }: {
33
+ projectRoot: string;
34
+ sessionId: string;
35
+ prompt: string;
36
+ dueAt: string;
37
+ keepsSession?: boolean;
38
+ }): Promise<ScheduleRecord>;
39
+ /** The job of that id, or undefined when there is none. */
40
+ get(id: string, { projectRoot }?: {
41
+ projectRoot?: string;
42
+ }): Promise<ScheduleRecord | undefined>;
43
+ /** The jobs of one project, oldest first by the time they are due. */
44
+ list({ projectRoot, status }: {
45
+ projectRoot: string;
46
+ status?: ScheduleStatus;
47
+ }): Promise<ScheduleRecord[]>;
48
+ /**
49
+ * Every job of the host, of every project. Only the daemon's own tick reads them
50
+ * all; a client reads the jobs of its own project (list).
51
+ */
52
+ all({ status }?: {
53
+ status?: ScheduleStatus;
54
+ }): Promise<ScheduleRecord[]>;
55
+ /** The jobs that are due at that time and still wait. */
56
+ due(at: number): Promise<ScheduleRecord[]>;
57
+ /**
58
+ * Changes the fields of a job under the store's own lock: the job is read and
59
+ * written in one step, so a change made elsewhere in between (a cancel) is not
60
+ * overwritten. The change is skipped when it returns nothing, and nothing is
61
+ * written then; undefined says the change was not made.
62
+ */
63
+ change(id: string, change: (job: ScheduleRecord) => Partial<ScheduleRecord> | undefined): Promise<ScheduleRecord | undefined>;
64
+ /** A job that will not run: cancelled before its time. */
65
+ cancel(id: string, { projectRoot }?: {
66
+ projectRoot?: string;
67
+ }): Promise<ScheduleRecord>;
68
+ /** Removes a job file outright; a job that is not there is not an error. */
69
+ remove(id: string): Promise<void>;
70
+ };
@@ -0,0 +1,246 @@
1
+ // packages/daemon/src/schedules.ts
2
+ import { randomBytes } from "node:crypto";
3
+ import { realpathSync } from "node:fs";
4
+ import { mkdir, readdir, readFile, rm } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { writeAtomic } from "@anhlp/alp-core/atomic";
7
+ import { createLogger } from "@anhlp/alp-core/log";
8
+ var log = createLogger({ component: "alpd.schedule" });
9
+ var SCHEDULE_VERSION = 1;
10
+ var SCHEDULE_ID = /^sch_[0-9a-f]{16}$/;
11
+ var PROMPT_CHARS = 8e3;
12
+ var STATUSES = ["pending", "delivered", "failed", "cancelled"];
13
+ function projectKey(root) {
14
+ const resolved = path.resolve(root);
15
+ try {
16
+ return realpathSync.native(resolved);
17
+ } catch {
18
+ return resolved;
19
+ }
20
+ }
21
+ function namedProject(root) {
22
+ if (root === void 0) return void 0;
23
+ if (!path.isAbsolute(root)) throw new ScheduleStoreError("INVALID_SCHEDULE", "A project is named by its absolute path");
24
+ return root;
25
+ }
26
+ var ScheduleStoreError = class extends Error {
27
+ constructor(code, message) {
28
+ super(message);
29
+ this.code = code;
30
+ this.name = "ScheduleStoreError";
31
+ }
32
+ };
33
+ var isStatus = (value) => typeof value === "string" && STATUSES.includes(value);
34
+ function readJob(text, name) {
35
+ let record;
36
+ try {
37
+ record = JSON.parse(text);
38
+ } catch {
39
+ log.warn(`skipped unreadable job ${name}`, { code: "ALP_SCHEDULE_UNREADABLE", file: name });
40
+ return void 0;
41
+ }
42
+ const isTime = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value));
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
+ 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)) && (record.keepsSession === void 0 || record.keepsSession === false);
46
+ if (!sound) {
47
+ log.warn(`skipped invalid job ${name}`, { code: "ALP_SCHEDULE_UNREADABLE", file: name });
48
+ return void 0;
49
+ }
50
+ return {
51
+ id: record.id,
52
+ projectRoot: record.projectRoot,
53
+ sessionId: record.sessionId,
54
+ prompt: record.prompt,
55
+ dueAt: record.dueAt,
56
+ status: record.status,
57
+ attempts: Number.isSafeInteger(record.attempts) ? record.attempts : 0,
58
+ createdAt: record.createdAt,
59
+ updatedAt: record.updatedAt,
60
+ ...record.attemptedAt === void 0 ? {} : { attemptedAt: record.attemptedAt },
61
+ ...record.deliveredAt === void 0 ? {} : { deliveredAt: record.deliveredAt },
62
+ ...record.failedAt === void 0 ? {} : { failedAt: record.failedAt },
63
+ ...record.cancelledAt === void 0 ? {} : { cancelledAt: record.cancelledAt },
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 } } },
66
+ ...record.keepsSession === false ? { keepsSession: false } : {}
67
+ };
68
+ }
69
+ function without(value) {
70
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
71
+ }
72
+ function createScheduleStore(root, { now = () => Date.now() } = {}) {
73
+ const directory = root;
74
+ let ready;
75
+ const prepare = () => ready ??= mkdir(directory, { recursive: true, mode: 448 }).then(() => {
76
+ }, (error) => {
77
+ ready = void 0;
78
+ throw error;
79
+ });
80
+ let writes = Promise.resolve();
81
+ const serial = (work) => {
82
+ const run = writes.catch(() => {
83
+ }).then(work);
84
+ writes = run;
85
+ return run;
86
+ };
87
+ const fileOf = (id) => path.join(directory, `${id}.json`);
88
+ const fileOfSafe = (id) => typeof id === "string" && SCHEDULE_ID.test(id) ? fileOf(id) : void 0;
89
+ const writeNow = async (job) => {
90
+ await prepare();
91
+ if (!path.isAbsolute(job.projectRoot)) throw new ScheduleStoreError("INVALID_SCHEDULE", "A project is named by its absolute path");
92
+ const canonical = { ...job, projectRoot: projectKey(job.projectRoot) };
93
+ await writeAtomic(fileOf(job.id), `${JSON.stringify({ version: SCHEDULE_VERSION, ...canonical })}
94
+ `);
95
+ return canonical;
96
+ };
97
+ const write = (job) => serial(() => writeNow(job));
98
+ const stamp = () => new Date(now()).toISOString();
99
+ return {
100
+ /** The directory the jobs live in. */
101
+ directory() {
102
+ return directory;
103
+ },
104
+ /**
105
+ * A new job waiting for its time. The id is drawn here, so two jobs never
106
+ * share one and a job's own id names its delivery.
107
+ */
108
+ async create({ projectRoot, sessionId, prompt, dueAt, keepsSession }) {
109
+ if (typeof projectRoot !== "string" || !projectRoot) throw new ScheduleStoreError("INVALID_SCHEDULE", "A job needs the project it continues");
110
+ if (!path.isAbsolute(projectRoot)) throw new ScheduleStoreError("INVALID_SCHEDULE", "A job needs the absolute path of the project it continues");
111
+ if (typeof sessionId !== "string" || !sessionId) throw new ScheduleStoreError("INVALID_SCHEDULE", "A job needs the session it continues");
112
+ if (typeof prompt !== "string" || !prompt.trim()) throw new ScheduleStoreError("INVALID_SCHEDULE", "A job needs a prompt");
113
+ if ([...prompt].length > PROMPT_CHARS) throw new ScheduleStoreError("INVALID_SCHEDULE", `A job's prompt is at most ${PROMPT_CHARS} characters`);
114
+ const due = new Date(dueAt);
115
+ if (Number.isNaN(due.getTime())) throw new ScheduleStoreError("INVALID_SCHEDULE", "A job needs the time it is due, as a timestamp");
116
+ const id = `sch_${randomBytes(8).toString("hex")}`;
117
+ const at = stamp();
118
+ return write({
119
+ id,
120
+ projectRoot,
121
+ sessionId,
122
+ prompt,
123
+ dueAt: due.toISOString(),
124
+ status: "pending",
125
+ attempts: 0,
126
+ createdAt: at,
127
+ updatedAt: at,
128
+ ...keepsSession === false ? { keepsSession: false } : {}
129
+ });
130
+ },
131
+ /** The job of that id, or undefined when there is none. */
132
+ async get(id, { projectRoot } = {}) {
133
+ const wanted = namedProject(projectRoot);
134
+ const file = fileOfSafe(id);
135
+ if (!file) return void 0;
136
+ await prepare();
137
+ let text;
138
+ try {
139
+ text = await readFile(file, "utf8");
140
+ } catch (error) {
141
+ if (error?.code === "ENOENT") return void 0;
142
+ throw error;
143
+ }
144
+ const job = readJob(text, `${id}.json`);
145
+ if (job && wanted !== void 0 && projectKey(job.projectRoot) !== projectKey(wanted)) return void 0;
146
+ return job;
147
+ },
148
+ /** The jobs of one project, oldest first by the time they are due. */
149
+ async list({ projectRoot, status }) {
150
+ await prepare();
151
+ const wanted = namedProject(projectRoot);
152
+ if (status !== void 0 && !isStatus(status)) throw new ScheduleStoreError("INVALID_SCHEDULE", `Unknown job status ${String(status)}`);
153
+ const key = projectKey(wanted);
154
+ const jobs = [];
155
+ for (const name of await readdir(directory).catch((error) => {
156
+ if (error?.code === "ENOENT") return [];
157
+ throw error;
158
+ })) {
159
+ if (!name.endsWith(".json")) continue;
160
+ let job;
161
+ try {
162
+ job = readJob(await readFile(path.join(directory, name), "utf8"), name);
163
+ } catch {
164
+ continue;
165
+ }
166
+ if (!job) continue;
167
+ if (projectKey(job.projectRoot) !== key) continue;
168
+ if (status !== void 0 && job.status !== status) continue;
169
+ jobs.push(job);
170
+ }
171
+ return jobs.sort((a, b) => Date.parse(a.dueAt) - Date.parse(b.dueAt) || a.id.localeCompare(b.id));
172
+ },
173
+ /**
174
+ * Every job of the host, of every project. Only the daemon's own tick reads them
175
+ * all; a client reads the jobs of its own project (list).
176
+ */
177
+ async all({ status } = {}) {
178
+ await prepare();
179
+ if (status !== void 0 && !isStatus(status)) throw new ScheduleStoreError("INVALID_SCHEDULE", `Unknown job status ${String(status)}`);
180
+ const jobs = [];
181
+ for (const name of await readdir(directory).catch((error) => {
182
+ if (error?.code === "ENOENT") return [];
183
+ throw error;
184
+ })) {
185
+ if (!name.endsWith(".json")) continue;
186
+ let job;
187
+ try {
188
+ job = readJob(await readFile(path.join(directory, name), "utf8"), name);
189
+ } catch {
190
+ continue;
191
+ }
192
+ if (!job) continue;
193
+ if (status !== void 0 && job.status !== status) continue;
194
+ jobs.push(job);
195
+ }
196
+ return jobs.sort((a, b) => Date.parse(a.dueAt) - Date.parse(b.dueAt) || a.id.localeCompare(b.id));
197
+ },
198
+ /** The jobs that are due at that time and still wait. */
199
+ async due(at) {
200
+ const jobs = await this.all({ status: "pending" });
201
+ return jobs.filter((job) => Date.parse(job.dueAt) <= at);
202
+ },
203
+ /**
204
+ * Changes the fields of a job under the store's own lock: the job is read and
205
+ * written in one step, so a change made elsewhere in between (a cancel) is not
206
+ * overwritten. The change is skipped when it returns nothing, and nothing is
207
+ * written then; undefined says the change was not made.
208
+ */
209
+ async change(id, change) {
210
+ return serial(async () => {
211
+ const job = await this.get(id);
212
+ if (!job) return void 0;
213
+ const patch = change(job);
214
+ if (!patch) return void 0;
215
+ const merged = { ...job, ...patch };
216
+ return writeNow({ ...merged, updatedAt: stamp() });
217
+ });
218
+ },
219
+ /** A job that will not run: cancelled before its time. */
220
+ async cancel(id, { projectRoot } = {}) {
221
+ return serial(async () => {
222
+ const job = await this.get(id, { projectRoot });
223
+ if (!job) throw new ScheduleStoreError("SCHEDULE_NOT_FOUND", `No scheduled job ${id}`);
224
+ if (job.status !== "pending") throw new ScheduleStoreError("SCHEDULE_NOT_PENDING", `Job ${id} is already ${job.status}`);
225
+ return writeNow(without({ ...job, status: "cancelled", cancelledAt: stamp(), lastError: void 0 }));
226
+ });
227
+ },
228
+ /** Removes a job file outright; a job that is not there is not an error. */
229
+ async remove(id) {
230
+ const file = fileOfSafe(id);
231
+ if (!file) return;
232
+ await serial(async () => {
233
+ await prepare();
234
+ await rm(file, { force: true });
235
+ });
236
+ }
237
+ };
238
+ }
239
+ export {
240
+ PROMPT_CHARS,
241
+ SCHEDULE_ID,
242
+ SCHEDULE_VERSION,
243
+ ScheduleStoreError,
244
+ createScheduleStore,
245
+ projectKey
246
+ };
package/dist/server.d.ts CHANGED
@@ -1,8 +1,10 @@
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';
6
+ import { type AttachmentStoreOptions } from './attachments.js';
7
+ import { type TerminalServiceOptions } from './terminals.js';
6
8
  /** What clients need from a daemon connection; AlpClient implements it over the socket. */
7
9
  import type { DaemonConnection } from '@anhlp/alp-protocol/connection';
8
10
  export type { DaemonConnection } from '@anhlp/alp-protocol/connection';
@@ -25,7 +27,9 @@ export type DaemonServer = {
25
27
  /** A session as clients list it: its last snapshot plus lifecycle (ALPD §18). The protocol owns the
26
28
  * shape so every viewer agrees; re-exported here to keep `@anhlp/alp-daemon/server`'s API. */
27
29
  export type { SessionSummary };
28
- export declare function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs, home, templates }: {
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;
29
33
  runtime: AlpRuntime;
30
34
  socketPath: string;
31
35
  version: string;
@@ -45,4 +49,12 @@ export declare function createDaemonServer({ runtime, socketPath, version, onShu
45
49
  home?: OperationsOptions['home'];
46
50
  /** ALP's built-in agents and teams, for the library and team methods. */
47
51
  templates?: OperationsOptions['templates'];
52
+ /** How often the scheduler looks for jobs whose time has come; tests shorten it. */
53
+ scheduleTickMs?: number;
54
+ /** How long a job's delivery may take; tests shorten it. */
55
+ scheduleDeliveryTimeoutMs?: number;
56
+ /** Lower attachment limits (an operator's, never higher than ATTACHMENTS) and test hooks. */
57
+ attachmentOptions?: Partial<Pick<AttachmentStoreOptions, 'limits' | 'now' | 'io' | 'sweepMs'>>;
58
+ /** Lower terminal limits (never higher than TERMINAL or the operator's) and test hooks. */
59
+ terminalOptions?: Partial<Pick<TerminalServiceOptions, 'limits' | 'now' | 'spawn' | 'processes' | 'sweepMs' | 'killGraceMs' | 'maxBufferedBytes' | 'platform'>>;
48
60
  }): DaemonServer;