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

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 (51) hide show
  1. package/README.md +4 -0
  2. package/dist/alpd.js +10350 -3346
  3. package/dist/attachments.d.ts +211 -0
  4. package/dist/attachments.js +819 -0
  5. package/dist/build-manifest.json +21 -1
  6. package/dist/conversation.d.ts +119 -0
  7. package/dist/conversation.js +672 -0
  8. package/dist/files.d.ts +13 -0
  9. package/dist/files.js +15 -0
  10. package/dist/git.d.ts +87 -0
  11. package/dist/git.js +1093 -0
  12. package/dist/gitignore.d.ts +5 -0
  13. package/dist/gitignore.js +7 -1
  14. package/dist/history.d.ts +24 -0
  15. package/dist/history.js +149 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.js +18 -1
  18. package/dist/lifecycle.d.ts +101 -0
  19. package/dist/lifecycle.js +239 -0
  20. package/dist/main.js +9 -3
  21. package/dist/registry.d.ts +89 -0
  22. package/dist/registry.js +343 -0
  23. package/dist/scheduler.d.ts +96 -0
  24. package/dist/scheduler.js +290 -0
  25. package/dist/schedules.d.ts +69 -0
  26. package/dist/schedules.js +244 -0
  27. package/dist/server.d.ts +11 -1
  28. package/dist/server.js +698 -76
  29. package/dist/store.d.ts +69 -1
  30. package/dist/store.js +109 -3
  31. package/dist/terminals.d.ts +157 -0
  32. package/dist/terminals.js +487 -0
  33. package/dist/worktrees.d.ts +41 -0
  34. package/dist/worktrees.js +246 -0
  35. package/package.json +64 -5
  36. package/src/attachments.ts +870 -0
  37. package/src/conversation.ts +837 -0
  38. package/src/files.ts +23 -2
  39. package/src/git.ts +1045 -0
  40. package/src/gitignore.ts +10 -0
  41. package/src/history.ts +118 -0
  42. package/src/index.ts +6 -0
  43. package/src/lifecycle.ts +283 -0
  44. package/src/main.ts +9 -3
  45. package/src/registry.ts +238 -0
  46. package/src/scheduler.ts +422 -0
  47. package/src/schedules.ts +294 -0
  48. package/src/server.ts +810 -86
  49. package/src/store.ts +115 -3
  50. package/src/terminals.ts +591 -0
  51. package/src/worktrees.ts +287 -0
@@ -0,0 +1,89 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ export type ProjectRecord = {
3
+ id: string;
4
+ root: string;
5
+ canonical?: string;
6
+ customName?: string | null;
7
+ addedAt: string;
8
+ removedAt?: string | null;
9
+ };
10
+ export type WorkspaceRecord = {
11
+ id: string;
12
+ projectId: string;
13
+ directory: string;
14
+ canonical?: string;
15
+ title?: string | null;
16
+ pinnedAt?: string | null;
17
+ labels: string[];
18
+ createdAt: string;
19
+ archivedAt?: string | null;
20
+ idempotencyKey?: string;
21
+ worktree?: ManagedWorktree;
22
+ };
23
+ export type ManagedWorktree = {
24
+ kind: 'user';
25
+ sourceWorkspaceId: string;
26
+ source: string;
27
+ commonDir: string;
28
+ gitDir: string;
29
+ mappingId: string;
30
+ principalId: string;
31
+ grantEpoch: string;
32
+ requestId?: string;
33
+ ifRevision?: number;
34
+ branch: string;
35
+ head: string;
36
+ removedAt?: string;
37
+ };
38
+ export type Registry = {
39
+ version: 1;
40
+ revision: number;
41
+ projects: ProjectRecord[];
42
+ workspaces: WorkspaceRecord[];
43
+ sessions: Record<string, string>;
44
+ labels: {
45
+ generation: string;
46
+ seq: number;
47
+ catalog: {
48
+ name: string;
49
+ color: string;
50
+ }[];
51
+ };
52
+ worktreeJournal?: Record<string, {
53
+ fingerprint: string;
54
+ intent: any;
55
+ }>;
56
+ receipts: Record<string, {
57
+ fingerprint: string;
58
+ result: unknown;
59
+ }>;
60
+ };
61
+ export declare class RegistryError extends Error {
62
+ readonly code: number;
63
+ readonly data: {
64
+ reason: string;
65
+ };
66
+ constructor(code: number, message: string, data: {
67
+ reason: string;
68
+ });
69
+ }
70
+ /** Sole mutable owner. Failed writes never publish the draft or consume a requestId. */
71
+ export declare function createRegistry(home: string, options?: {
72
+ write?: typeof writeFile;
73
+ }): {
74
+ /** Native intent and receipt share the sole registry writer and atomic persistence boundary. */
75
+ nativeMutation: (method: string, args: any, context: {
76
+ actor: string;
77
+ requestId: string;
78
+ ifRevision: number;
79
+ }, prepare: (r: Registry) => Promise<any>, apply: (intent: any, draft: Registry) => Promise<any>) => Promise<any>;
80
+ snapshot: () => Promise<Registry>;
81
+ mutate: (method: string, args: any, context: {
82
+ actor?: string;
83
+ allowedRoots?: string[];
84
+ ifRevision?: number;
85
+ requestId: string;
86
+ }) => Promise<any>;
87
+ resolve(workspaceId: string, cwd?: string, includeArchived?: boolean): Promise<string>;
88
+ };
89
+ export type RegistryService = ReturnType<typeof createRegistry>;
@@ -0,0 +1,343 @@
1
+ // packages/daemon/src/registry.ts
2
+ import { randomBytes, createHash } from "node:crypto";
3
+ import { mkdir, readFile, writeFile, rename, realpath, stat, chmod, unlink } from "node:fs/promises";
4
+ import path from "node:path";
5
+ var RegistryError = class extends Error {
6
+ constructor(code, message, data) {
7
+ super(message);
8
+ this.code = code;
9
+ this.data = data;
10
+ }
11
+ };
12
+ function fail(reason, message, code = 1004) {
13
+ throw new RegistryError(code, message, { reason });
14
+ }
15
+ var hex = () => randomBytes(8).toString("hex");
16
+ var now = () => (/* @__PURE__ */ new Date()).toISOString();
17
+ var object = (v) => v && typeof v === "object" && !Array.isArray(v);
18
+ var nullable = (v) => v === void 0 || v === null || typeof v === "string";
19
+ var labelColors = /* @__PURE__ */ new Set(["violet", "sky", "emerald", "orange", "pink", "indigo", "teal", "red", "amber", "blue"]);
20
+ var strings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
21
+ function validate(value) {
22
+ if (!object(value) || !Array.isArray(value.projects) || !Array.isArray(value.workspaces) || !object(value.sessions) || !object(value.labels) || typeof value.labels.generation !== "string" || !Number.isSafeInteger(value.labels.seq) || value.labels.seq < 0 || !Array.isArray(value.labels.catalog) || value.labels.catalog.some((l) => !object(l) || typeof l.name !== "string" || !labelColors.has(l.color)) || value.version !== void 0 && value.version !== 1 || value.revision !== void 0 && (!Number.isSafeInteger(value.revision) || value.revision < 0)) fail("corrupt_registry", "Invalid workspace registry", 1005);
23
+ if (value.version === 1 && (!Number.isSafeInteger(value.revision) || !object(value.receipts))) fail("corrupt_registry", "Missing versioned registry metadata", 1005);
24
+ if (value.worktreeJournal !== void 0 && (!object(value.worktreeJournal) || Object.values(value.worktreeJournal).some((j) => !object(j) || typeof j.fingerprint !== "string" || !object(j.intent)))) fail("corrupt_registry", "Invalid worktree journal", 1005);
25
+ for (const j of Object.values(value.worktreeJournal ?? {})) {
26
+ const i = j.intent;
27
+ if (!["create", "remove"].includes(i.method) || !/^wks_[0-9a-f]{16}$/.test(i.id) || i.branch !== `alp/workspace/${i.id}` || !["directory", "source", "commonDir"].every((k) => typeof i[k] === "string" && path.isAbsolute(i[k])) || !/^[0-9a-f]{40,64}$/.test(i.head)) fail("corrupt_registry", "Invalid native intent", 1005);
28
+ }
29
+ const projects = /* @__PURE__ */ new Set();
30
+ const workspaces = /* @__PURE__ */ new Set();
31
+ for (const p of value.projects) {
32
+ if (!object(p) || typeof p.id !== "string" || !p.id || projects.has(p.id) || typeof p.root !== "string" || !path.isAbsolute(p.root) || typeof p.addedAt !== "string" || !nullable(p.customName) || !nullable(p.removedAt) || p.canonical !== void 0 && (typeof p.canonical !== "string" || !path.isAbsolute(p.canonical))) fail("corrupt_registry", "Invalid project record", 1005);
33
+ projects.add(p.id);
34
+ }
35
+ for (const w of value.workspaces) {
36
+ if (!object(w) || typeof w.id !== "string" || !w.id || workspaces.has(w.id) || !projects.has(w.projectId) || typeof w.directory !== "string" || !path.isAbsolute(w.directory) || typeof w.createdAt !== "string" || (value.version === 1 || w.labels !== void 0) && !strings(w.labels) || !nullable(w.title) || !nullable(w.pinnedAt) || !nullable(w.archivedAt) || w.canonical !== void 0 && (typeof w.canonical !== "string" || !path.isAbsolute(w.canonical)) || w.idempotencyKey !== void 0 && typeof w.idempotencyKey !== "string") fail("corrupt_registry", "Invalid workspace record", 1005);
37
+ if (w.worktree !== void 0 && (!object(w.worktree) || w.worktree.kind !== "user" || ["sourceWorkspaceId", "source", "commonDir", "gitDir", "mappingId", "principalId", "grantEpoch", "branch", "head"].some((k) => typeof w.worktree[k] !== "string"))) fail("corrupt_registry", "Invalid managed worktree", 1005);
38
+ workspaces.add(w.id);
39
+ }
40
+ if (Object.values(value.sessions).some((id) => typeof id !== "string" || !workspaces.has(id))) fail("corrupt_registry", "Invalid session placement", 1005);
41
+ if (value.receipts !== void 0 && (!object(value.receipts) || Object.values(value.receipts).some((r) => !object(r) || typeof r.fingerprint !== "string" || !Object.hasOwn(r, "result")))) fail("corrupt_registry", "Invalid operation receipts", 1005);
42
+ }
43
+ var placementOf = (r, id) => Object.hasOwn(r.sessions, id) ? r.sessions[id] : void 0;
44
+ var place = (r, id, workspaceId) => Object.defineProperty(r.sessions, id, { value: workspaceId, writable: true, enumerable: true, configurable: true });
45
+ async function identity(directory) {
46
+ if (typeof directory !== "string" || !path.isAbsolute(directory)) fail("directory_not_found", "An absolute existing directory is required", -32602);
47
+ const canonical = await realpath(directory);
48
+ if (!(await stat(canonical)).isDirectory()) fail("directory_not_found", "An existing directory is required", -32602);
49
+ return canonical;
50
+ }
51
+ function createRegistry(home, options = {}) {
52
+ const file = path.join(home, "state", "web-workspaces.json");
53
+ let committed;
54
+ let tail = Promise.resolve();
55
+ const serial = (fn) => {
56
+ const result = tail.then(fn);
57
+ tail = result.catch(() => {
58
+ });
59
+ return result;
60
+ };
61
+ const write = options.write ?? writeFile;
62
+ async function persist(value) {
63
+ await mkdir(path.dirname(file), { recursive: true, mode: 448 });
64
+ await chmod(path.dirname(file), 448);
65
+ const temporary = `${file}.${hex()}.tmp`;
66
+ try {
67
+ await write(temporary, JSON.stringify(value, null, 2) + "\n", { mode: 384, flag: "wx" });
68
+ await rename(temporary, file);
69
+ } finally {
70
+ await unlink(temporary).catch(() => {
71
+ });
72
+ }
73
+ }
74
+ async function load() {
75
+ if (committed) return;
76
+ let text;
77
+ try {
78
+ text = await readFile(file, "utf8");
79
+ } catch (error) {
80
+ if (error.code !== "ENOENT") throw error;
81
+ committed = { version: 1, revision: 0, projects: [], workspaces: [], sessions: {}, labels: { generation: hex(), seq: 0, catalog: [] }, receipts: {} };
82
+ return;
83
+ }
84
+ let parsed;
85
+ try {
86
+ parsed = JSON.parse(text);
87
+ } catch {
88
+ fail("corrupt_registry", "Workspace registry is unreadable; original retained", 1005);
89
+ }
90
+ validate(parsed);
91
+ if (parsed.version === void 0) {
92
+ await writeFile(`${file}.legacy-v0.json`, text, { mode: 384, flag: "wx" }).catch((e) => {
93
+ if (e.code !== "EEXIST") throw e;
94
+ });
95
+ await chmod(`${file}.legacy-v0.json`, 384);
96
+ const migrated = { ...parsed, version: 1, revision: 0, receipts: {}, workspaces: parsed.workspaces.map((w) => ({ ...w, labels: w.labels ?? [] })) };
97
+ for (const p of migrated.projects) p.canonical = await realpath(p.root).catch(() => void 0);
98
+ for (const w of migrated.workspaces) w.canonical = await realpath(w.directory).catch(() => void 0);
99
+ await persist(migrated);
100
+ committed = migrated;
101
+ } else {
102
+ await chmod(path.dirname(file), 448);
103
+ await chmod(file, 384);
104
+ committed = parsed;
105
+ }
106
+ }
107
+ const project = (r, id) => r.projects.find((p) => p.id === id) ?? fail("not_found", "No project", 1001);
108
+ const workspace = (r, id) => r.workspaces.find((w) => w.id === id) ?? fail("not_found", "No workspace", 1001);
109
+ const live = (r, w) => !w.archivedAt && !project(r, w.projectId).removedAt;
110
+ function register(r, directory, canonical) {
111
+ let p = r.projects.find((p2) => !p2.removedAt && (p2.canonical ?? path.resolve(p2.root)) === (canonical ?? path.resolve(directory)));
112
+ if (!p) {
113
+ p = { id: `prj_${hex()}`, root: directory, ...canonical === void 0 ? {} : { canonical }, addedAt: now() };
114
+ r.projects.push(p);
115
+ }
116
+ return p;
117
+ }
118
+ function makeWorkspace(r, p, directory, canonical, fields = {}) {
119
+ const w = { id: `wks_${hex()}`, projectId: p.id, directory, ...canonical === void 0 ? {} : { canonical }, labels: [], createdAt: now(), ...fields };
120
+ r.workspaces.push(w);
121
+ return w;
122
+ }
123
+ async function action(r, method, a) {
124
+ switch (method) {
125
+ case "project.add": {
126
+ const canonical = await identity(a.directory);
127
+ return { project: register(r, a.directory, canonical) };
128
+ }
129
+ case "project.register": {
130
+ const canonical = await identity(a.directory);
131
+ const p = register(r, a.directory, canonical);
132
+ if (!r.workspaces.some((w) => w.projectId === p.id && live(r, w) && (w.canonical ?? w.directory) === canonical)) makeWorkspace(r, p, a.directory, canonical);
133
+ return { project: p };
134
+ }
135
+ case "project.remove": {
136
+ const p = project(r, a.projectId);
137
+ p.removedAt = now();
138
+ for (const w of r.workspaces.filter((w2) => w2.projectId === p.id)) {
139
+ w.archivedAt = now();
140
+ w.pinnedAt = null;
141
+ }
142
+ return { project: p };
143
+ }
144
+ case "project.rename": {
145
+ const p = project(r, a.projectId);
146
+ p.customName = a.customName?.trim() || null;
147
+ return { project: p };
148
+ }
149
+ case "workspace.create": {
150
+ const canonical = await identity(a.directory);
151
+ const previous = a.idempotencyKey ? r.workspaces.find((w) => w.idempotencyKey === a.idempotencyKey) : void 0;
152
+ if (previous) {
153
+ if ((previous.canonical ?? previous.directory) !== canonical) fail("request_conflict", "Idempotency key names another directory");
154
+ return { workspace: previous };
155
+ }
156
+ const p = a.projectId ? project(r, a.projectId) : register(r, a.directory, canonical);
157
+ if (p.removedAt) fail("not_found", "Project was removed", 1001);
158
+ return { workspace: makeWorkspace(r, p, a.directory, canonical, { ...a.workspaceId ? { id: a.workspaceId } : {}, title: a.title?.trim() || null, ...a.idempotencyKey ? { idempotencyKey: a.idempotencyKey } : {} }) };
159
+ }
160
+ case "workspace.update": {
161
+ const w = workspace(r, a.workspaceId);
162
+ if (a.title !== void 0) w.title = a.title?.trim() || null;
163
+ if (a.pinned !== void 0) w.pinnedAt = a.pinned ? w.pinnedAt ?? now() : null;
164
+ if (a.archived !== void 0) {
165
+ w.archivedAt = a.archived ? now() : null;
166
+ if (a.archived) w.pinnedAt = null;
167
+ }
168
+ return { workspace: w };
169
+ }
170
+ case "placement.prepare": {
171
+ for (const s of a.sessions) {
172
+ const mapped = placementOf(r, s.id);
173
+ let w = mapped ? workspace(r, mapped) : void 0;
174
+ const historical = s.archived || s.status === "closed" || s.status === "error";
175
+ if (w) {
176
+ if (!historical && w.archivedAt) w.archivedAt = null;
177
+ continue;
178
+ }
179
+ if (typeof s.projectRoot !== "string" || !path.isAbsolute(s.projectRoot)) fail("directory_not_found", "An absolute directory is required", -32602);
180
+ const lexical = path.resolve(s.projectRoot);
181
+ const canonical = await identity(s.projectRoot).catch((error) => {
182
+ if (historical || error.code === "ENOENT" || error.code === "ENOTDIR") return void 0;
183
+ throw error;
184
+ });
185
+ const here = r.workspaces.filter((w2) => canonical === void 0 ? path.resolve(w2.directory) === lexical : (w2.canonical ?? w2.directory) === canonical).sort((a2, b) => a2.createdAt.localeCompare(b.createdAt));
186
+ w = here.find((w2) => live(r, w2)) ?? (s.archived ? here.at(-1) : void 0) ?? makeWorkspace(r, register(r, s.projectRoot, canonical), s.projectRoot, canonical, s.archived ? { archivedAt: s.updatedAt ?? now() } : {});
187
+ place(r, s.id, w.id);
188
+ }
189
+ return {};
190
+ }
191
+ case "placement.assign": {
192
+ workspace(r, a.workspaceId);
193
+ if (placementOf(r, a.sessionId) && placementOf(r, a.sessionId) !== a.workspaceId) fail("workspace_mismatch", "Session already has another workspace");
194
+ place(r, a.sessionId, a.workspaceId);
195
+ return {};
196
+ }
197
+ case "placement.remove": {
198
+ if (placementOf(r, a.sessionId) === a.workspaceId) delete r.sessions[a.sessionId];
199
+ return {};
200
+ }
201
+ case "label.assign": {
202
+ const w = workspace(r, a.workspaceId);
203
+ const name = a.label.name.trim().replace(/\s+/g, " ");
204
+ if (!name) fail("invalid_label", "A label needs a name", -32602);
205
+ let l = r.labels.catalog.find((l2) => l2.name.toLowerCase() === name.toLowerCase());
206
+ if (!l && a.assigned) {
207
+ l = { name, color: a.label.color };
208
+ r.labels.catalog.push(l);
209
+ r.labels.seq++;
210
+ }
211
+ w.labels = w.labels.filter((n) => n.toLowerCase() !== name.toLowerCase());
212
+ if (a.assigned && l) w.labels.push(l.name);
213
+ return { label: l ?? a.label, workspaceLabels: w.labels };
214
+ }
215
+ case "label.update": {
216
+ const l = r.labels.catalog.find((l2) => l2.name.toLowerCase() === a.name.toLowerCase());
217
+ if (!l) fail("not_found", "No label", 1001);
218
+ const previousName = l.name;
219
+ const name = a.newName === void 0 ? l.name : a.newName.trim().replace(/\s+/g, " ");
220
+ if (!name || r.labels.catalog.some((other) => other !== l && other.name.toLowerCase() === name.toLowerCase())) fail("label_name_taken", "Invalid or duplicate label", -32602);
221
+ l.name = name;
222
+ if (a.color) l.color = a.color;
223
+ let affectedWorkspaceCount = 0;
224
+ for (const w of r.workspaces) {
225
+ const i = w.labels.findIndex((n) => n.toLowerCase() === previousName.toLowerCase());
226
+ if (i >= 0) {
227
+ w.labels[i] = name;
228
+ affectedWorkspaceCount++;
229
+ }
230
+ }
231
+ r.labels.seq++;
232
+ return { label: l, previousName, affectedWorkspaceCount };
233
+ }
234
+ case "label.delete": {
235
+ const l = r.labels.catalog.find((l2) => l2.name.toLowerCase() === a.name.toLowerCase());
236
+ if (!l) fail("not_found", "No label", 1001);
237
+ r.labels.catalog = r.labels.catalog.filter((other) => other !== l);
238
+ let affectedWorkspaceCount = 0;
239
+ for (const w of r.workspaces) {
240
+ const before = w.labels.length;
241
+ w.labels = w.labels.filter((n) => n.toLowerCase() !== l.name.toLowerCase());
242
+ if (before !== w.labels.length) affectedWorkspaceCount++;
243
+ }
244
+ r.labels.seq++;
245
+ return { affectedWorkspaceCount };
246
+ }
247
+ default:
248
+ return fail("unknown_operation", "Unknown registry operation", -32602);
249
+ }
250
+ }
251
+ const fingerprintOf = (args, revision) => createHash("sha256").update(JSON.stringify({ args, ifRevision: revision }, (_key, value) => object(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value)).digest("hex");
252
+ return {
253
+ /** Native intent and receipt share the sole registry writer and atomic persistence boundary. */
254
+ nativeMutation: (method, args, context, prepare, apply) => serial(async () => {
255
+ await load();
256
+ if (!context.requestId || typeof context.requestId !== "string" || context.requestId.length > 200 || !Number.isSafeInteger(context.ifRevision) || context.ifRevision < 0) fail("invalid_request_id", "requestId and ifRevision are required", -32602);
257
+ const key = createHash("sha256").update(JSON.stringify([context.actor, method, context.requestId])).digest("hex");
258
+ const fingerprint = fingerprintOf(args, context.ifRevision);
259
+ const receipt = committed.receipts[key];
260
+ if (receipt) {
261
+ if (receipt.fingerprint !== fingerprint) fail("request_conflict", "requestId reused");
262
+ return structuredClone(receipt.result);
263
+ }
264
+ const pending = committed.worktreeJournal?.[key];
265
+ if (pending && pending.fingerprint !== fingerprint) fail("request_conflict", "requestId reused");
266
+ if (!pending && Object.keys(committed.worktreeJournal ?? {}).length) fail("reconciliation_required", "Retry the pending worktree request before another mutation");
267
+ if (!pending && context.ifRevision !== committed.revision) fail("stale_revision", "Registry changed; refresh");
268
+ if (!pending) {
269
+ const intent = await prepare(structuredClone(committed));
270
+ const draft2 = structuredClone(committed);
271
+ (draft2.worktreeJournal ??= {})[key] = { fingerprint, intent };
272
+ await persist(draft2);
273
+ committed = draft2;
274
+ }
275
+ const draft = structuredClone(committed);
276
+ const result = await apply(structuredClone(draft.worktreeJournal[key].intent), draft);
277
+ draft.revision++;
278
+ const response = { ...result, revision: draft.revision };
279
+ draft.receipts[key] = { fingerprint, result: structuredClone(response) };
280
+ delete draft.worktreeJournal[key];
281
+ validate(draft);
282
+ await persist(draft);
283
+ committed = draft;
284
+ return structuredClone(response);
285
+ }),
286
+ snapshot: () => serial(async () => {
287
+ await load();
288
+ return structuredClone(committed);
289
+ }),
290
+ mutate: (method, args, context) => serial(async () => {
291
+ await load();
292
+ if (Object.keys(committed.worktreeJournal ?? {}).length) fail("reconciliation_required", "Retry the pending worktree request before changing metadata");
293
+ if (context.allowedRoots) {
294
+ const checked = async (directory, canonical) => {
295
+ const actual = await identity(directory);
296
+ if (!context.allowedRoots.includes(actual) || canonical !== void 0 && canonical !== actual) fail("outside_workspace", "Resource is outside the credential grant", 1003);
297
+ };
298
+ if (method === "project.register") await checked(args.directory);
299
+ else if (method === "workspace.update") {
300
+ const w = workspace(committed, args.workspaceId);
301
+ await checked(w.directory, w.canonical);
302
+ } else if (method === "project.remove") {
303
+ const p = project(committed, args.projectId);
304
+ await checked(p.root, p.canonical);
305
+ for (const w of committed.workspaces.filter((w2) => w2.projectId === p.id)) await checked(w.directory, w.canonical);
306
+ }
307
+ }
308
+ if (!context.requestId || typeof context.requestId !== "string" || context.requestId.length > 200) fail("invalid_request_id", "requestId is required", -32602);
309
+ const key = createHash("sha256").update(JSON.stringify([context.actor ?? "owner", method, context.requestId])).digest("hex");
310
+ const fingerprint = createHash("sha256").update(JSON.stringify({ args, ifRevision: context.ifRevision }, (_key, value) => object(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value)).digest("hex");
311
+ const receipt = committed.receipts[key];
312
+ if (receipt) {
313
+ if (receipt.fingerprint !== fingerprint) fail("request_conflict", "requestId reused with different payload");
314
+ return structuredClone(receipt.result);
315
+ }
316
+ if (context.ifRevision !== void 0 && context.ifRevision !== committed.revision) fail("stale_revision", "Registry changed; refresh and retry");
317
+ const draft = structuredClone(committed);
318
+ const result = await action(draft, method, args);
319
+ if (method === "placement.prepare" && JSON.stringify(draft) === JSON.stringify(committed)) return { ...result, revision: draft.revision };
320
+ draft.revision++;
321
+ const response = { ...result, revision: draft.revision };
322
+ draft.receipts[key] = { fingerprint, result: structuredClone(response) };
323
+ validate(draft);
324
+ await persist(draft);
325
+ committed = draft;
326
+ return structuredClone(response);
327
+ }),
328
+ async resolve(workspaceId, cwd, includeArchived = false) {
329
+ const r = await this.snapshot();
330
+ const w = workspace(r, workspaceId);
331
+ if (!includeArchived && !live(r, w)) fail("not_found", "Workspace is archived", 1001);
332
+ if (Object.values(r.worktreeJournal ?? {}).some((j) => j.intent.id === workspaceId)) fail("reconciliation_required", "Workspace mutation requires reconciliation");
333
+ const canonical = await identity(w.directory);
334
+ if (w.canonical && canonical !== w.canonical) fail("identity_changed", "Workspace directory identity changed", 1003);
335
+ if (cwd !== void 0 && await identity(cwd) !== canonical) fail("cwd_mismatch", "cwd and workspaceId must agree", -32602);
336
+ return canonical;
337
+ }
338
+ };
339
+ }
340
+ export {
341
+ RegistryError,
342
+ createRegistry
343
+ };
@@ -0,0 +1,96 @@
1
+ import type { AlpRuntime } from '@anhlp/alp-runtime/index';
2
+ import type { PromptContent } from '@anhlp/alp-protocol/session';
3
+ import type { ScheduleJob } from '@anhlp/alp-protocol/index';
4
+ import type { ScheduleStore } from './schedules.js';
5
+ /** How long a job waits for a busy session before it fails; an hour by default. */
6
+ export declare const SCHEDULE_GRACE_MS: number;
7
+ /** How often alpd looks for jobs whose time has come. */
8
+ export declare const SCHEDULE_TICK_MS = 10000;
9
+ /** How long a delivery may take; a session that never answers does not hold the tick. */
10
+ export declare const DELIVERY_TIMEOUT_MS: number;
11
+ /** What the daemon's prompt path answered. */
12
+ export type ScheduleDelivery = {
13
+ outcome: 'accepted' | 'failed' | 'unknown';
14
+ error?: {
15
+ message: string;
16
+ code?: string;
17
+ };
18
+ };
19
+ export type Scheduler = ReturnType<typeof createScheduler>;
20
+ /** A delay in words: "45 seconds", "7 minutes", "1 hour 3 minutes". */
21
+ export declare function duration(ms: number): string;
22
+ /**
23
+ * The text a job delivers: the continuation, and what the session needs to know
24
+ * about it — that it was asked for, and how late it is. The text is a function of
25
+ * the job alone, so a retry after a crash sends the very same words.
26
+ */
27
+ export declare function renderPrompt(job: ScheduleJob): string;
28
+ /**
29
+ * The id of the message a job delivers under. It is the job's own, so the receipt
30
+ * of that message is what keeps the job from running twice: a retry after a crash
31
+ * reads the receipt of the first delivery instead of sending again.
32
+ */
33
+ export declare function clientMessageId(job: ScheduleJob): string;
34
+ export declare function createScheduler({ store, runtime, deliver, ready, session, settled, stopping, now, graceMs, deliveryTimeoutMs }: {
35
+ /** The job files, in `$ALP_HOME/schedules`. */
36
+ store: ScheduleStore;
37
+ /** The runtime that holds the sessions a job continues. */
38
+ runtime: AlpRuntime;
39
+ /** The daemon's prompt path: a delivery of this job, by its own clientMessageId. */
40
+ deliver: (job: ScheduleJob, content: PromptContent, clientMessageId: string, send?: AlpRuntime['prompt']) => Promise<ScheduleDelivery>;
41
+ /** The daemon's own start-up; a job waits for it, so a reopened session is ready. */
42
+ ready?: () => Promise<unknown>;
43
+ /**
44
+ * What the daemon knows about the session of a job that the runtime does not show:
45
+ * that it is being opened again, or that it could not be opened. A session that is
46
+ * being opened is not closed: the job waits for it.
47
+ */
48
+ session?: (sessionId: string) => {
49
+ opening?: boolean;
50
+ error?: {
51
+ message: string;
52
+ code?: string;
53
+ };
54
+ } | undefined;
55
+ /**
56
+ * Called when a job of that session waits for nothing any more. The daemon may keep
57
+ * something for that job alone (the reason its session could not be opened again);
58
+ * it is told the job is through, so it can drop it.
59
+ */
60
+ settled?: (sessionId: string) => void;
61
+ /** Whether the daemon is stopping; a job is not failed because alpd is going away. */
62
+ stopping?: () => boolean;
63
+ now?: () => number;
64
+ graceMs?: number;
65
+ /** How long a delivery may take before the job is failed for it. */
66
+ deliveryTimeoutMs?: number;
67
+ }): {
68
+ /** Whether a job waits for this session; such a session is kept open. */
69
+ holds(sessionId: string): boolean;
70
+ /** A job that is just being created waits for its session, before it is written. */
71
+ holdSession(sessionId: string): void;
72
+ /** The job is written; its own hold takes over. */
73
+ releaseSession(sessionId: string): void;
74
+ /** Whether a job is being delivered right now; a cancel of it is refused. */
75
+ delivering(jobId: string): boolean;
76
+ /** A job that was just created waits for its session. */
77
+ hold: (job: ScheduleJob) => void;
78
+ /** A job that will not run any more waits for nothing. */
79
+ release: (job: ScheduleJob) => void;
80
+ /** Reads the job files again. */
81
+ refresh: () => Promise<void>;
82
+ /** One pass of the tick. */
83
+ tick: () => Promise<{
84
+ delivered: number;
85
+ failed: number;
86
+ waiting: number;
87
+ }>;
88
+ /** The tick, every `everyMs`; the first pass waits for the daemon's start-up. */
89
+ start(everyMs?: number): void;
90
+ /**
91
+ * The tick stops, and the pass that runs now is waited for, up to a grace: a
92
+ * delivery that outlives the grace is left to the next alpd, whose receipt of
93
+ * the message says whether it went through.
94
+ */
95
+ stop(): Promise<void>;
96
+ };