@anhlp/alp-daemon 0.0.0-stage → 0.10.0

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,47 @@
1
+ import type { Envelope, SessionSnapshot, SessionSpec } from '@anhlp/alp-runtime/index';
2
+ import type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
3
+ /**
4
+ * alpd's durable state (plans/reference/ALPD.md §5): one JSON record per session,
5
+ * written atomically, one append-only JSONL timeline per tree, and one receipt per
6
+ * delivered prompt.
7
+ */
8
+ export type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
9
+ export type SessionRecord = {
10
+ version: 1;
11
+ id: string;
12
+ rootId: string;
13
+ /** The client's request, kept for roots so they can be resumed. */
14
+ spec?: SessionSpec;
15
+ delegation?: boolean;
16
+ session?: SessionSnapshot;
17
+ status: SessionStatus;
18
+ lastError?: SessionError;
19
+ title?: string;
20
+ /** Set aside by the user: closed, and listed only when asked (ALPD §61). */
21
+ archived?: boolean;
22
+ createdAt: string;
23
+ updatedAt: string;
24
+ };
25
+ /** Delivery of one clientMessageId; `pending` means alpd may have stopped while sending it. */
26
+ export type Receipt = {
27
+ version: 1;
28
+ sessionId: string;
29
+ clientMessageId: string;
30
+ fingerprint: string;
31
+ state: 'pending' | 'completed';
32
+ updatedAt: string;
33
+ };
34
+ export type Store = ReturnType<typeof createStore>;
35
+ export declare function createStore(root: string): {
36
+ put(record: SessionRecord): Promise<void>;
37
+ receipt(key: string): Promise<Receipt | undefined>;
38
+ putReceipt(key: string, receipt: Receipt): Promise<void>;
39
+ /** Deletes receipts not written for `maxAgeMs`. */
40
+ pruneReceipts(maxAgeMs: number): Promise<void>;
41
+ list(): Promise<SessionRecord[]>;
42
+ append(rootId: string, envelope: Envelope): Promise<void>;
43
+ timeline(rootId: string): Promise<Envelope[]>;
44
+ /** Removes a whole tree: its records and its timeline. */
45
+ remove(rootId: string, ids: string[]): Promise<void>;
46
+ flush(): Promise<void>;
47
+ };
package/dist/store.js ADDED
@@ -0,0 +1,117 @@
1
+ // packages/daemon/src/store.ts
2
+ import { appendFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { randomBytes } from "node:crypto";
4
+ import path from "node:path";
5
+ var SAFE = /[^\w.:-]/g;
6
+ var fileName = (id) => id.replace(SAFE, "_");
7
+ function createStore(root) {
8
+ const sessionsDir = path.join(root, "sessions");
9
+ const timelineDir = path.join(root, "timeline");
10
+ const receiptsDir = path.join(root, "receipts");
11
+ const writes = /* @__PURE__ */ new Map();
12
+ const appends = /* @__PURE__ */ new Map();
13
+ let ready;
14
+ const prepare = () => ready ??= Promise.all([
15
+ mkdir(sessionsDir, { recursive: true, mode: 448 }),
16
+ mkdir(timelineDir, { recursive: true, mode: 448 }),
17
+ mkdir(receiptsDir, { recursive: true, mode: 448 })
18
+ ]).then(() => {
19
+ });
20
+ async function writeAtomic(file, body) {
21
+ const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
22
+ await writeFile(temporary, body, { mode: 384 });
23
+ await rename(temporary, file);
24
+ }
25
+ function queue(map, key, work) {
26
+ const next = (map.get(key) ?? Promise.resolve()).then(prepare).then(work);
27
+ const settled = next.catch((error) => {
28
+ console.error(`${(/* @__PURE__ */ new Date()).toISOString()} store`, error);
29
+ });
30
+ map.set(key, settled);
31
+ void settled.then(() => {
32
+ if (map.get(key) === settled) map.delete(key);
33
+ });
34
+ return settled;
35
+ }
36
+ return {
37
+ put(record) {
38
+ const file = path.join(sessionsDir, `${fileName(record.id)}.json`);
39
+ const body = JSON.stringify(record);
40
+ return queue(writes, record.id, () => writeAtomic(file, body));
41
+ },
42
+ async receipt(key) {
43
+ await writes.get(`receipt:${key}`);
44
+ try {
45
+ const receipt = JSON.parse(await readFile(path.join(receiptsDir, `${fileName(key)}.json`), "utf8"));
46
+ return receipt?.version === 1 ? receipt : void 0;
47
+ } catch (error) {
48
+ if (error?.code === "ENOENT") return void 0;
49
+ throw error;
50
+ }
51
+ },
52
+ putReceipt(key, receipt) {
53
+ const body = JSON.stringify(receipt);
54
+ return queue(writes, `receipt:${key}`, () => writeAtomic(path.join(receiptsDir, `${fileName(key)}.json`), body));
55
+ },
56
+ /** Deletes receipts not written for `maxAgeMs`. */
57
+ async pruneReceipts(maxAgeMs) {
58
+ await prepare();
59
+ const now = Date.now();
60
+ for (const name of await readdir(receiptsDir)) {
61
+ const file = path.join(receiptsDir, name);
62
+ const info = await stat(file).catch(() => void 0);
63
+ if (info && now - info.mtimeMs > maxAgeMs) await rm(file, { force: true });
64
+ }
65
+ },
66
+ async list() {
67
+ await prepare();
68
+ const records = [];
69
+ for (const name of await readdir(sessionsDir)) {
70
+ if (!name.endsWith(".json")) continue;
71
+ try {
72
+ const record = JSON.parse(await readFile(path.join(sessionsDir, name), "utf8"));
73
+ if (record?.version === 1 && typeof record.id === "string") records.push(record);
74
+ else console.error(`${(/* @__PURE__ */ new Date()).toISOString()} store: skipped invalid record ${name}`);
75
+ } catch {
76
+ console.error(`${(/* @__PURE__ */ new Date()).toISOString()} store: skipped unreadable record ${name}`);
77
+ }
78
+ }
79
+ return records;
80
+ },
81
+ append(rootId, envelope) {
82
+ const line = `${JSON.stringify(envelope)}
83
+ `;
84
+ return queue(appends, rootId, () => appendFile(path.join(timelineDir, `${fileName(rootId)}.jsonl`), line, { mode: 384 }));
85
+ },
86
+ async timeline(rootId) {
87
+ await appends.get(rootId);
88
+ try {
89
+ const text = await readFile(path.join(timelineDir, `${fileName(rootId)}.jsonl`), "utf8");
90
+ return text.split("\n").filter(Boolean).flatMap((line) => {
91
+ try {
92
+ return [JSON.parse(line)];
93
+ } catch {
94
+ return [];
95
+ }
96
+ });
97
+ } catch (error) {
98
+ if (error?.code === "ENOENT") return [];
99
+ throw error;
100
+ }
101
+ },
102
+ /** Removes a whole tree: its records and its timeline. */
103
+ async remove(rootId, ids) {
104
+ await Promise.all([...ids.map((id) => writes.get(id)), appends.get(rootId)]);
105
+ await Promise.all([
106
+ ...ids.map((id) => rm(path.join(sessionsDir, `${fileName(id)}.json`), { force: true })),
107
+ rm(path.join(timelineDir, `${fileName(rootId)}.jsonl`), { force: true })
108
+ ]);
109
+ },
110
+ async flush() {
111
+ await Promise.all([...writes.values(), ...appends.values()]);
112
+ }
113
+ };
114
+ }
115
+ export {
116
+ createStore
117
+ };
package/package.json CHANGED
@@ -1,6 +1,87 @@
1
1
  {
2
2
  "name": "@anhlp/alp-daemon",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.10.0",
4
+ "type": "module",
5
+ "description": "ALP daemon module",
6
+ "files": [
7
+ "src",
8
+ "dist"
9
+ ],
10
+ "exports": {
11
+ "./index": {
12
+ "alp-source": {
13
+ "types": "./src/index.ts",
14
+ "default": "./src/index.ts"
15
+ },
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ ".": {
20
+ "alp-source": {
21
+ "types": "./src/index.ts",
22
+ "default": "./src/index.ts"
23
+ },
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "./lock": {
28
+ "alp-source": {
29
+ "types": "./src/lock.ts",
30
+ "default": "./src/lock.ts"
31
+ },
32
+ "types": "./dist/lock.d.ts",
33
+ "default": "./dist/lock.js"
34
+ },
35
+ "./main": {
36
+ "alp-source": {
37
+ "types": "./src/main.ts",
38
+ "default": "./src/main.ts"
39
+ },
40
+ "types": "./dist/main.d.ts",
41
+ "default": "./dist/main.js"
42
+ },
43
+ "./server": {
44
+ "alp-source": {
45
+ "types": "./src/server.ts",
46
+ "default": "./src/server.ts"
47
+ },
48
+ "types": "./dist/server.d.ts",
49
+ "default": "./dist/server.js"
50
+ },
51
+ "./store": {
52
+ "alp-source": {
53
+ "types": "./src/store.ts",
54
+ "default": "./src/store.ts"
55
+ },
56
+ "types": "./dist/store.d.ts",
57
+ "default": "./dist/store.js"
58
+ }
59
+ },
60
+ "engines": {
61
+ "node": ">=20"
62
+ },
63
+ "dependencies": {
64
+ "@anhlp/alp-core": "0.10.0",
65
+ "@anhlp/alp-runtime": "0.10.0",
66
+ "@anhlp/alp-client": "0.10.0",
67
+ "@anhlp/alp-protocol": "0.10.0",
68
+ "@anthropic-ai/sdk": "^0.131.0",
69
+ "ws": "^8.22.0",
70
+ "zod": "4.4.3",
71
+ "@anthropic-ai/claude-agent-sdk": "^0.3.292"
72
+ },
73
+ "scripts": {
74
+ "build": "node ../../scripts/build-workspace.mjs daemon",
75
+ "test": "node ../../scripts/test-package.mjs daemon",
76
+ "prepack": "npm run build"
77
+ },
78
+ "publishConfig": {
79
+ "access": "public",
80
+ "registry": "https://registry.npmjs.org/"
81
+ },
82
+ "repository": {
83
+ "type": "git",
84
+ "url": "git+https://github.com/phucanh08/alp-paseo.git",
85
+ "directory": "packages/daemon"
86
+ }
87
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ // alpd's building blocks, for embedding and tests; src/daemon/main.ts is the daemon itself.
2
+ export { createDaemonServer, ERROR } from './server.js';
3
+ export type { DaemonConnection, DaemonServer, SessionSummary } from './server.js';
4
+ export { createStore } from './store.js';
5
+ export type { SessionRecord, SessionStatus, Store } from './store.js';
package/src/lock.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { open, readFile, unlink, utimes, writeFile, rename } from 'node:fs/promises';
2
+ import { bootTime, daemonPaths, lockAlive, readLock } from '@anhlp/alp-client/index';
3
+
4
+ export type LockContents = {
5
+ pid: number;
6
+ startedAt: string;
7
+ bootTime: number;
8
+ uid: number;
9
+ version: string;
10
+ protocolVersion: number;
11
+ socket: string;
12
+ ready: boolean;
13
+ };
14
+
15
+ /** Single-instance lock (Paseo acquirePidLock, simplified): exclusive create, stale when its pid or boot is gone. */
16
+ export async function acquireLock(home: string, contents: Omit<LockContents, 'pid' | 'startedAt' | 'bootTime' | 'uid' | 'ready'>) {
17
+ const file = daemonPaths(home).lock;
18
+ const lock: LockContents = { pid: process.pid, startedAt: new Date().toISOString(), bootTime: bootTime(), uid: process.getuid?.() ?? -1, ready: false, ...contents };
19
+ for (let attempt = 0; attempt < 2; attempt++) {
20
+ try {
21
+ const handle = await open(file, 'wx', 0o600);
22
+ await handle.writeFile(JSON.stringify(lock));
23
+ await handle.close();
24
+ return lock;
25
+ } catch (error: any) {
26
+ if (error?.code !== 'EEXIST') throw error;
27
+ const current = await readLock(home);
28
+ if (lockAlive(current)) throw new Error(`ALP daemon already running (pid ${current.pid})`);
29
+ // Remove the stale lock only if nobody replaced it meanwhile.
30
+ const again = await readFile(file, 'utf8').catch(() => undefined);
31
+ if (again === undefined || JSON.stringify(current) === again || !lockAlive(JSON.parse(again))) await unlink(file).catch(() => {});
32
+ }
33
+ }
34
+ throw new Error('Could not acquire the ALP daemon lock');
35
+ }
36
+
37
+ export async function updateLock(home: string, lock: LockContents) {
38
+ const file = daemonPaths(home).lock;
39
+ const temporary = `${file}.${process.pid}.tmp`;
40
+ await writeFile(temporary, JSON.stringify(lock), { mode: 0o600 });
41
+ await rename(temporary, file);
42
+ }
43
+
44
+ /** True while this process still owns the lock; refreshes its mtime as a heartbeat. */
45
+ export async function heartbeat(home: string) {
46
+ const current = await readLock(home);
47
+ if (current?.pid !== process.pid) return false;
48
+ const now = new Date();
49
+ await utimes(daemonPaths(home).lock, now, now).catch(() => {});
50
+ return true;
51
+ }
52
+
53
+ export async function releaseLock(home: string) {
54
+ const current = await readLock(home);
55
+ if (current?.pid === process.pid) await unlink(daemonPaths(home).lock).catch(() => {});
56
+ }
package/src/main.ts ADDED
@@ -0,0 +1,172 @@
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, 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
+
14
+ declare const __ALP_VERSION__: string;
15
+ const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-dev';
16
+ const LOG_BYTES = 10 * 1024 * 1024;
17
+ const LOG_FILES = 3;
18
+
19
+ async function rotate(log: string) {
20
+ const size = await stat(log).then(info => info.size, () => 0);
21
+ if (size < LOG_BYTES) return;
22
+ for (let index = LOG_FILES - 1; index >= 1; index--) {
23
+ await rename(index === 1 ? log : `${log}.${index - 1}`, `${log}.${index}`).catch(() => {});
24
+ }
25
+ }
26
+
27
+ /** Starts the daemon in a new session and returns at once, so it is not part of the caller's process tree. */
28
+ async function detach(home: string) {
29
+ const { log } = daemonPaths(home);
30
+ await mkdir(path.dirname(log), { recursive: true, mode: 0o700 });
31
+ await rotate(log);
32
+ const output = await open(log, 'a', 0o600);
33
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {
34
+ detached: true,
35
+ stdio: ['ignore', output.fd, output.fd],
36
+ env: process.env,
37
+ windowsHide: true,
38
+ });
39
+ child.unref();
40
+ await output.close();
41
+ }
42
+
43
+ /**
44
+ * Under a service manager (ALPD §37), which holds alpd's stdout open: alpd rotates its
45
+ * log at start as the detached launcher does, then writes its output there itself. The
46
+ * manager's own file keeps only what Node prints when it dies.
47
+ */
48
+ async function serviceLog(home: string) {
49
+ const { log } = daemonPaths(home);
50
+ await mkdir(path.dirname(log), { recursive: true, mode: 0o700 });
51
+ await rotate(log);
52
+ const fd = openSync(log, 'a', 0o600);
53
+ for (const stream of [process.stdout, process.stderr]) {
54
+ stream.write = ((chunk: string | Uint8Array, encoding?: unknown, callback?: unknown) => {
55
+ try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, chunk); } catch {}
56
+ const done = typeof encoding === 'function' ? encoding : callback;
57
+ if (typeof done === 'function') done();
58
+ return true;
59
+ }) as typeof stream.write;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * The user's alpd settings in $ALP_HOME/settings.json; none when it is missing.
65
+ * Invalid settings are logged and alpd starts with the defaults, so a typo never
66
+ * keeps it from running; alp doctor reports them too.
67
+ */
68
+ async function userSettings(home: string): Promise<any> {
69
+ const file = path.join(home, 'settings.json');
70
+ let text: string;
71
+ try { text = await readFile(file, 'utf8'); } catch { return {}; }
72
+ try { return validateUserSettings(JSON.parse(text), file); }
73
+ catch (error: any) {
74
+ console.error(`${new Date().toISOString()} ignoring ${file}: ${error?.message ?? error}`);
75
+ return {};
76
+ }
77
+ }
78
+
79
+ /**
80
+ * How the previous alpd ended (ALPD §31). A running alpd keeps a marker file and
81
+ * touches it with its heartbeat; a clean stop removes it last. A marker found at
82
+ * start means the previous alpd crashed, around the marker's last touch.
83
+ */
84
+ async function previousExit(marker: string): Promise<{ kind: 'clean' | 'crash'; at?: string }> {
85
+ const info = await stat(marker).catch(() => undefined);
86
+ return info ? { kind: 'crash', at: info.mtime.toISOString() } : { kind: 'clean' };
87
+ }
88
+
89
+ async function run(home: string) {
90
+ await mkdir(home, { recursive: true, mode: 0o700 });
91
+ const { socket } = daemonPaths(home);
92
+ let lock;
93
+ try {
94
+ lock = await acquireLock(home, { version: VERSION, protocolVersion: PROTOCOL_VERSION, socket });
95
+ } catch (error: any) {
96
+ // Under a service manager, another alpd serving this home is no failure to retry.
97
+ if (process.argv.includes('--service') && /already running/.test(error?.message ?? '')) {
98
+ console.log(`${new Date().toISOString()} ${error.message}; this one exits`);
99
+ process.exit(0);
100
+ }
101
+ throw error;
102
+ }
103
+ const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home, 'runs');
104
+ const worktreeDir = path.join(home, 'worktrees');
105
+ // Worktrees of assignments a crash interrupted: their work goes to their branches.
106
+ for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [] as string[])) console.log(`${new Date().toISOString()} kept interrupted work on branch ${branch}`);
107
+ // Review copies of interrupted assignments hold nothing to keep.
108
+ const copyDir = path.join(home, 'copies');
109
+ await reclaimCopies(copyDir).catch(() => 0);
110
+ // A hold (ALPD §40) only means something while alpd is stopped.
111
+ await unlink(path.join(home, 'state', 'alpd.held')).catch(() => {});
112
+ const marker = path.join(home, 'state', 'alpd.running');
113
+ const exit = await previousExit(marker);
114
+ if (exit.kind === 'crash') console.log(`${new Date().toISOString()} the previous alpd stopped unexpectedly around ${exit.at}`);
115
+ await mkdir(path.dirname(marker), { recursive: true, mode: 0o700 });
116
+ await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }), { mode: 0o600 });
117
+ const settings = await userSettings(home);
118
+ const runtime = createAlpRuntime({
119
+ templates, runLogDir, worktreeDir, copyDir, boardDir: path.join(home, 'boards'), libraryDir: home,
120
+ recallFile: path.join(home, 'state', 'recall.json'), pauseFile: path.join(home, 'state', 'pause.json'), liveFile: path.join(home, 'state', 'live.json'),
121
+ autoResume: settings?.limits?.autoResume !== false, recoveryResume: settings?.recovery?.autoResume !== false, previousExit: exit,
122
+ });
123
+ const store = createStore(path.join(home, 'state'));
124
+ let stopping: Promise<void> | undefined;
125
+ const shutdown = (code = 0) => {
126
+ stopping ??= (async () => {
127
+ const force = setTimeout(() => process.exit(code), 10_000);
128
+ force.unref();
129
+ clearInterval(beat);
130
+ await server.close().catch(() => {});
131
+ await runtime.shutdown().catch(() => {});
132
+ await store.flush();
133
+ // Last: what remains is a clean stop.
134
+ await unlink(marker).catch(() => {});
135
+ await releaseLock(home);
136
+ console.log(`${new Date().toISOString()} alpd stopped`);
137
+ process.exit(code);
138
+ })();
139
+ return stopping;
140
+ };
141
+ const server = createDaemonServer({ runtime, socketPath: socket, version: VERSION, store, runLogDir, previousExit: exit, onShutdown: () => void shutdown() });
142
+ const beat = setInterval(() => {
143
+ void heartbeat(home).then(owned => { if (!owned) void shutdown(1); });
144
+ const now = new Date();
145
+ void utimes(marker, now, now).catch(() => {});
146
+ }, 30_000);
147
+ beat.unref();
148
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => void shutdown());
149
+ process.on('uncaughtException', error => { console.error(`${new Date().toISOString()} fatal`, error); void shutdown(1); });
150
+ process.on('unhandledRejection', error => { console.error(`${new Date().toISOString()} fatal`, error); void shutdown(1); });
151
+ try {
152
+ await server.listen();
153
+ } catch (error) {
154
+ await releaseLock(home);
155
+ throw error;
156
+ }
157
+ // Web app and relay are owned by the optional Paseo integration process.
158
+ await updateLock(home, { ...lock, ready: true });
159
+ // Clients that cannot locate alpd themselves (the Paseo plugin) start it from here next time.
160
+ const { install } = daemonPaths(home);
161
+ await writeFile(`${install}.tmp`, JSON.stringify({ entry: fileURLToPath(import.meta.url), version: VERSION }), { mode: 0o600 })
162
+ .then(() => rename(`${install}.tmp`, install))
163
+ .catch(error => console.error(`${new Date().toISOString()} could not record alpd's location`, error));
164
+ console.log(`${new Date().toISOString()} alpd ${VERSION} ready on ${socket} (pid ${process.pid})`);
165
+ }
166
+
167
+ const home = alpHome();
168
+ if (process.argv.includes('--detach')) await detach(home);
169
+ else {
170
+ if (process.argv.includes('--service')) await serviceLog(home);
171
+ await run(home);
172
+ }