@anhlp/alp-daemon 0.0.0-beta.1 → 0.0.0-stage
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.
- package/README.md +2 -10
- package/package.json +4 -92
- package/LICENSE +0 -202
- package/NOTICE +0 -7
- package/dist/THIRD-PARTY-NOTICES.txt +0 -431
- package/dist/alp-templates.d.ts +0 -5
- package/dist/alpd.js +0 -41053
- package/dist/build-manifest.json +0 -108
- package/dist/index.d.ts +0 -4
- package/dist/index.js +0 -8
- package/dist/lock.d.ts +0 -21
- package/dist/lock.js +0 -42
- package/dist/main.d.ts +0 -1
- package/dist/main.js +0 -238
- package/dist/operations.d.ts +0 -23
- package/dist/operations.js +0 -272
- package/dist/rpc-error.d.ts +0 -6
- package/dist/rpc-error.js +0 -11
- package/dist/server.d.ts +0 -48
- package/dist/server.js +0 -1020
- package/dist/store.d.ts +0 -108
- package/dist/store.js +0 -279
- package/src/alp-templates.d.ts +0 -5
- package/src/index.ts +0 -5
- package/src/lock.ts +0 -53
- package/src/main.ts +0 -250
- package/src/operations.ts +0 -298
- package/src/rpc-error.ts +0 -4
- package/src/server.ts +0 -1159
- package/src/store.ts +0 -336
package/src/main.ts
DELETED
|
@@ -1,250 +0,0 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
2
|
-
import { openSync, writeSync } from 'node:fs';
|
|
3
|
-
import { mkdir, open, readFile, rename, stat, unlink, utimes, writeFile } from 'node:fs/promises';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import { fileURLToPath } from 'node:url';
|
|
6
|
-
import templates from 'alp:templates';
|
|
7
|
-
import { alpHome, daemonPaths, assertPrivateDirectory, PROTOCOL_VERSION } from '@anhlp/alp-client/index';
|
|
8
|
-
import { createAlpRuntime, reclaimCopies, reclaimWorktrees } from '@anhlp/alp-runtime/index';
|
|
9
|
-
import { createDaemonServer } from './server.js';
|
|
10
|
-
import { acquireLock, heartbeat, releaseLock, updateLock } from './lock.js';
|
|
11
|
-
import { createStore } from './store.js';
|
|
12
|
-
import { validateUserSettings } from '@anhlp/alp-core/validation';
|
|
13
|
-
import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } from '@anhlp/alp-core/backup';
|
|
14
|
-
import { migrateState } from '@anhlp/alp-core/migrations';
|
|
15
|
-
import { createLogger } from '@anhlp/alp-core/log';
|
|
16
|
-
|
|
17
|
-
declare const __ALP_VERSION__: string;
|
|
18
|
-
const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-dev';
|
|
19
|
-
const LOG_BYTES = 10 * 1024 * 1024;
|
|
20
|
-
const LOG_FILES = 3;
|
|
21
|
-
const log = createLogger({ component: 'alpd' });
|
|
22
|
-
|
|
23
|
-
async function rotate(log: string) {
|
|
24
|
-
const size = await stat(log).then(info => info.size, () => 0);
|
|
25
|
-
if (size < LOG_BYTES) return;
|
|
26
|
-
for (let index = LOG_FILES - 1; index >= 1; index--) {
|
|
27
|
-
await rename(index === 1 ? log : `${log}.${index - 1}`, `${log}.${index}`).catch(() => {});
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** Starts the daemon in a new session and returns at once, so it is not part of the caller's process tree. */
|
|
32
|
-
async function detach(home: string) {
|
|
33
|
-
await assertPrivateDirectory(home, { create: true });
|
|
34
|
-
const { log } = daemonPaths(home);
|
|
35
|
-
await assertPrivateDirectory(path.dirname(log), { create: true });
|
|
36
|
-
await rotate(log);
|
|
37
|
-
const output = await open(log, 'a', 0o600);
|
|
38
|
-
const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {
|
|
39
|
-
detached: true,
|
|
40
|
-
stdio: ['ignore', output.fd, output.fd],
|
|
41
|
-
env: process.env,
|
|
42
|
-
windowsHide: true,
|
|
43
|
-
});
|
|
44
|
-
child.unref();
|
|
45
|
-
await output.close();
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Under a service manager (ALPD §37), which holds alpd's stdout open: alpd rotates its
|
|
50
|
-
* log at start as the detached launcher does, then writes its output there itself. The
|
|
51
|
-
* manager's own file keeps only what Node prints when it dies.
|
|
52
|
-
*/
|
|
53
|
-
async function serviceLog(home: string) {
|
|
54
|
-
await assertPrivateDirectory(home, { create: true });
|
|
55
|
-
const { log } = daemonPaths(home);
|
|
56
|
-
await assertPrivateDirectory(path.dirname(log), { create: true });
|
|
57
|
-
await rotate(log);
|
|
58
|
-
const fd = openSync(log, 'a', 0o600);
|
|
59
|
-
for (const stream of [process.stdout, process.stderr]) {
|
|
60
|
-
stream.write = ((chunk: string | Uint8Array, encoding?: unknown, callback?: unknown) => {
|
|
61
|
-
try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, chunk); } catch {}
|
|
62
|
-
const done = typeof encoding === 'function' ? encoding : callback;
|
|
63
|
-
if (typeof done === 'function') done();
|
|
64
|
-
return true;
|
|
65
|
-
}) as typeof stream.write;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* The user's alpd settings in $ALP_HOME/settings.json; none when it is missing.
|
|
71
|
-
* Invalid settings are logged and alpd starts with the defaults, so a typo never
|
|
72
|
-
* keeps it from running; alp doctor reports them too.
|
|
73
|
-
*/
|
|
74
|
-
async function userSettings(home: string): Promise<any> {
|
|
75
|
-
const file = path.join(home, 'settings.json');
|
|
76
|
-
let text: string;
|
|
77
|
-
try { text = await readFile(file, 'utf8'); } catch { return {}; }
|
|
78
|
-
try { return validateUserSettings(JSON.parse(text), file); }
|
|
79
|
-
catch (error: any) {
|
|
80
|
-
log.warn(`ignoring ${file}: ${error?.message ?? error}`, { code: 'ALP_SETTINGS_INVALID' });
|
|
81
|
-
return {};
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* How the previous alpd ended (ALPD §31). A running alpd keeps a marker file and
|
|
87
|
-
* touches it with its heartbeat; a clean stop removes it last. A marker found at
|
|
88
|
-
* start means the previous alpd crashed, around the marker's last touch.
|
|
89
|
-
*/
|
|
90
|
-
async function previousExit(marker: string): Promise<{ kind: 'clean' | 'crash'; at?: string }> {
|
|
91
|
-
const info = await stat(marker).catch(() => undefined);
|
|
92
|
-
return info ? { kind: 'crash', at: info.mtime.toISOString() } : { kind: 'clean' };
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** Whether a process group `id` exists; on POSIX a pid is never reused while its group lives. */
|
|
96
|
-
function groupAlive(id: number) {
|
|
97
|
-
try { process.kill(-id, 0); return true; } catch (error: any) { return error?.code === 'EPERM'; }
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** alpd leads its own process group when started detached or by a service manager. */
|
|
101
|
-
const leadsGroup = () => process.platform !== 'win32' && groupAlive(process.pid);
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Stops what a crashed alpd left running (ALPD §66): its provider processes normally exit
|
|
105
|
-
* when their stdin closes, but a stuck one, or a command an agent started, can outlive it.
|
|
106
|
-
* They stay in the crashed alpd's process group, so alpd ends that group when the crashed
|
|
107
|
-
* one led its group and this one leads its own (so it is not a member). Not on Windows.
|
|
108
|
-
*/
|
|
109
|
-
async function stopLeftovers(previous: { pid?: number; groupLeader?: boolean } | undefined) {
|
|
110
|
-
const pid = previous?.pid;
|
|
111
|
-
if (!previous?.groupLeader || !Number.isSafeInteger(pid) || pid === process.pid || !leadsGroup() || !groupAlive(pid!)) return;
|
|
112
|
-
log.warn(`stopping processes the previous alpd (pid ${pid}) left running`, { code: 'ALP_LEFTOVER_PROCESSES', previousPid: pid });
|
|
113
|
-
const signal = (name: NodeJS.Signals) => { try { process.kill(-pid!, name); } catch {} };
|
|
114
|
-
signal('SIGTERM');
|
|
115
|
-
for (let waited = 0; waited < 3000 && groupAlive(pid!); waited += 50) await new Promise(resolve => setTimeout(resolve, 50));
|
|
116
|
-
if (groupAlive(pid!)) signal('SIGKILL');
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/** Where start-up stands, so a failure says which step it stopped at. */
|
|
120
|
-
type Phase = 'home' | 'lock' | 'state' | 'recovery' | 'listen' | 'ready';
|
|
121
|
-
let phase: Phase = 'home';
|
|
122
|
-
const STARTUP_CODES = { home: 'ALP_HOME_UNUSABLE', lock: 'ALP_LOCK_FAILED', state: 'ALP_STATE_UNUSABLE', recovery: 'ALP_STARTUP_FAILED', listen: 'ALP_IPC_LISTEN_FAILED', ready: 'ALP_STARTUP_FAILED' } as const;
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Before anything reads or writes the state (ALPD §68): a restore cut short is settled, a
|
|
126
|
-
* state of a newer schema is refused untouched, an older one is migrated forward, and a
|
|
127
|
-
* restore's marker says to continue no work by itself this time; it is cleared once alpd is
|
|
128
|
-
* ready, so a start that fails keeps it for the next.
|
|
129
|
-
*/
|
|
130
|
-
async function openState(home: string) {
|
|
131
|
-
const settled = await recoverInterruptedRestore(home);
|
|
132
|
-
if (settled) log.warn(`a restore from ${settled.file} was cut short and has been ${settled.outcome}`, { code: 'ALP_RESTORE_SETTLED', outcome: settled.outcome });
|
|
133
|
-
const migrated = await migrateState(home, { by: `alpd ${VERSION}`, log });
|
|
134
|
-
for (const step of migrated.steps) log.info(`state migrated from schema ${step.from} to ${step.to} (${step.name}); the state before it is in ${step.backup}`, { code: 'ALP_STATE_MIGRATED', from: step.from, to: step.to, migration: step.name });
|
|
135
|
-
const restored = await readRestoredMarker(home);
|
|
136
|
-
if (restored) log.info(`state restored${restored.from ? ` from ${restored.from}` : ''}; sessions that were working wait for the user`, { code: 'ALP_STATE_RESTORED' });
|
|
137
|
-
return { restored: !!restored };
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
async function run(home: string) {
|
|
141
|
-
await assertPrivateDirectory(home, { create: true });
|
|
142
|
-
phase = 'lock';
|
|
143
|
-
const { socket } = daemonPaths(home);
|
|
144
|
-
let lock;
|
|
145
|
-
try {
|
|
146
|
-
lock = await acquireLock(home, { version: VERSION, protocolVersion: PROTOCOL_VERSION, socket });
|
|
147
|
-
} catch (error: any) {
|
|
148
|
-
// Under a service manager, another alpd serving this home is no failure to retry.
|
|
149
|
-
if (process.argv.includes('--service') && /already running|ALP is busy/.test(error?.message ?? '')) {
|
|
150
|
-
log.info(`${error.message}; this one exits`, { code: 'ALP_LOCK_HELD' });
|
|
151
|
-
process.exit(0);
|
|
152
|
-
}
|
|
153
|
-
throw error;
|
|
154
|
-
}
|
|
155
|
-
phase = 'state';
|
|
156
|
-
let opened;
|
|
157
|
-
try {
|
|
158
|
-
opened = await openState(home);
|
|
159
|
-
} catch (error) {
|
|
160
|
-
await releaseLock(home);
|
|
161
|
-
throw error;
|
|
162
|
-
}
|
|
163
|
-
phase = 'recovery';
|
|
164
|
-
// First: nothing a crashed alpd left running may still write while this one recovers.
|
|
165
|
-
const marker = path.join(home, 'state', 'alpd.running');
|
|
166
|
-
const exit = await previousExit(marker);
|
|
167
|
-
if (exit.kind === 'crash') {
|
|
168
|
-
log.warn(`the previous alpd stopped unexpectedly around ${exit.at}`, { code: 'ALP_PREVIOUS_CRASH', at: exit.at });
|
|
169
|
-
await stopLeftovers(await readFile(marker, 'utf8').then(JSON.parse).catch(() => undefined));
|
|
170
|
-
}
|
|
171
|
-
await mkdir(path.dirname(marker), { recursive: true, mode: 0o700 });
|
|
172
|
-
await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), groupLeader: leadsGroup() }), { mode: 0o600 });
|
|
173
|
-
const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home, 'runs');
|
|
174
|
-
const worktreeDir = path.join(home, 'worktrees');
|
|
175
|
-
// Worktrees of assignments a crash interrupted: their work goes to their branches.
|
|
176
|
-
for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [] as string[])) log.info(`kept interrupted work on branch ${branch}`, { event: 'worktree.kept', branch });
|
|
177
|
-
// Review copies of interrupted assignments hold nothing to keep.
|
|
178
|
-
const copyDir = path.join(home, 'copies');
|
|
179
|
-
await reclaimCopies(copyDir).catch(() => 0);
|
|
180
|
-
// A hold (ALPD §40) only means something while alpd is stopped.
|
|
181
|
-
await unlink(path.join(home, 'state', 'alpd.held')).catch(() => {});
|
|
182
|
-
const settings = await userSettings(home);
|
|
183
|
-
const runtime = createAlpRuntime({
|
|
184
|
-
templates, runLogDir, worktreeDir, copyDir, boardDir: path.join(home, 'boards'), libraryDir: home,
|
|
185
|
-
recallFile: path.join(home, 'state', 'recall.json'), pauseFile: path.join(home, 'state', 'pause.json'), liveFile: path.join(home, 'state', 'live.json'),
|
|
186
|
-
autoResume: settings?.limits?.autoResume !== false, recoveryResume: settings?.recovery?.autoResume !== false && !opened.restored, previousExit: exit,
|
|
187
|
-
});
|
|
188
|
-
const store = createStore(path.join(home, 'state'));
|
|
189
|
-
let stopping: Promise<void> | undefined;
|
|
190
|
-
const shutdown = (code = 0) => {
|
|
191
|
-
stopping ??= (async () => {
|
|
192
|
-
const force = setTimeout(() => process.exit(code), 10_000);
|
|
193
|
-
force.unref();
|
|
194
|
-
clearInterval(beat);
|
|
195
|
-
await server.close().catch(() => {});
|
|
196
|
-
await runtime.shutdown().catch(() => {});
|
|
197
|
-
await store.flush();
|
|
198
|
-
// Last: what remains is a clean stop.
|
|
199
|
-
await unlink(marker).catch(() => {});
|
|
200
|
-
await releaseLock(home);
|
|
201
|
-
log.info('alpd stopped', { event: 'stopped', exitCode: code });
|
|
202
|
-
process.exit(code);
|
|
203
|
-
})();
|
|
204
|
-
return stopping;
|
|
205
|
-
};
|
|
206
|
-
const server = createDaemonServer({ runtime, socketPath: socket, version: VERSION, store, runLogDir, previousExit: exit, home, templates, onShutdown: () => void shutdown() });
|
|
207
|
-
const beat = setInterval(() => {
|
|
208
|
-
void heartbeat(home).then(owned => { if (!owned) void shutdown(1); });
|
|
209
|
-
const now = new Date();
|
|
210
|
-
void utimes(marker, now, now).catch(() => {});
|
|
211
|
-
}, 30_000);
|
|
212
|
-
beat.unref();
|
|
213
|
-
for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => void shutdown());
|
|
214
|
-
process.on('uncaughtException', error => { log.error('uncaught exception; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
|
|
215
|
-
process.on('unhandledRejection', error => { log.error('unhandled rejection; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
|
|
216
|
-
phase = 'listen';
|
|
217
|
-
try {
|
|
218
|
-
await server.listen();
|
|
219
|
-
} catch (error) {
|
|
220
|
-
await releaseLock(home);
|
|
221
|
-
throw error;
|
|
222
|
-
}
|
|
223
|
-
phase = 'ready';
|
|
224
|
-
// Web app and relay are owned by the optional Paseo integration process.
|
|
225
|
-
await updateLock(home, { ...lock, ready: true });
|
|
226
|
-
// Clients that cannot locate alpd themselves (the Paseo plugin) start it from here next time.
|
|
227
|
-
const { install } = daemonPaths(home);
|
|
228
|
-
await writeFile(`${install}.tmp`, JSON.stringify({ entry: fileURLToPath(import.meta.url), version: VERSION }), { mode: 0o600 })
|
|
229
|
-
.then(() => rename(`${install}.tmp`, install))
|
|
230
|
-
.catch(error => log.warn('could not record alpd\'s location', { code: 'ALP_INSTALL_RECORD_FAILED', error }));
|
|
231
|
-
if (opened.restored) await clearRestoredMarker(home).catch(error => log.warn('could not clear the restore marker', { code: 'ALP_STATE_RESTORED', error }));
|
|
232
|
-
log.info(`alpd ${VERSION} ready on ${socket} (pid ${process.pid})`, { event: 'ready', version: VERSION, pid: process.pid });
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
const home = alpHome();
|
|
236
|
-
try {
|
|
237
|
-
if (process.argv.includes('--detach')) await detach(home);
|
|
238
|
-
else {
|
|
239
|
-
if (process.argv.includes('--service')) await serviceLog(home);
|
|
240
|
-
await run(home);
|
|
241
|
-
}
|
|
242
|
-
} catch (error: any) {
|
|
243
|
-
// The log says where start-up stopped; alp doctor reads it from there.
|
|
244
|
-
const stoppedIn = phase as Phase;
|
|
245
|
-
// Opening the state fails with the state's own code (a newer schema, a failed migration).
|
|
246
|
-
const code = /already running|ALP is busy/.test(error?.message ?? '') ? 'ALP_LOCK_HELD'
|
|
247
|
-
: stoppedIn === 'state' && typeof error?.code === 'string' && /^[A-Z_]+$/.test(error.code) ? `ALP_${error.code}` : STARTUP_CODES[stoppedIn];
|
|
248
|
-
log.error(`alpd failed to start while ${{ home: 'preparing its home', lock: 'taking its lock', state: 'opening its state', recovery: 'recovering earlier work', listen: 'opening its IPC endpoint', ready: 'finishing start-up' }[stoppedIn]}${stoppedIn === 'state' ? `: ${error?.message ?? error}` : ''}`, { code, phase: stoppedIn, error });
|
|
249
|
-
process.exit(1);
|
|
250
|
-
}
|
package/src/operations.ts
DELETED
|
@@ -1,298 +0,0 @@
|
|
|
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_PATH': return failure(ERROR.forbidden, 'unsafe_path', message);
|
|
55
|
-
case 'TASK_NOT_FOUND': return failure(ERROR.notFound, 'unknown_task', message);
|
|
56
|
-
case 'TASK_CHANGED': case 'REVISION_CONFLICT': return failure(ERROR.conflict, 'revision_conflict', message);
|
|
57
|
-
case 'INVALID_TASK': case 'TASK_CYCLE': case 'TASK_TAKEN': case 'TASK_UNVERIFIED': return failure(ERROR.conflict, 'task_state', message);
|
|
58
|
-
case 'TASKS_LOCKED': return failure(ERROR.unavailable, 'busy', message);
|
|
59
|
-
case 'IN_USE': return failure(ERROR.conflict, 'in_use', message);
|
|
60
|
-
case 'INVALID_SCOPE': return failure(RPC_ERROR.invalidParams, 'invalid_scope', message);
|
|
61
|
-
case 'INVALID_LIBRARY': case 'INVALID_SETTINGS': return failure(ERROR.failed, 'unreadable', message);
|
|
62
|
-
}
|
|
63
|
-
if (error.code === 'NOT_FOUND' || error.code.endsWith('_NOT_FOUND')) {
|
|
64
|
-
return context.notFound === 'invalid_entry' ? failure(RPC_ERROR.invalidParams, 'invalid_entry', message) : failure(ERROR.notFound, 'not_found', message);
|
|
65
|
-
}
|
|
66
|
-
if (error.code.startsWith('INVALID_')) return failure(RPC_ERROR.invalidParams, 'invalid_entry', message);
|
|
67
|
-
return error;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
const object = (value: unknown): value is Record<string, any> => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
71
|
-
const pointer = (parts: string[]) => parts.map(part => `/${part.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');
|
|
72
|
-
const isMarker = (value: unknown) => object(value) && Object.keys(value).length === 1 && value[MARKER] === KEEP;
|
|
73
|
-
const at = (content: unknown, parts: string[]) => parts.reduce<any>((value, part) => object(value) ? value[part] : undefined, content);
|
|
74
|
-
|
|
75
|
-
/** A copy of an entry's content with each stored secret replaced by the marker, and where they were. */
|
|
76
|
-
function redact(kind: string, content: Record<string, unknown>) {
|
|
77
|
-
const copy = structuredClone(content);
|
|
78
|
-
const secrets: string[] = [];
|
|
79
|
-
for (const parts of SECRET_MAPS[kind] ?? []) {
|
|
80
|
-
const map = at(copy, parts);
|
|
81
|
-
if (!object(map)) continue;
|
|
82
|
-
for (const key of Object.keys(map)) {
|
|
83
|
-
if (typeof map[key] !== 'string') continue;
|
|
84
|
-
map[key] = { [MARKER]: KEEP };
|
|
85
|
-
secrets.push(pointer([...parts, key]));
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
return { content: copy, secrets };
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* The content a save writes: a marker keeps the value stored at its place in `previous` (the entry
|
|
93
|
-
* the save replaces, or the one that applies when the scope has none yet), a string replaces it, a
|
|
94
|
-
* missing key removes it. A marker anywhere else, or with nothing stored to keep, refuses the save,
|
|
95
|
-
* so a placeholder never reaches storage.
|
|
96
|
-
*/
|
|
97
|
-
function unredact(kind: string, content: Record<string, unknown>, previous: Record<string, unknown> | undefined) {
|
|
98
|
-
const next = structuredClone(content);
|
|
99
|
-
for (const parts of SECRET_MAPS[kind] ?? []) {
|
|
100
|
-
const map = at(next, parts);
|
|
101
|
-
if (!object(map)) continue;
|
|
102
|
-
const stored = at(previous, parts);
|
|
103
|
-
for (const key of Object.keys(map)) {
|
|
104
|
-
if (!isMarker(map[key])) continue;
|
|
105
|
-
const value = object(stored) ? stored[key] : undefined;
|
|
106
|
-
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`);
|
|
107
|
-
map[key] = value;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
const stray = (value: unknown, parts: string[]): string | undefined => {
|
|
111
|
-
if (isMarker(value) || (object(value) && Object.hasOwn(value, MARKER))) return pointer(parts);
|
|
112
|
-
if (Array.isArray(value)) for (const [index, item] of value.entries()) { const found = stray(item, [...parts, String(index)]); if (found) return found; }
|
|
113
|
-
if (object(value)) for (const [key, item] of Object.entries(value)) { const found = stray(item, [...parts, key]); if (found) return found; }
|
|
114
|
-
return undefined;
|
|
115
|
-
};
|
|
116
|
-
const found = stray(next, []);
|
|
117
|
-
if (found !== undefined) throw failure(RPC_ERROR.invalidParams, 'secret_marker', `${found || 'content'} holds a secret marker where no secret is kept`);
|
|
118
|
-
return next;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export function createOperations({ home, templates, knownProjects = () => [] }: OperationsOptions = {}) {
|
|
122
|
-
/** Revisions on the wire are keyed per alpd process, so they never carry a hash of secret content. */
|
|
123
|
-
const revisionKey = randomBytes(32);
|
|
124
|
-
const toWire = (revision: string | null | undefined) => revision == null ? null : `r${createHmac('sha256', revisionKey).update(revision).digest('base64url').slice(0, 22)}`;
|
|
125
|
-
/** alpd's own writes to the library, settings and projects' .alp happen one at a time. */
|
|
126
|
-
let writes: Promise<unknown> = Promise.resolve();
|
|
127
|
-
const serial = <T>(work: () => Promise<T>): Promise<T> => {
|
|
128
|
-
const run = writes.catch(() => {}).then(work);
|
|
129
|
-
writes = run;
|
|
130
|
-
return run;
|
|
131
|
-
};
|
|
132
|
-
const requests = new Map<string, { fingerprint: string; at: number; result: Promise<{ id: string }> }>();
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* A project as params name it: an absolute, normalized path to a directory holding a real .alp
|
|
136
|
-
* directory. alpd never walks up to a parent, so the path a caller authorizes is the one used.
|
|
137
|
-
*/
|
|
138
|
-
async function project(value: string) {
|
|
139
|
-
if (!path.isAbsolute(value) || path.resolve(value) !== value) throw failure(RPC_ERROR.invalidParams, 'invalid_path', 'projectRoot must be an absolute, normalized path');
|
|
140
|
-
if (!(await stat(value).catch(() => undefined))?.isDirectory()) throw failure(ERROR.notFound, 'not_alp_project', `${value} is not a directory`);
|
|
141
|
-
const alp = await lstat(path.join(value, '.alp')).catch(() => undefined);
|
|
142
|
-
if (alp?.isSymbolicLink()) throw failure(ERROR.forbidden, 'unsafe_path', `${path.join(value, '.alp')} is a symlink`);
|
|
143
|
-
if (!alp?.isDirectory()) throw failure(ERROR.notFound, 'not_alp_project', `${value} is not an ALP project; run alp init there`);
|
|
144
|
-
return value;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
async function where(projectRoot: string | undefined, scope?: string) {
|
|
148
|
-
if (scope === 'project' && projectRoot === undefined) throw failure(RPC_ERROR.invalidParams, 'invalid_scope', 'scope project needs projectRoot');
|
|
149
|
-
return { root: projectRoot === undefined ? undefined : await project(projectRoot), library: home, templates };
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** One layer's version of an entry, or undefined. */
|
|
153
|
-
async function layer(kind: string, name: string, options: object, scope?: string) {
|
|
154
|
-
try { return await getEntry(kind as any, name, { ...options, ...(scope ? { scope } : {}) } as any); }
|
|
155
|
-
catch (error: any) { if (error?.code === 'NOT_FOUND') return undefined; throw error; }
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
const guard = (handler: Handler, context?: Parameters<typeof fromCore>[1]): Handler => async params => {
|
|
159
|
-
try { return await handler(params); }
|
|
160
|
-
catch (error) { throw fromCore(error, context); }
|
|
161
|
-
};
|
|
162
|
-
|
|
163
|
-
const taskHandlers: Record<string, Handler> = {
|
|
164
|
-
'task.list': guard(async ({ projectRoot }) => {
|
|
165
|
-
const root = await project(projectRoot);
|
|
166
|
-
const { tasks, unreadable } = await taskRows(root);
|
|
167
|
-
return { projectRoot: root, tasks, unreadable, revision: createHash('sha256').update(JSON.stringify([tasks, unreadable])).digest('hex').slice(0, 16) };
|
|
168
|
-
}),
|
|
169
|
-
|
|
170
|
-
'task.create': guard(async ({ projectRoot, title, priority, requestId }) => {
|
|
171
|
-
const root = await project(projectRoot);
|
|
172
|
-
const create = () => createTask(root, { title: title.trim(), ...(priority !== undefined ? { priority } : {}) }, 'user').then(task => ({ id: task.id }));
|
|
173
|
-
if (requestId === undefined) return create();
|
|
174
|
-
const now = Date.now();
|
|
175
|
-
for (const [key, entry] of requests) if (now - entry.at > REQUEST_TTL_MS) requests.delete(key);
|
|
176
|
-
const key = JSON.stringify([root, requestId]);
|
|
177
|
-
const fingerprint = JSON.stringify([title.trim(), priority ?? null]);
|
|
178
|
-
const existing = requests.get(key);
|
|
179
|
-
if (existing) {
|
|
180
|
-
if (existing.fingerprint !== fingerprint) throw failure(ERROR.conflict, 'key_conflict', `Request ${requestId} was already used for another task`);
|
|
181
|
-
return { ...await existing.result, duplicate: true as const };
|
|
182
|
-
}
|
|
183
|
-
const result = create();
|
|
184
|
-
if (requests.size >= MAX_REQUESTS) requests.delete(requests.keys().next().value!);
|
|
185
|
-
requests.set(key, { fingerprint, at: now, result });
|
|
186
|
-
// A create that failed made nothing: the same requestId may try again.
|
|
187
|
-
result.catch(() => { if (requests.get(key)?.result === result) requests.delete(key); });
|
|
188
|
-
return result;
|
|
189
|
-
}),
|
|
190
|
-
|
|
191
|
-
'task.update': guard(async ({ projectRoot, id, action, note, ifRev }) => {
|
|
192
|
-
const root = await project(projectRoot);
|
|
193
|
-
const options = ifRev !== undefined ? { ifRev } : undefined;
|
|
194
|
-
if (action === 'reopen') {
|
|
195
|
-
const task = await reopenTask(root, id, { ...(note ? { note } : {}) }, 'user', options);
|
|
196
|
-
return { id: task.id, status: task.status, rev: task.rev };
|
|
197
|
-
}
|
|
198
|
-
const task = await closeTask(root, id, { reason: 'done', ...(note ? { summary: note } : {}) }, 'user', options);
|
|
199
|
-
const { tasks } = await loadTasks(root);
|
|
200
|
-
const landed = tasks.some(entry => entry.parent === task.id) ? epicReport(task.id, tasks).text.split('\n')[0] : undefined;
|
|
201
|
-
return { id: task.id, status: task.status, rev: task.rev, ...(landed ? { landed } : {}) };
|
|
202
|
-
}),
|
|
203
|
-
|
|
204
|
-
'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev }) => {
|
|
205
|
-
const root = await project(projectRoot);
|
|
206
|
-
const task = await resolveGate(root, id, gate, { by: 'user', ...(note ? { note } : {}), ...(ifRev !== undefined ? { ifRev } : {}) });
|
|
207
|
-
return { id: task.id, status: task.status, rev: task.rev };
|
|
208
|
-
}),
|
|
209
|
-
};
|
|
210
|
-
|
|
211
|
-
const libraryHandlers: Record<string, Handler> = {
|
|
212
|
-
'team.list': guard(async ({ projectRoot }) => {
|
|
213
|
-
const { root } = await where(projectRoot);
|
|
214
|
-
const teams = await listTeams(root, { library: home, templates });
|
|
215
|
-
return { projectRoot: root ?? null, teams: teams.map(({ path: _path, ...team }) => team) };
|
|
216
|
-
}),
|
|
217
|
-
|
|
218
|
-
'library.list': guard(async ({ kind, projectRoot }) => {
|
|
219
|
-
const options = await where(projectRoot);
|
|
220
|
-
const entries = await listEntries(kind, options);
|
|
221
|
-
return { projectRoot: options.root ?? null, entries: entries.map(({ path: _path, ...entry }: any) => entry) };
|
|
222
|
-
}),
|
|
223
|
-
|
|
224
|
-
'library.get': guard(async ({ kind, name, projectRoot, scope }) => {
|
|
225
|
-
const options = await where(projectRoot, scope);
|
|
226
|
-
const entry = await getEntry(kind, name, { ...options, ...(scope ? { scope } : {}) });
|
|
227
|
-
const { content, secrets } = redact(kind, entry.content);
|
|
228
|
-
return { ...entry, content, revision: toWire(entry.revision), ...(secrets.length ? { secrets } : {}) };
|
|
229
|
-
}),
|
|
230
|
-
|
|
231
|
-
'library.save': guard(({ kind, name, scope, projectRoot, content, revision, sync = 'none' }) => serial(async () => {
|
|
232
|
-
const options = await where(projectRoot, scope);
|
|
233
|
-
const current = await layer(kind, name, options, scope);
|
|
234
|
-
if (revision !== undefined && revision !== toWire(current?.revision ?? null)) {
|
|
235
|
-
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`);
|
|
236
|
-
}
|
|
237
|
-
const previous = current?.content ?? (await layer(kind, name, options))?.content;
|
|
238
|
-
const next = unredact(kind, content, previous);
|
|
239
|
-
// Core checks the revision again as it writes, against writers outside alpd.
|
|
240
|
-
const saved = await saveEntry(kind, name, next, { ...options, scope, ...(revision !== undefined ? { revision: current?.revision ?? null } : {}) });
|
|
241
|
-
if (kind !== 'teams' || sync !== 'known-projects') return { revision: toWire(saved.revision) };
|
|
242
|
-
const roots = new Set<string>(options.root ? [options.root] : []);
|
|
243
|
-
if (scope === 'library') for (const root of knownProjects()) if (typeof root === 'string' && path.isAbsolute(root)) roots.add(path.resolve(root));
|
|
244
|
-
let syncedProjects = 0;
|
|
245
|
-
const syncErrors: string[] = [];
|
|
246
|
-
for (const root of roots) {
|
|
247
|
-
try { if (await syncProjectSettings(root, { library: home, templates, teamIds: [name], replaceModels: true })) syncedProjects += 1; }
|
|
248
|
-
catch (error) { syncErrors.push(`${root}: ${error instanceof Error ? error.message : String(error)}`); }
|
|
249
|
-
}
|
|
250
|
-
return { revision: toWire(saved.revision), syncedProjects, syncErrors };
|
|
251
|
-
}), { notFound: 'invalid_entry' }),
|
|
252
|
-
|
|
253
|
-
'library.delete': guard(({ kind, name, scope, projectRoot, revision }) => serial(async () => {
|
|
254
|
-
const options = await where(projectRoot, scope);
|
|
255
|
-
const current = await layer(kind, name, options, scope);
|
|
256
|
-
if (!current) throw failure(ERROR.notFound, 'not_found', `No ${kind} entry '${name}' in the ${scope}`);
|
|
257
|
-
if (revision !== undefined && revision !== toWire(current.revision)) throw failure(ERROR.conflict, 'revision_conflict', `${kind} '${name}' changed in the ${scope} since you opened it`);
|
|
258
|
-
return deleteEntry(kind, name, { ...options, scope, ...(revision !== undefined ? { revision: current.revision } : {}) });
|
|
259
|
-
})),
|
|
260
|
-
|
|
261
|
-
'library.duplicate': guard(({ kind, from, to, scope, projectRoot }) => serial(async () => {
|
|
262
|
-
const options = await where(projectRoot, scope);
|
|
263
|
-
try { await getEntry(kind, from, options); }
|
|
264
|
-
catch (error) { throw fromCore(error, { notFound: 'not_found' }); }
|
|
265
|
-
return { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope })).revision) };
|
|
266
|
-
}), { notFound: 'invalid_entry' }),
|
|
267
|
-
|
|
268
|
-
'library.rename': guard(({ kind, from, to, scope, projectRoot }) => serial(async () => {
|
|
269
|
-
const options = await where(projectRoot, scope);
|
|
270
|
-
return { revision: toWire((await renameEntry(kind, from, to, { ...options, scope })).revision) };
|
|
271
|
-
})),
|
|
272
|
-
|
|
273
|
-
'library.skills.set': guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: 'invalid_entry' }),
|
|
274
|
-
|
|
275
|
-
'library.models': guard(async () => {
|
|
276
|
-
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 } : {}) }));
|
|
277
|
-
for (const provider of await listProviders(home)) {
|
|
278
|
-
if (provider.enabled === false || provider.kind === 'antigravity') continue;
|
|
279
|
-
models.push({ id: `acp:${provider.id}`, label: `${provider.label} · Provider default`, efforts: [] });
|
|
280
|
-
for (const model of [...(provider.models ?? []), ...(provider.additionalModels ?? [])]) models.push({ id: `acp:${provider.id}/${model.id}`, label: `${provider.label} · ${model.label ?? model.id}`, efforts: [] });
|
|
281
|
-
}
|
|
282
|
-
return { models: [...new Map(models.map(model => [model.id, model])).values()] };
|
|
283
|
-
}),
|
|
284
|
-
|
|
285
|
-
'settings.language.get': guard(async () => languageSetting(home!)),
|
|
286
|
-
|
|
287
|
-
'settings.language.set': guard(async ({ language }) => {
|
|
288
|
-
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`);
|
|
289
|
-
return serial(() => setLanguage(home!, language));
|
|
290
|
-
}),
|
|
291
|
-
};
|
|
292
|
-
|
|
293
|
-
const library = home !== undefined;
|
|
294
|
-
return {
|
|
295
|
-
handlers: { ...taskHandlers, ...(library ? libraryHandlers : {}) },
|
|
296
|
-
capabilities: [CAPABILITY.task, ...(library ? [CAPABILITY.team, CAPABILITY.library, CAPABILITY.settingsLanguage] : [])],
|
|
297
|
-
};
|
|
298
|
-
}
|
package/src/rpc-error.ts
DELETED