@anhlp/alp-daemon 0.0.0-stage → 0.0.1-beta.3

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.
@@ -0,0 +1,300 @@
1
+ import { createHash, createHmac, randomBytes } from 'node:crypto';
2
+ import { lstat, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { CAPABILITY, ERROR, RPC_ERROR } from '@anhlp/alp-protocol';
5
+ import { closeTask, createTask, epicReport, loadTasks, reopenTask, resolveGate } from '@anhlp/alp-core/tasks';
6
+ import { taskRows } from '@anhlp/alp-core/task-rows';
7
+ import { deleteEntry, duplicateEntry, getEntry, listEntries, renameEntry, saveEntry, setGivenSkills } from '@anhlp/alp-core/library-edit';
8
+ import { listTeams } from '@anhlp/alp-core/teams';
9
+ import { MODELS } from '@anhlp/alp-core/models';
10
+ import { listProviders } from '@anhlp/alp-core/providers';
11
+ import { languageSetting, setLanguage, LANGUAGE_CHARS } from '@anhlp/alp-core/user-settings';
12
+ import { syncProjectSettings } from '@anhlp/alp-core/init';
13
+ import { RpcError } from './rpc-error.js';
14
+
15
+ /**
16
+ * The project, task, library and settings methods (docs/protocol/alp-json-rpc-v1.md §12, §15):
17
+ * what a client needs besides sessions, answered from the daemon host's own files so a remote
18
+ * client never reads ALP_HOME or a project. The business logic is core's; alpd resolves the
19
+ * project, serializes its own writes, maps core's refusals to protocol errors and keeps
20
+ * secrets out of what it answers. The schema has checked every param before a handler runs.
21
+ */
22
+
23
+ export type OperationsOptions = {
24
+ /** The daemon user's ALP_HOME: their library and settings.json. Without it only task.* is served. */
25
+ home?: string;
26
+ /** ALP's built-in agents and teams. */
27
+ templates?: Record<string, string>;
28
+ /** Project roots the daemon knows from its session records, for a team save's sync. */
29
+ knownProjects?: () => Iterable<string>;
30
+ };
31
+
32
+ type Handler = (params: any) => Promise<unknown>;
33
+
34
+ /** How long task.create remembers a requestId (§10): within one alpd process only. */
35
+ const REQUEST_TTL_MS = 10 * 60 * 1000;
36
+ /** At most this many remembered requestIds; the oldest go first. */
37
+ const MAX_REQUESTS = 10_000;
38
+ const MARKER = '$secret';
39
+ const KEEP = 'keep';
40
+
41
+ /** Secret-bearing maps of each kind's content: their values never leave alpd. */
42
+ const SECRET_MAPS: Record<string, string[][]> = {
43
+ mcp: [['server', 'env'], ['server', 'headers']],
44
+ providers: [['provider', 'env']],
45
+ };
46
+
47
+ const failure = (code: number, reason: string, message: string, extra: object = {}) => new RpcError(code, message, { reason, ...extra });
48
+
49
+ /** Core refusals (AlpError codes) as protocol errors; `context` decides what an ambiguous one means. */
50
+ function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry' } = {}): unknown {
51
+ if (error instanceof RpcError || typeof error?.code !== 'string' || error?.name !== 'AlpError') return error;
52
+ const message = error.message as string;
53
+ switch (error.code) {
54
+ case 'UNSAFE_LIBRARY_WRITE': return failure(ERROR.forbidden, 'library_policy', message);
55
+ case 'UNSAFE_PATH': return failure(ERROR.forbidden, 'unsafe_path', message);
56
+ case 'TASK_NOT_FOUND': return failure(ERROR.notFound, 'unknown_task', message);
57
+ case 'TASK_CHANGED': case 'REVISION_CONFLICT': return failure(ERROR.conflict, 'revision_conflict', message);
58
+ case 'INVALID_TASK': case 'TASK_CYCLE': case 'TASK_TAKEN': case 'TASK_UNVERIFIED': return failure(ERROR.conflict, 'task_state', message);
59
+ case 'TASKS_LOCKED': return failure(ERROR.unavailable, 'busy', message);
60
+ case 'IN_USE': return failure(ERROR.conflict, 'in_use', message);
61
+ case 'INVALID_SCOPE': return failure(RPC_ERROR.invalidParams, 'invalid_scope', message);
62
+ case 'INVALID_LIBRARY': case 'INVALID_SETTINGS': return failure(ERROR.failed, 'unreadable', message);
63
+ }
64
+ if (error.code === 'NOT_FOUND' || error.code.endsWith('_NOT_FOUND')) {
65
+ return context.notFound === 'invalid_entry' ? failure(RPC_ERROR.invalidParams, 'invalid_entry', message) : failure(ERROR.notFound, 'not_found', message);
66
+ }
67
+ if (error.code.startsWith('INVALID_')) return failure(RPC_ERROR.invalidParams, 'invalid_entry', message);
68
+ return error;
69
+ }
70
+
71
+ const object = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object' && !Array.isArray(value);
72
+ const pointer = (parts: string[]) => parts.map(part => `/${part.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');
73
+ const isMarker = (value: unknown) => object(value) && Object.keys(value).length === 1 && value[MARKER] === KEEP;
74
+ const at = (content: unknown, parts: string[]) => parts.reduce<any>((value, part) => object(value) ? value[part] : undefined, content);
75
+
76
+ /** A copy of an entry's content with each stored secret replaced by the marker, and where they were. */
77
+ function redact(kind: string, content: Record<string, unknown>) {
78
+ const copy = structuredClone(content);
79
+ const secrets: string[] = [];
80
+ for (const parts of SECRET_MAPS[kind] ?? []) {
81
+ const map = at(copy, parts);
82
+ if (!object(map)) continue;
83
+ for (const key of Object.keys(map)) {
84
+ if (typeof map[key] !== 'string') continue;
85
+ map[key] = { [MARKER]: KEEP };
86
+ secrets.push(pointer([...parts, key]));
87
+ }
88
+ }
89
+ return { content: copy, secrets };
90
+ }
91
+
92
+ /**
93
+ * The content a save writes: a marker keeps the value stored at its place in `previous` (the entry
94
+ * the save replaces, or the one that applies when the scope has none yet), a string replaces it, a
95
+ * missing key removes it. A marker anywhere else, or with nothing stored to keep, refuses the save,
96
+ * so a placeholder never reaches storage.
97
+ */
98
+ function unredact(kind: string, content: Record<string, unknown>, previous: Record<string, unknown> | undefined) {
99
+ const next = structuredClone(content);
100
+ for (const parts of SECRET_MAPS[kind] ?? []) {
101
+ const map = at(next, parts);
102
+ if (!object(map)) continue;
103
+ const stored = at(previous, parts);
104
+ for (const key of Object.keys(map)) {
105
+ if (!isMarker(map[key])) continue;
106
+ const value = object(stored) ? stored[key] : undefined;
107
+ if (typeof value !== 'string') throw failure(RPC_ERROR.invalidParams, 'secret_marker', `There is no stored value of ${pointer([...parts, key])} to keep; send the value instead`);
108
+ map[key] = value;
109
+ }
110
+ }
111
+ const stray = (value: unknown, parts: string[]): string | undefined => {
112
+ if (isMarker(value) || (object(value) && Object.hasOwn(value, MARKER))) return pointer(parts);
113
+ if (Array.isArray(value)) for (const [index, item] of value.entries()) { const found = stray(item, [...parts, String(index)]); if (found) return found; }
114
+ if (object(value)) for (const [key, item] of Object.entries(value)) { const found = stray(item, [...parts, key]); if (found) return found; }
115
+ return undefined;
116
+ };
117
+ const found = stray(next, []);
118
+ if (found !== undefined) throw failure(RPC_ERROR.invalidParams, 'secret_marker', `${found || 'content'} holds a secret marker where no secret is kept`);
119
+ return next;
120
+ }
121
+
122
+ export function createOperations({ home, templates, knownProjects = () => [] }: OperationsOptions = {}) {
123
+ /** Revisions on the wire are keyed per alpd process, so they never carry a hash of secret content. */
124
+ const revisionKey = randomBytes(32);
125
+ const toWire = (revision: string | null | undefined) => revision == null ? null : `r${createHmac('sha256', revisionKey).update(revision).digest('base64url').slice(0, 22)}`;
126
+ /** alpd's own writes to the library, settings and projects' .alp happen one at a time. */
127
+ let writes: Promise<unknown> = Promise.resolve();
128
+ const serial = <T>(work: () => Promise<T>): Promise<T> => {
129
+ const run = writes.catch(() => {}).then(work);
130
+ writes = run;
131
+ return run;
132
+ };
133
+ const requests = new Map<string, { fingerprint: string; at: number; result: Promise<{ id: string }> }>();
134
+
135
+ /**
136
+ * A project as params name it: an absolute, normalized path to a directory holding a real .alp
137
+ * directory. alpd never walks up to a parent, so the path a caller authorizes is the one used.
138
+ */
139
+ async function project(value: string) {
140
+ if (!path.isAbsolute(value) || path.resolve(value) !== value) throw failure(RPC_ERROR.invalidParams, 'invalid_path', 'projectRoot must be an absolute, normalized path');
141
+ if (!(await stat(value).catch(() => undefined))?.isDirectory()) throw failure(ERROR.notFound, 'not_alp_project', `${value} is not a directory`);
142
+ const alp = await lstat(path.join(value, '.alp')).catch(() => undefined);
143
+ if (alp?.isSymbolicLink()) throw failure(ERROR.forbidden, 'unsafe_path', `${path.join(value, '.alp')} is a symlink`);
144
+ if (!alp?.isDirectory()) throw failure(ERROR.notFound, 'not_alp_project', `${value} is not an ALP project; run alp init there`);
145
+ return value;
146
+ }
147
+
148
+ async function where(projectRoot: string | undefined, scope?: string) {
149
+ if (scope === 'project' && projectRoot === undefined) throw failure(RPC_ERROR.invalidParams, 'invalid_scope', 'scope project needs projectRoot');
150
+ return { root: projectRoot === undefined ? undefined : await project(projectRoot), library: home, templates };
151
+ }
152
+
153
+ /** One layer's version of an entry, or undefined. */
154
+ async function layer(kind: string, name: string, options: object, scope?: string) {
155
+ try { return await getEntry(kind as any, name, { ...options, ...(scope ? { scope } : {}) } as any); }
156
+ catch (error: any) { if (error?.code === 'NOT_FOUND') return undefined; throw error; }
157
+ }
158
+
159
+ const guard = (handler: Handler, context?: Parameters<typeof fromCore>[1]): Handler => async params => {
160
+ try { return await handler(params); }
161
+ catch (error) { throw fromCore(error, context); }
162
+ };
163
+
164
+ const taskHandlers: Record<string, Handler> = {
165
+ 'task.list': guard(async ({ projectRoot }) => {
166
+ const root = await project(projectRoot);
167
+ const { tasks, unreadable } = await taskRows(root);
168
+ return { projectRoot: root, tasks, unreadable, revision: createHash('sha256').update(JSON.stringify([tasks, unreadable])).digest('hex').slice(0, 16) };
169
+ }),
170
+
171
+ 'task.create': guard(async ({ projectRoot, title, priority, requestId }) => {
172
+ const root = await project(projectRoot);
173
+ const create = () => createTask(root, { title: title.trim(), ...(priority !== undefined ? { priority } : {}) }, 'user').then(task => ({ id: task.id }));
174
+ if (requestId === undefined) return create();
175
+ const now = Date.now();
176
+ for (const [key, entry] of requests) if (now - entry.at > REQUEST_TTL_MS) requests.delete(key);
177
+ const key = JSON.stringify([root, requestId]);
178
+ const fingerprint = JSON.stringify([title.trim(), priority ?? null]);
179
+ const existing = requests.get(key);
180
+ if (existing) {
181
+ if (existing.fingerprint !== fingerprint) throw failure(ERROR.conflict, 'key_conflict', `Request ${requestId} was already used for another task`);
182
+ return { ...await existing.result, duplicate: true as const };
183
+ }
184
+ const result = create();
185
+ if (requests.size >= MAX_REQUESTS) requests.delete(requests.keys().next().value!);
186
+ requests.set(key, { fingerprint, at: now, result });
187
+ // A create that failed made nothing: the same requestId may try again.
188
+ result.catch(() => { if (requests.get(key)?.result === result) requests.delete(key); });
189
+ return result;
190
+ }),
191
+
192
+ 'task.update': guard(async ({ projectRoot, id, action, note, ifRev }) => {
193
+ const root = await project(projectRoot);
194
+ const options = ifRev !== undefined ? { ifRev } : undefined;
195
+ if (action === 'reopen') {
196
+ const task = await reopenTask(root, id, { ...(note ? { note } : {}) }, 'user', options);
197
+ return { id: task.id, status: task.status, rev: task.rev };
198
+ }
199
+ const task = await closeTask(root, id, { reason: 'done', ...(note ? { summary: note } : {}) }, 'user', options);
200
+ const { tasks } = await loadTasks(root);
201
+ const landed = tasks.some(entry => entry.parent === task.id) ? epicReport(task.id, tasks).text.split('\n')[0] : undefined;
202
+ return { id: task.id, status: task.status, rev: task.rev, ...(landed ? { landed } : {}) };
203
+ }),
204
+
205
+ 'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev }) => {
206
+ const root = await project(projectRoot);
207
+ const task = await resolveGate(root, id, gate, { by: 'user', ...(note ? { note } : {}), ...(ifRev !== undefined ? { ifRev } : {}) });
208
+ return { id: task.id, status: task.status, rev: task.rev };
209
+ }),
210
+ };
211
+
212
+ const libraryHandlers: Record<string, Handler> = {
213
+ 'team.list': guard(async ({ projectRoot }) => {
214
+ const { root } = await where(projectRoot);
215
+ const teams = await listTeams(root, { library: home, templates });
216
+ return { projectRoot: root ?? null, teams: teams.map(({ path: _path, ...team }) => team) };
217
+ }),
218
+
219
+ 'library.list': guard(async ({ kind, projectRoot }) => {
220
+ const options = await where(projectRoot);
221
+ const entries = await listEntries(kind, options);
222
+ return { projectRoot: options.root ?? null, entries: entries.map(({ path: _path, ...entry }: any) => entry) };
223
+ }),
224
+
225
+ 'library.get': guard(async ({ kind, name, projectRoot, scope }) => {
226
+ const options = await where(projectRoot, scope);
227
+ const entry = await getEntry(kind, name, { ...options, ...(scope ? { scope } : {}) });
228
+ const { content, secrets } = redact(kind, entry.content);
229
+ return { ...entry, content, revision: toWire(entry.revision), ...(secrets.length ? { secrets } : {}) };
230
+ }),
231
+
232
+ 'library.save': guard(({ kind, name, scope, projectRoot, content, revision, policy, sync = 'none' }) => serial(async () => {
233
+ if (policy === 'project-data' && sync !== 'none') throw failure(ERROR.forbidden, 'library_policy', 'Project-data writes cannot synchronize projects');
234
+ const options = await where(projectRoot, scope);
235
+ const current = await layer(kind, name, options, scope);
236
+ if (revision !== undefined && revision !== toWire(current?.revision ?? null)) {
237
+ throw failure(ERROR.conflict, 'revision_conflict', current === undefined ? `${kind} '${name}' is not in the ${scope}` : revision === null ? `${kind} '${name}' already exists in the ${scope}` : `${kind} '${name}' changed in the ${scope} since you opened it; reload it and apply your change again`);
238
+ }
239
+ const previous = current?.content ?? (await layer(kind, name, options))?.content;
240
+ const next = unredact(kind, content, previous);
241
+ // Core checks the revision again as it writes, against writers outside alpd.
242
+ const saved = await saveEntry(kind, name, next, { ...options, scope, policy, ...(revision !== undefined ? { revision: current?.revision ?? null } : {}) });
243
+ if (kind !== 'teams' || sync !== 'known-projects') return { revision: toWire(saved.revision) };
244
+ const roots = new Set<string>(options.root ? [options.root] : []);
245
+ if (scope === 'library') for (const root of knownProjects()) if (typeof root === 'string' && path.isAbsolute(root)) roots.add(path.resolve(root));
246
+ let syncedProjects = 0;
247
+ const syncErrors: string[] = [];
248
+ for (const root of roots) {
249
+ try { if (await syncProjectSettings(root, { library: home, templates, teamIds: [name], replaceModels: true })) syncedProjects += 1; }
250
+ catch (error) { syncErrors.push(`${root}: ${error instanceof Error ? error.message : String(error)}`); }
251
+ }
252
+ return { revision: toWire(saved.revision), syncedProjects, syncErrors };
253
+ }), { notFound: 'invalid_entry' }),
254
+
255
+ 'library.delete': guard(({ kind, name, scope, projectRoot, revision, policy }) => serial(async () => {
256
+ const options = await where(projectRoot, scope);
257
+ const current = await layer(kind, name, options, scope);
258
+ if (!current) throw failure(ERROR.notFound, 'not_found', `No ${kind} entry '${name}' in the ${scope}`);
259
+ if (revision !== undefined && revision !== toWire(current.revision)) throw failure(ERROR.conflict, 'revision_conflict', `${kind} '${name}' changed in the ${scope} since you opened it`);
260
+ return deleteEntry(kind, name, { ...options, scope, policy, ...(revision !== undefined ? { revision: current.revision } : {}) });
261
+ })),
262
+
263
+ 'library.duplicate': guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
264
+ const options = await where(projectRoot, scope);
265
+ try { await getEntry(kind, from, options); }
266
+ catch (error) { throw fromCore(error, { notFound: 'not_found' }); }
267
+ return { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope, policy })).revision) };
268
+ }), { notFound: 'invalid_entry' }),
269
+
270
+ 'library.rename': guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
271
+ const options = await where(projectRoot, scope);
272
+ return { revision: toWire((await renameEntry(kind, from, to, { ...options, scope, policy })).revision) };
273
+ })),
274
+
275
+ 'library.skills.set': guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: 'invalid_entry' }),
276
+
277
+ 'library.models': guard(async () => {
278
+ const models: Array<{ id: string; label: string; efforts: string[]; effort?: string }> = MODELS.map(model => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} · ${model.label}`, efforts: model.efforts, ...(model.effort ? { effort: model.effort } : {}) }));
279
+ for (const provider of await listProviders(home)) {
280
+ if (provider.enabled === false || provider.kind === 'antigravity') continue;
281
+ models.push({ id: `acp:${provider.id}`, label: `${provider.label} · Provider default`, efforts: [] });
282
+ for (const model of [...(provider.models ?? []), ...(provider.additionalModels ?? [])]) models.push({ id: `acp:${provider.id}/${model.id}`, label: `${provider.label} · ${model.label ?? model.id}`, efforts: [] });
283
+ }
284
+ return { models: [...new Map(models.map(model => [model.id, model])).values()] };
285
+ }),
286
+
287
+ 'settings.language.get': guard(async () => languageSetting(home!)),
288
+
289
+ 'settings.language.set': guard(async ({ language }) => {
290
+ if (language !== null && language.trim().length > LANGUAGE_CHARS) throw failure(RPC_ERROR.invalidParams, 'invalid_params', `A language is a name of at most ${LANGUAGE_CHARS} characters`);
291
+ return serial(() => setLanguage(home!, language));
292
+ }),
293
+ };
294
+
295
+ const library = home !== undefined;
296
+ return {
297
+ handlers: { ...taskHandlers, ...(library ? libraryHandlers : {}) },
298
+ capabilities: [CAPABILITY.task, ...(library ? [CAPABILITY.team, CAPABILITY.library, CAPABILITY.libraryProjectWrite, CAPABILITY.settingsLanguage] : [])],
299
+ };
300
+ }
@@ -0,0 +1,4 @@
1
+ /** An error alpd answers with as is: its code, message and `data` (docs/protocol/alp-json-rpc-v1.md §5). */
2
+ export class RpcError extends Error {
3
+ constructor(public code: number, message: string, public data?: unknown) { super(message); }
4
+ }