@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.
- package/README.md +8 -2
- package/dist/alpd.js +38612 -0
- package/dist/build-manifest.json +81 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +8 -0
- package/dist/lock.d.ts +16 -0
- package/dist/lock.js +48 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +175 -0
- package/dist/server.d.ts +41 -0
- package/dist/server.js +718 -0
- package/dist/store.d.ts +47 -0
- package/dist/store.js +117 -0
- package/package.json +85 -4
- package/src/index.ts +5 -0
- package/src/lock.ts +56 -0
- package/src/main.ts +172 -0
- package/src/server.ts +812 -0
- package/src/store.ts +156 -0
package/src/store.ts
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { appendFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import type { Envelope, SessionSnapshot, SessionSpec } from '@anhlp/alp-runtime/index';
|
|
5
|
+
import type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* alpd's durable state (plans/reference/ALPD.md §5): one JSON record per session,
|
|
9
|
+
* written atomically, one append-only JSONL timeline per tree, and one receipt per
|
|
10
|
+
* delivered prompt.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
// The session lifecycle and the error shape are neutral (ALPD §18): the protocol owns them so
|
|
14
|
+
// viewers and integrations speak one language. Re-exported here to keep the daemon's API stable.
|
|
15
|
+
export type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
|
|
16
|
+
|
|
17
|
+
export type SessionRecord = {
|
|
18
|
+
version: 1;
|
|
19
|
+
id: string;
|
|
20
|
+
rootId: string;
|
|
21
|
+
/** The client's request, kept for roots so they can be resumed. */
|
|
22
|
+
spec?: SessionSpec;
|
|
23
|
+
delegation?: boolean;
|
|
24
|
+
session?: SessionSnapshot;
|
|
25
|
+
status: SessionStatus;
|
|
26
|
+
lastError?: SessionError;
|
|
27
|
+
title?: string;
|
|
28
|
+
/** Set aside by the user: closed, and listed only when asked (ALPD §61). */
|
|
29
|
+
archived?: boolean;
|
|
30
|
+
createdAt: string;
|
|
31
|
+
updatedAt: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Delivery of one clientMessageId; `pending` means alpd may have stopped while sending it. */
|
|
35
|
+
export type Receipt = {
|
|
36
|
+
version: 1;
|
|
37
|
+
sessionId: string;
|
|
38
|
+
clientMessageId: string;
|
|
39
|
+
fingerprint: string;
|
|
40
|
+
state: 'pending' | 'completed';
|
|
41
|
+
updatedAt: string;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const SAFE = /[^\w.:-]/g;
|
|
45
|
+
const fileName = (id: string) => id.replace(SAFE, '_');
|
|
46
|
+
|
|
47
|
+
export type Store = ReturnType<typeof createStore>;
|
|
48
|
+
|
|
49
|
+
export function createStore(root: string) {
|
|
50
|
+
const sessionsDir = path.join(root, 'sessions');
|
|
51
|
+
const timelineDir = path.join(root, 'timeline');
|
|
52
|
+
const receiptsDir = path.join(root, 'receipts');
|
|
53
|
+
const writes = new Map<string, Promise<void>>();
|
|
54
|
+
const appends = new Map<string, Promise<void>>();
|
|
55
|
+
let ready: Promise<void> | undefined;
|
|
56
|
+
const prepare = () => ready ??= Promise.all([
|
|
57
|
+
mkdir(sessionsDir, { recursive: true, mode: 0o700 }),
|
|
58
|
+
mkdir(timelineDir, { recursive: true, mode: 0o700 }),
|
|
59
|
+
mkdir(receiptsDir, { recursive: true, mode: 0o700 }),
|
|
60
|
+
]).then(() => {});
|
|
61
|
+
|
|
62
|
+
async function writeAtomic(file: string, body: string) {
|
|
63
|
+
const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
64
|
+
await writeFile(temporary, body, { mode: 0o600 });
|
|
65
|
+
await rename(temporary, file);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Serializes work per key so a later write never lands before an earlier one. */
|
|
69
|
+
function queue(map: Map<string, Promise<void>>, key: string, work: () => Promise<void>) {
|
|
70
|
+
const next = (map.get(key) ?? Promise.resolve()).then(prepare).then(work);
|
|
71
|
+
const settled = next.catch(error => { console.error(`${new Date().toISOString()} store`, error); });
|
|
72
|
+
map.set(key, settled);
|
|
73
|
+
void settled.then(() => { if (map.get(key) === settled) map.delete(key); });
|
|
74
|
+
return settled;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
put(record: SessionRecord) {
|
|
79
|
+
const file = path.join(sessionsDir, `${fileName(record.id)}.json`);
|
|
80
|
+
const body = JSON.stringify(record);
|
|
81
|
+
return queue(writes, record.id, () => writeAtomic(file, body));
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
async receipt(key: string): Promise<Receipt | undefined> {
|
|
85
|
+
await writes.get(`receipt:${key}`);
|
|
86
|
+
try {
|
|
87
|
+
const receipt = JSON.parse(await readFile(path.join(receiptsDir, `${fileName(key)}.json`), 'utf8'));
|
|
88
|
+
return receipt?.version === 1 ? receipt : undefined;
|
|
89
|
+
} catch (error: any) {
|
|
90
|
+
if (error?.code === 'ENOENT') return undefined;
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
|
|
95
|
+
putReceipt(key: string, receipt: Receipt) {
|
|
96
|
+
const body = JSON.stringify(receipt);
|
|
97
|
+
return queue(writes, `receipt:${key}`, () => writeAtomic(path.join(receiptsDir, `${fileName(key)}.json`), body));
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
/** Deletes receipts not written for `maxAgeMs`. */
|
|
101
|
+
async pruneReceipts(maxAgeMs: number) {
|
|
102
|
+
await prepare();
|
|
103
|
+
const now = Date.now();
|
|
104
|
+
for (const name of await readdir(receiptsDir)) {
|
|
105
|
+
const file = path.join(receiptsDir, name);
|
|
106
|
+
const info = await stat(file).catch(() => undefined);
|
|
107
|
+
if (info && now - info.mtimeMs > maxAgeMs) await rm(file, { force: true });
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
async list(): Promise<SessionRecord[]> {
|
|
112
|
+
await prepare();
|
|
113
|
+
const records: SessionRecord[] = [];
|
|
114
|
+
for (const name of await readdir(sessionsDir)) {
|
|
115
|
+
if (!name.endsWith('.json')) continue;
|
|
116
|
+
try {
|
|
117
|
+
const record = JSON.parse(await readFile(path.join(sessionsDir, name), 'utf8'));
|
|
118
|
+
if (record?.version === 1 && typeof record.id === 'string') records.push(record);
|
|
119
|
+
else console.error(`${new Date().toISOString()} store: skipped invalid record ${name}`);
|
|
120
|
+
} catch {
|
|
121
|
+
console.error(`${new Date().toISOString()} store: skipped unreadable record ${name}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return records;
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
append(rootId: string, envelope: Envelope) {
|
|
128
|
+
const line = `${JSON.stringify(envelope)}\n`;
|
|
129
|
+
return queue(appends, rootId, () => appendFile(path.join(timelineDir, `${fileName(rootId)}.jsonl`), line, { mode: 0o600 }));
|
|
130
|
+
},
|
|
131
|
+
|
|
132
|
+
async timeline(rootId: string): Promise<Envelope[]> {
|
|
133
|
+
await appends.get(rootId);
|
|
134
|
+
try {
|
|
135
|
+
const text = await readFile(path.join(timelineDir, `${fileName(rootId)}.jsonl`), 'utf8');
|
|
136
|
+
return text.split('\n').filter(Boolean).flatMap(line => { try { return [JSON.parse(line)]; } catch { return []; } });
|
|
137
|
+
} catch (error: any) {
|
|
138
|
+
if (error?.code === 'ENOENT') return [];
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
|
|
143
|
+
/** Removes a whole tree: its records and its timeline. */
|
|
144
|
+
async remove(rootId: string, ids: string[]) {
|
|
145
|
+
await Promise.all([...ids.map(id => writes.get(id)), appends.get(rootId)]);
|
|
146
|
+
await Promise.all([
|
|
147
|
+
...ids.map(id => rm(path.join(sessionsDir, `${fileName(id)}.json`), { force: true })),
|
|
148
|
+
rm(path.join(timelineDir, `${fileName(rootId)}.jsonl`), { force: true }),
|
|
149
|
+
]);
|
|
150
|
+
},
|
|
151
|
+
|
|
152
|
+
async flush() {
|
|
153
|
+
await Promise.all([...writes.values(), ...appends.values()]);
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|