@thready-web/dsh-bot-plugin 0.0.0-stage → 0.1.0-beta.1

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/dist/errors.js ADDED
@@ -0,0 +1,46 @@
1
+ /** Structured tool and recovery failures. These are plugin contracts, not DSH errors. */
2
+ export const CODES = [
3
+ 'BUSY',
4
+ 'CAS_CONFLICT',
5
+ 'IDEMPOTENCY_KEY_REUSE',
6
+ 'NOT_FOUND',
7
+ 'FORBIDDEN',
8
+ 'VALIDATION',
9
+ 'HASH_MISMATCH',
10
+ 'BUDGET_OVERFLOW',
11
+ 'BUDGET',
12
+ 'REVOKED',
13
+ 'STORE_FAILURE',
14
+ 'UNAVAILABLE',
15
+ 'HOP_LIMIT',
16
+ 'TTL_EXPIRED',
17
+ 'RATE_LIMIT',
18
+ 'SIGNATURE',
19
+ 'REPLAY',
20
+ 'REJECTED',
21
+ ];
22
+ const RETRYABLE = new Set(['BUSY']);
23
+ /**
24
+ * @param {string} code
25
+ * @param {string} message
26
+ * @param {Record<string, unknown>} [details]
27
+ */
28
+ export function toolError(code, message, details) {
29
+ return {
30
+ ok: false,
31
+ code,
32
+ message,
33
+ retryable: code === 'CAS_CONFLICT' ? true : RETRYABLE.has(code),
34
+ ...(details ? { details } : {}),
35
+ };
36
+ }
37
+ /**
38
+ * @param {unknown} error
39
+ */
40
+ export function asStoreFailure(error) {
41
+ const message = error instanceof Error ? error.message : String(error);
42
+ if (message.includes('SQLITE_BUSY') || message.includes('database is locked')) {
43
+ return toolError('BUSY', 'The write lock was not acquired, so nothing was written.');
44
+ }
45
+ return toolError('STORE_FAILURE', message);
46
+ }
@@ -0,0 +1,100 @@
1
+ import { closeSync, constants, fsyncSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, renameSync, writeSync } from 'node:fs';
2
+ import { basename, dirname, join, relative, sep } from 'node:path';
3
+ import { createHash, randomBytes } from 'node:crypto';
4
+ const OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0);
5
+ /**
6
+ * @param {Buffer | string} bytes
7
+ */
8
+ export function sha256(bytes) {
9
+ return createHash('sha256').update(bytes).digest('hex');
10
+ }
11
+ /**
12
+ * @param {string} root
13
+ */
14
+ export function ensureDir(root) {
15
+ mkdirSync(root, { recursive: true, mode: 0o700 });
16
+ return realpathSync(root);
17
+ }
18
+ /**
19
+ * Reject `..`, absolute segments, and symlink escapes. The returned descriptor
20
+ * is the file that was opened; callers hash those bytes.
21
+ * A same-user process can still win a race. This is not an OS sandbox.
22
+ * @param {string} root
23
+ * @param {string} file
24
+ */
25
+ export function openContained(root, file) {
26
+ const rootReal = realpathSync(root);
27
+ const rel = relative(rootReal, file);
28
+ if (rel.startsWith('..') || rel === '' || file.includes('\0')) {
29
+ throw Object.assign(new Error('path escapes the skill root'), { code: 'FORBIDDEN' });
30
+ }
31
+ const segments = rel.split(sep).filter(Boolean);
32
+ if (segments.some(segment => segment === '.' || segment === '..')) {
33
+ throw Object.assign(new Error('path segment rejected'), { code: 'FORBIDDEN' });
34
+ }
35
+ let cursor = rootReal;
36
+ for (const segment of segments) {
37
+ cursor = join(cursor, segment);
38
+ let stat;
39
+ try {
40
+ stat = lstatSync(cursor);
41
+ }
42
+ catch (error) {
43
+ throw Object.assign(new Error(`path missing: ${segment}`), { code: 'NOT_FOUND', cause: error });
44
+ }
45
+ if (stat.isSymbolicLink()) {
46
+ throw Object.assign(new Error('symlink rejected'), { code: 'FORBIDDEN' });
47
+ }
48
+ }
49
+ const parentReal = realpathSync(dirname(cursor));
50
+ const parentRel = relative(rootReal, parentReal);
51
+ if (parentRel.startsWith('..') || parentRel.split(sep).includes('..')) {
52
+ throw Object.assign(new Error('resolved parent escapes the skill root'), { code: 'FORBIDDEN' });
53
+ }
54
+ const fd = openSync(join(parentReal, basename(cursor)), OPEN_FLAGS);
55
+ return { fd, path: join(parentReal, basename(cursor)) };
56
+ }
57
+ /**
58
+ * @param {string} root
59
+ * @param {string} file
60
+ */
61
+ export function readContained(root, file) {
62
+ const opened = openContained(root, file);
63
+ try {
64
+ const chunks = [];
65
+ const buffer = Buffer.alloc(64 * 1024);
66
+ let offset = 0;
67
+ while (true) {
68
+ const read = readSync(opened.fd, buffer, 0, buffer.length, offset);
69
+ if (read === 0)
70
+ break;
71
+ chunks.push(Buffer.from(buffer.subarray(0, read)));
72
+ offset += read;
73
+ }
74
+ return Buffer.concat(chunks);
75
+ }
76
+ finally {
77
+ closeSync(opened.fd);
78
+ }
79
+ }
80
+ /**
81
+ * Write bytes to a temp file, fsync, then rename into place.
82
+ * @param {string} file
83
+ * @param {Buffer | string} bytes
84
+ */
85
+ export function writeAtomic(file, bytes) {
86
+ const data = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
87
+ const tmp = `${file}.${randomBytes(6).toString('hex')}.tmp`;
88
+ const fd = openSync(tmp, 'w', 0o600);
89
+ try {
90
+ let offset = 0;
91
+ while (offset < data.length)
92
+ offset += writeSync(fd, data, offset);
93
+ fsyncSync(fd);
94
+ }
95
+ finally {
96
+ closeSync(fd);
97
+ }
98
+ renameSync(tmp, file);
99
+ return data;
100
+ }
@@ -0,0 +1,33 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { openStore } from "./store.js";
4
+ import { createEngine } from "./engine.js";
5
+ import { registerHttp } from "./http.js";
6
+ import { runtimeFor, workRuntimeFor } from "./runtime-registry.js";
7
+ export const name = 'session-foundations-http';
8
+ export const inject = ['webServer', 'agents', 'sessionPersistence'];
9
+ /**
10
+ * Local management routes for the same SQLite the main plugin uses.
11
+ * Loaded only on profiles that have a web server, so headless does not need it.
12
+ * @param {import('@deepseek-ai/cordis').Context} ctx
13
+ * @param {{ dataDir?: string }} [config]
14
+ */
15
+ export function apply(ctx, config = {}) {
16
+ const dataDir = config.dataDir ?? (ctx.profileContext?.dir ? join(ctx.profileContext.dir, 'session-foundations') : '');
17
+ if (dataDir === '')
18
+ throw new Error('session-foundations-http: pass dataDir or launch with dsh profileContext');
19
+ const store = openStore(dataDir);
20
+ const engine = createEngine(store);
21
+ ctx.effect(() => () => {
22
+ try {
23
+ store.close();
24
+ }
25
+ catch { /* closed */ }
26
+ });
27
+ let key = dataDir;
28
+ try {
29
+ key = realpathSync(dataDir);
30
+ }
31
+ catch { /* not created yet */ }
32
+ registerHttp(ctx, engine, () => runtimeFor(key) ?? runtimeFor(dataDir), () => workRuntimeFor(key) ?? workRuntimeFor(dataDir), dataDir);
33
+ }