@thready-web/dsh-bot-plugin 0.0.0-stage → 0.1.0-beta.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/LICENSE +21 -0
- package/README.md +45 -2
- package/client.js +646 -0
- package/dist/cdc.js +73 -0
- package/dist/cli.js +352 -0
- package/dist/context.js +262 -0
- package/dist/cron.js +98 -0
- package/dist/desk-ledger.js +91 -0
- package/dist/desk.js +518 -0
- package/dist/engine.js +733 -0
- package/dist/errors.js +46 -0
- package/dist/fs-safe.js +100 -0
- package/dist/http-plugin.js +33 -0
- package/dist/http.js +593 -0
- package/dist/inbox.js +194 -0
- package/dist/index.js +411 -0
- package/dist/live-diff.js +188 -0
- package/dist/live-snapshot.js +152 -0
- package/dist/provision.js +44 -0
- package/dist/router-plugin.js +14 -0
- package/dist/runtime-registry.js +36 -0
- package/dist/session-files.js +111 -0
- package/dist/session-previews.js +111 -0
- package/dist/store.js +598 -0
- package/dist/tools.js +357 -0
- package/dist/triggers.js +874 -0
- package/dist/work-admit.js +128 -0
- package/dist/work-child.js +73 -0
- package/dist/work-durable.js +53 -0
- package/dist/work-http.js +287 -0
- package/dist/work-ledger.js +217 -0
- package/dist/work-mock-host.js +187 -0
- package/dist/work-mock.js +131 -0
- package/dist/work-tickets.js +1042 -0
- package/dist/work-tools.js +150 -0
- package/dist/work-worker.js +1108 -0
- package/fixtures/mock-llm.mjs +267 -0
- package/package.json +54 -4
- package/public/assets/index-Be82iGwe.css +1 -0
- package/public/assets/index-ByU9a3Lh.js +61 -0
- package/public/index.html +14 -0
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diff between two live documents.
|
|
3
|
+
* The first frame on a connection is the whole value. Every later frame is one of these patches.
|
|
4
|
+
* Objects merge by key. Lists of records merge by a stable id, so one changed session or ticket
|
|
5
|
+
* does not repeat the rest of the list.
|
|
6
|
+
*/
|
|
7
|
+
/** Append user/assistant messages kept on session/follow. Older history is the CDC prefix. */
|
|
8
|
+
export const FOLLOW_TAIL_MESSAGES = 4;
|
|
9
|
+
const ID_FIELDS = ['sessionId', 'id', 'event_id', 'ticket.id', 'from', 'date', 'model'];
|
|
10
|
+
function stable(value) {
|
|
11
|
+
if (value === undefined)
|
|
12
|
+
return 'null';
|
|
13
|
+
if (value === null || typeof value !== 'object')
|
|
14
|
+
return JSON.stringify(value) ?? 'null';
|
|
15
|
+
if (Array.isArray(value))
|
|
16
|
+
return `[${value.map(item => stable(item)).join(',')}]`;
|
|
17
|
+
const record = value;
|
|
18
|
+
const keys = Object.keys(record).filter(key => record[key] !== undefined).sort();
|
|
19
|
+
return `{${keys.map(key => `${JSON.stringify(key)}:${stable(record[key])}`).join(',')}}`;
|
|
20
|
+
}
|
|
21
|
+
function isObject(value) {
|
|
22
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
23
|
+
}
|
|
24
|
+
function readId(item, field) {
|
|
25
|
+
if (!isObject(item))
|
|
26
|
+
return undefined;
|
|
27
|
+
if (field === 'ticket.id') {
|
|
28
|
+
const ticket = item.ticket;
|
|
29
|
+
if (!isObject(ticket))
|
|
30
|
+
return undefined;
|
|
31
|
+
const id = ticket.id;
|
|
32
|
+
return typeof id === 'string' && id !== '' ? id : undefined;
|
|
33
|
+
}
|
|
34
|
+
const id = item[field];
|
|
35
|
+
if (typeof id === 'string' && id !== '')
|
|
36
|
+
return id;
|
|
37
|
+
if (typeof id === 'number' && Number.isFinite(id))
|
|
38
|
+
return String(id);
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
function listField(items) {
|
|
42
|
+
if (items.length === 0)
|
|
43
|
+
return null;
|
|
44
|
+
for (const field of ID_FIELDS) {
|
|
45
|
+
const seen = new Set();
|
|
46
|
+
let ok = true;
|
|
47
|
+
for (const item of items) {
|
|
48
|
+
const id = readId(item, field);
|
|
49
|
+
if (id === undefined || seen.has(id)) {
|
|
50
|
+
ok = false;
|
|
51
|
+
break;
|
|
52
|
+
}
|
|
53
|
+
seen.add(id);
|
|
54
|
+
}
|
|
55
|
+
if (ok)
|
|
56
|
+
return field;
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
export function diffValue(prev, next) {
|
|
61
|
+
if (stable(prev) === stable(next))
|
|
62
|
+
return null;
|
|
63
|
+
if (isObject(prev) && isObject(next))
|
|
64
|
+
return diffObject(prev, next);
|
|
65
|
+
if (Array.isArray(prev) && Array.isArray(next)) {
|
|
66
|
+
const listed = diffList(prev, next);
|
|
67
|
+
if (listed)
|
|
68
|
+
return listed;
|
|
69
|
+
}
|
|
70
|
+
return { t: 'v', v: next };
|
|
71
|
+
}
|
|
72
|
+
function diffObject(prev, next) {
|
|
73
|
+
const set = {};
|
|
74
|
+
const del = [];
|
|
75
|
+
for (const key of Object.keys(prev)) {
|
|
76
|
+
if (!Object.prototype.hasOwnProperty.call(next, key))
|
|
77
|
+
del.push(key);
|
|
78
|
+
}
|
|
79
|
+
for (const key of Object.keys(next)) {
|
|
80
|
+
if (!Object.prototype.hasOwnProperty.call(prev, key)) {
|
|
81
|
+
set[key] = { t: 'v', v: next[key] };
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const child = diffValue(prev[key], next[key]);
|
|
85
|
+
if (child)
|
|
86
|
+
set[key] = child;
|
|
87
|
+
}
|
|
88
|
+
if (Object.keys(set).length === 0 && del.length === 0)
|
|
89
|
+
return null;
|
|
90
|
+
return del.length > 0 ? { t: 'o', s: set, d: del } : { t: 'o', s: set };
|
|
91
|
+
}
|
|
92
|
+
function diffList(prev, next) {
|
|
93
|
+
const prevField = listField(prev);
|
|
94
|
+
const nextField = listField(next);
|
|
95
|
+
if (prev.length > 0 && !prevField)
|
|
96
|
+
return null;
|
|
97
|
+
if (next.length > 0 && !nextField)
|
|
98
|
+
return null;
|
|
99
|
+
if (prevField && nextField && prevField !== nextField)
|
|
100
|
+
return null;
|
|
101
|
+
const field = nextField || prevField;
|
|
102
|
+
if (!field)
|
|
103
|
+
return null;
|
|
104
|
+
const prevById = new Map(prev.map(item => [readId(item, field), item]));
|
|
105
|
+
const set = {};
|
|
106
|
+
const del = [];
|
|
107
|
+
const nextIds = next.map(item => readId(item, field) ?? '');
|
|
108
|
+
const seen = new Set(nextIds);
|
|
109
|
+
for (const item of prev) {
|
|
110
|
+
const id = readId(item, field);
|
|
111
|
+
if (id !== undefined && !seen.has(id))
|
|
112
|
+
del.push(id);
|
|
113
|
+
}
|
|
114
|
+
for (const item of next) {
|
|
115
|
+
const id = readId(item, field);
|
|
116
|
+
if (id === undefined)
|
|
117
|
+
continue;
|
|
118
|
+
if (!prevById.has(id)) {
|
|
119
|
+
set[id] = { t: 'v', v: item };
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const child = diffValue(prevById.get(id), item);
|
|
123
|
+
if (child)
|
|
124
|
+
set[id] = child;
|
|
125
|
+
}
|
|
126
|
+
const prevIds = prev.map(item => readId(item, field) ?? '');
|
|
127
|
+
const orderChanged = prevIds.length !== nextIds.length || prevIds.some((id, index) => id !== nextIds[index]);
|
|
128
|
+
if (Object.keys(set).length === 0 && del.length === 0 && !orderChanged)
|
|
129
|
+
return null;
|
|
130
|
+
const patch = { t: 'l', id: field };
|
|
131
|
+
if (Object.keys(set).length > 0)
|
|
132
|
+
patch.s = set;
|
|
133
|
+
if (del.length > 0)
|
|
134
|
+
patch.d = del;
|
|
135
|
+
if (orderChanged)
|
|
136
|
+
patch.order = nextIds;
|
|
137
|
+
return patch;
|
|
138
|
+
}
|
|
139
|
+
export function applyValue(prev, patch) {
|
|
140
|
+
if (!isObject(patch) || (patch.t !== 'v' && patch.t !== 'o' && patch.t !== 'l'))
|
|
141
|
+
return prev;
|
|
142
|
+
const node = patch;
|
|
143
|
+
if (node.t === 'v')
|
|
144
|
+
return node.v;
|
|
145
|
+
if (node.t === 'o')
|
|
146
|
+
return applyObject(prev, node);
|
|
147
|
+
return applyList(prev, node);
|
|
148
|
+
}
|
|
149
|
+
function applyObject(prev, patch) {
|
|
150
|
+
const base = isObject(prev) ? { ...prev } : {};
|
|
151
|
+
for (const key of patch.d ?? [])
|
|
152
|
+
delete base[key];
|
|
153
|
+
for (const [key, child] of Object.entries(patch.s))
|
|
154
|
+
base[key] = applyValue(base[key], child);
|
|
155
|
+
return base;
|
|
156
|
+
}
|
|
157
|
+
function applyList(prev, patch) {
|
|
158
|
+
const field = patch.id;
|
|
159
|
+
const items = Array.isArray(prev) ? prev.slice() : [];
|
|
160
|
+
const removed = new Set(patch.d ?? []);
|
|
161
|
+
const kept = [];
|
|
162
|
+
const index = new Map();
|
|
163
|
+
for (const item of items) {
|
|
164
|
+
const id = readId(item, field);
|
|
165
|
+
if (id !== undefined && removed.has(id))
|
|
166
|
+
continue;
|
|
167
|
+
if (id !== undefined)
|
|
168
|
+
index.set(id, kept.length);
|
|
169
|
+
kept.push(item);
|
|
170
|
+
}
|
|
171
|
+
for (const [id, child] of Object.entries(patch.s ?? {})) {
|
|
172
|
+
const at = index.get(id);
|
|
173
|
+
if (at === undefined) {
|
|
174
|
+
kept.push(applyValue(undefined, child));
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
kept[at] = applyValue(kept[at], child);
|
|
178
|
+
}
|
|
179
|
+
if (!patch.order)
|
|
180
|
+
return kept;
|
|
181
|
+
const byId = new Map();
|
|
182
|
+
for (const item of kept) {
|
|
183
|
+
const id = readId(item, field);
|
|
184
|
+
if (id !== undefined)
|
|
185
|
+
byId.set(id, item);
|
|
186
|
+
}
|
|
187
|
+
return patch.order.filter(id => byId.has(id)).map(id => byId.get(id));
|
|
188
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { planChunks } from "./cdc.js";
|
|
2
|
+
/**
|
|
3
|
+
* Session history is one canonical JSON array of the host event log.
|
|
4
|
+
* FastCDC is only for that blob, and only when a session is opened.
|
|
5
|
+
* The live tail is the events themselves, not these chunks.
|
|
6
|
+
*/
|
|
7
|
+
const PLAN_LIMIT = 8;
|
|
8
|
+
/**
|
|
9
|
+
* Sorted-key JSON, so the same log cuts into the same chunks.
|
|
10
|
+
* Array order is the host order.
|
|
11
|
+
*/
|
|
12
|
+
export function stableStringify(value) {
|
|
13
|
+
if (value === undefined)
|
|
14
|
+
return 'null';
|
|
15
|
+
if (value instanceof Date)
|
|
16
|
+
return JSON.stringify(value);
|
|
17
|
+
if (value === null || typeof value !== 'object')
|
|
18
|
+
return JSON.stringify(value) ?? 'null';
|
|
19
|
+
if (Array.isArray(value))
|
|
20
|
+
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
|
21
|
+
const record = value;
|
|
22
|
+
const keys = Object.keys(record).filter(key => record[key] !== undefined).sort();
|
|
23
|
+
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`;
|
|
24
|
+
}
|
|
25
|
+
export function canonicalBytes(value) {
|
|
26
|
+
return Buffer.from(stableStringify(value), 'utf8');
|
|
27
|
+
}
|
|
28
|
+
export function eventLogBytes(events) {
|
|
29
|
+
return canonicalBytes(Array.isArray(events) ? events : []);
|
|
30
|
+
}
|
|
31
|
+
const MESSAGE_TYPES = new Set(['user/message', 'assistant/message']);
|
|
32
|
+
function eventSeq(event) {
|
|
33
|
+
if (!event || typeof event !== 'object')
|
|
34
|
+
return undefined;
|
|
35
|
+
const seq = event.seq;
|
|
36
|
+
return typeof seq === 'number' ? seq : undefined;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* First seq of the follow opening page for this message budget.
|
|
40
|
+
* Same rule as the host history page: count append-origin user and assistant messages from the end.
|
|
41
|
+
*/
|
|
42
|
+
export function followTailStart(events, maxMessages) {
|
|
43
|
+
const list = Array.isArray(events) ? events : [];
|
|
44
|
+
let count = 0;
|
|
45
|
+
let cut = 0;
|
|
46
|
+
for (let index = list.length - 1; index >= 0; index -= 1) {
|
|
47
|
+
const event = list[index];
|
|
48
|
+
if (!event || typeof event !== 'object')
|
|
49
|
+
continue;
|
|
50
|
+
const record = event;
|
|
51
|
+
if (typeof record.type !== 'string' || !MESSAGE_TYPES.has(record.type) || record.surfaceOp !== 'append')
|
|
52
|
+
continue;
|
|
53
|
+
count += 1;
|
|
54
|
+
let groupStart = typeof record.seq === 'number' ? record.seq : index;
|
|
55
|
+
if (Array.isArray(record.sourceEventSeqs)) {
|
|
56
|
+
for (const source of record.sourceEventSeqs) {
|
|
57
|
+
if (typeof source === 'number' && source < groupStart)
|
|
58
|
+
groupStart = source;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (count >= maxMessages) {
|
|
62
|
+
cut = groupStart;
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return cut;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The prefix `session/follow` does not send.
|
|
70
|
+
* `beforeSeq` is the first seq of the follow opening page. That page is a suffix, so everything before it belongs to CDC.
|
|
71
|
+
*/
|
|
72
|
+
export function eventsBefore(events, beforeSeq) {
|
|
73
|
+
const list = Array.isArray(events) ? events : [];
|
|
74
|
+
const cut = list.findIndex(event => {
|
|
75
|
+
const seq = eventSeq(event);
|
|
76
|
+
return seq !== undefined && seq >= beforeSeq;
|
|
77
|
+
});
|
|
78
|
+
return cut < 0 ? list.slice() : list.slice(0, cut);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Events in `[fromSeq, beforeSeq)`. A missing `beforeSeq` runs through the end.
|
|
82
|
+
*/
|
|
83
|
+
export function eventsWindow(events, fromSeq, beforeSeq = null) {
|
|
84
|
+
const list = Array.isArray(events) ? events : [];
|
|
85
|
+
const start = list.findIndex(event => {
|
|
86
|
+
const seq = eventSeq(event);
|
|
87
|
+
return seq !== undefined && seq >= fromSeq;
|
|
88
|
+
});
|
|
89
|
+
if (start < 0)
|
|
90
|
+
return [];
|
|
91
|
+
if (beforeSeq == null)
|
|
92
|
+
return list.slice(start);
|
|
93
|
+
const end = list.findIndex((event, index) => {
|
|
94
|
+
if (index < start)
|
|
95
|
+
return false;
|
|
96
|
+
const seq = eventSeq(event);
|
|
97
|
+
return seq !== undefined && seq >= beforeSeq;
|
|
98
|
+
});
|
|
99
|
+
return end < 0 ? list.slice(start) : list.slice(start, end);
|
|
100
|
+
}
|
|
101
|
+
export function createSessionSnapshots() {
|
|
102
|
+
const plans = new Map();
|
|
103
|
+
const order = [];
|
|
104
|
+
function publish(sessionId, events) {
|
|
105
|
+
const list = Array.isArray(events) ? events : [];
|
|
106
|
+
const plan = { ...planChunks(eventLogBytes(list)), count: list.length };
|
|
107
|
+
const previous = plans.get(sessionId);
|
|
108
|
+
if (previous && previous.epoch === plan.epoch)
|
|
109
|
+
return previous;
|
|
110
|
+
plans.set(sessionId, plan);
|
|
111
|
+
const index = order.indexOf(sessionId);
|
|
112
|
+
if (index >= 0)
|
|
113
|
+
order.splice(index, 1);
|
|
114
|
+
order.push(sessionId);
|
|
115
|
+
while (order.length > PLAN_LIMIT) {
|
|
116
|
+
const old = order.shift();
|
|
117
|
+
if (old)
|
|
118
|
+
plans.delete(old);
|
|
119
|
+
}
|
|
120
|
+
return plan;
|
|
121
|
+
}
|
|
122
|
+
/** Manifest only. Chunk bodies stay on the chunk route. */
|
|
123
|
+
function manifest(sessionId) {
|
|
124
|
+
const plan = plans.get(sessionId);
|
|
125
|
+
if (!plan)
|
|
126
|
+
return { ok: false };
|
|
127
|
+
return {
|
|
128
|
+
ok: true,
|
|
129
|
+
sessionId,
|
|
130
|
+
epoch: plan.epoch,
|
|
131
|
+
totalSize: plan.totalSize,
|
|
132
|
+
hashes: plan.hashes,
|
|
133
|
+
count: plan.count,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function take(sessionId, hashes) {
|
|
137
|
+
const plan = plans.get(sessionId);
|
|
138
|
+
if (!plan)
|
|
139
|
+
return null;
|
|
140
|
+
const chunks = {};
|
|
141
|
+
for (const hash of hashes) {
|
|
142
|
+
if (chunks[hash])
|
|
143
|
+
continue;
|
|
144
|
+
const body = plan.chunks.get(hash);
|
|
145
|
+
if (!body)
|
|
146
|
+
return null;
|
|
147
|
+
chunks[hash] = body.toString('base64');
|
|
148
|
+
}
|
|
149
|
+
return { ok: true, sessionId, chunks };
|
|
150
|
+
}
|
|
151
|
+
return { publish, manifest, take };
|
|
152
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { toolError } from "./errors.js";
|
|
3
|
+
import { toolDefinitions } from "./tools.js";
|
|
4
|
+
/**
|
|
5
|
+
* Bind a new session to the current persona, and optionally record one fact.
|
|
6
|
+
* An empty persona text keeps the latest confirmed SOUL. Facts are not copied
|
|
7
|
+
* from another session. The model cannot call this.
|
|
8
|
+
* @param {import('./engine.js').Engine} engine
|
|
9
|
+
* @param {{ sessionId?: unknown, personaText?: unknown, fact?: unknown, idempotencyKey?: unknown }} input
|
|
10
|
+
*/
|
|
11
|
+
export async function provisionSession(engine, input) {
|
|
12
|
+
if (typeof input.sessionId !== 'string' || input.sessionId.trim() === '') {
|
|
13
|
+
return toolError('VALIDATION', 'sessionId is required.');
|
|
14
|
+
}
|
|
15
|
+
const sessionId = input.sessionId.trim();
|
|
16
|
+
if (!engine.isBot(sessionId))
|
|
17
|
+
return toolError('FORBIDDEN', 'Only a bot session can apply a persona.');
|
|
18
|
+
const personaText = typeof input.personaText === 'string' ? input.personaText.trim() : '';
|
|
19
|
+
if (personaText !== '') {
|
|
20
|
+
const persona = engine.confirmPersona(personaText);
|
|
21
|
+
engine.bindPersona(sessionId, persona.id);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
engine.ensureSession(sessionId);
|
|
25
|
+
if (engine.binding(sessionId).persona_version_id == null && engine.latestPersona()) {
|
|
26
|
+
engine.bindPersona(sessionId, engine.latestPersona().id);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const factText = typeof input.fact === 'string' ? input.fact.trim() : '';
|
|
30
|
+
if (factText === '')
|
|
31
|
+
return { ok: true, sessionId, fact: null };
|
|
32
|
+
const key = typeof input.idempotencyKey === 'string' && input.idempotencyKey.trim() !== ''
|
|
33
|
+
? input.idempotencyKey.trim()
|
|
34
|
+
: `provision:${sessionId}:${createHash('sha256').update(factText).digest('hex').slice(0, 16)}`;
|
|
35
|
+
const remember = toolDefinitions(engine).find(item => item.name === 'foundations_remember');
|
|
36
|
+
const fact = await remember.execute({
|
|
37
|
+
target: 'fact',
|
|
38
|
+
content: factText,
|
|
39
|
+
idempotencyKey: key,
|
|
40
|
+
}, { agent: { id: sessionId } });
|
|
41
|
+
if (fact?.ok === false)
|
|
42
|
+
return fact;
|
|
43
|
+
return { ok: true, sessionId, fact };
|
|
44
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of the Web router plugin.
|
|
3
|
+
*
|
|
4
|
+
* The whole feature lives in the browser: `client.js` mirrors the active
|
|
5
|
+
* Session and the open main panel into `location.hash` and restores them on
|
|
6
|
+
* `popstate`. Nothing is needed on the Host, so this entry only declares the
|
|
7
|
+
* plugin identity for the Loader.
|
|
8
|
+
*/
|
|
9
|
+
/** Plugin display name used by the Loader. */
|
|
10
|
+
export const name = 'dsh-bot-router';
|
|
11
|
+
/** No Host services are required. */
|
|
12
|
+
export const inject = [];
|
|
13
|
+
/** Host half is intentionally empty: routing is client-only. */
|
|
14
|
+
export function apply() { }
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** @type {Map<string, unknown>} */
|
|
2
|
+
const runtimes = new Map();
|
|
3
|
+
/**
|
|
4
|
+
* @param {string} dataDir
|
|
5
|
+
* @param {unknown} runtime
|
|
6
|
+
*/
|
|
7
|
+
export function publishRuntime(dataDir, runtime) {
|
|
8
|
+
if (runtime)
|
|
9
|
+
runtimes.set(dataDir, runtime);
|
|
10
|
+
else
|
|
11
|
+
runtimes.delete(dataDir);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* @param {string} dataDir
|
|
15
|
+
*/
|
|
16
|
+
export function runtimeFor(dataDir) {
|
|
17
|
+
return runtimes.get(dataDir) ?? null;
|
|
18
|
+
}
|
|
19
|
+
/** @type {Map<string, unknown>} */
|
|
20
|
+
const workRuntimes = new Map();
|
|
21
|
+
/**
|
|
22
|
+
* @param {string} dataDir
|
|
23
|
+
* @param {unknown} runtime
|
|
24
|
+
*/
|
|
25
|
+
export function publishWorkRuntime(dataDir, runtime) {
|
|
26
|
+
if (runtime)
|
|
27
|
+
workRuntimes.set(dataDir, runtime);
|
|
28
|
+
else
|
|
29
|
+
workRuntimes.delete(dataDir);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* @param {string} dataDir
|
|
33
|
+
*/
|
|
34
|
+
export function workRuntimeFor(dataDir) {
|
|
35
|
+
return workRuntimes.get(dataDir) ?? null;
|
|
36
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/** Remove one blank session's on-disk log. DSH has no delete RPC; session/list rescans these directories. */
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join, resolve, sep } from 'node:path';
|
|
4
|
+
const SESSION_ID = /^session-[A-Za-z0-9-]+$/;
|
|
5
|
+
/**
|
|
6
|
+
* Same project-directory key as @deepseek-ai/dsh-session-persistence-jsonl.
|
|
7
|
+
* @param {string} cwd
|
|
8
|
+
*/
|
|
9
|
+
export function projectKey(cwd) {
|
|
10
|
+
if (cwd.length === 0)
|
|
11
|
+
throw new Error('cannot encode an empty project path');
|
|
12
|
+
let readable = '';
|
|
13
|
+
let separatorRun = false;
|
|
14
|
+
for (let i = 0; i < cwd.length; i++) {
|
|
15
|
+
const ch = cwd[i];
|
|
16
|
+
if (ch === '/' || ch === '\\' || ch === ':') {
|
|
17
|
+
if (!separatorRun)
|
|
18
|
+
readable += '-';
|
|
19
|
+
separatorRun = true;
|
|
20
|
+
}
|
|
21
|
+
else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
|
|
22
|
+
readable += ch;
|
|
23
|
+
separatorRun = false;
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
readable += '~' + ch.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0');
|
|
27
|
+
separatorRun = false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return `--${(readable.replace(/^-+/, '') || 'root').slice(0, 251)}--`;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* @param {string} sessionsRoot
|
|
34
|
+
* @param {string} cwd
|
|
35
|
+
* @param {string} sessionId
|
|
36
|
+
*/
|
|
37
|
+
export function sessionDirectory(sessionsRoot, cwd, sessionId) {
|
|
38
|
+
if (!SESSION_ID.test(sessionId))
|
|
39
|
+
throw new Error('session id is not a storage name');
|
|
40
|
+
const root = resolve(sessionsRoot);
|
|
41
|
+
const dir = resolve(root, projectKey(cwd), sessionId);
|
|
42
|
+
if (dir !== root && !dir.startsWith(root + sep))
|
|
43
|
+
throw new Error('session path escapes the session root');
|
|
44
|
+
return dir;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* @param {string} root
|
|
48
|
+
* @param {string} target
|
|
49
|
+
*/
|
|
50
|
+
function inside(root, target) {
|
|
51
|
+
const base = resolve(root);
|
|
52
|
+
const file = resolve(target);
|
|
53
|
+
return file === base || file.startsWith(base + sep);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* On-disk mark beside the session log. The plugin's kind column is the behavior gate;
|
|
57
|
+
* this file is the mark you can see in the session directory.
|
|
58
|
+
* @param {{ sessionsRoot: string, cwd: string, sessionId: string, name?: string }} input
|
|
59
|
+
*/
|
|
60
|
+
export function writeBotMarker(input) {
|
|
61
|
+
const dir = sessionDirectory(input.sessionsRoot, input.cwd, input.sessionId);
|
|
62
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
63
|
+
const file = join(dir, 'bot.json');
|
|
64
|
+
const name = typeof input.name === 'string' ? input.name.trim() : '';
|
|
65
|
+
writeFileSync(file, `${JSON.stringify({ kind: 'bot', sessionId: input.sessionId, ...(name ? { name } : {}) }, null, 2)}\n`, { mode: 0o644 });
|
|
66
|
+
return file;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* @param {{ sessionsRoot: string, cacheFile: string, workspaceFile: string, sessionId: string, cwd: string }} input
|
|
70
|
+
*/
|
|
71
|
+
export function purgeSessionFiles(input) {
|
|
72
|
+
const dir = sessionDirectory(input.sessionsRoot, input.cwd, input.sessionId);
|
|
73
|
+
if (existsSync(dir)) {
|
|
74
|
+
if (lstatSync(dir).isSymbolicLink())
|
|
75
|
+
throw new Error('refusing to delete a symlink');
|
|
76
|
+
const realRoot = realpathSync(input.sessionsRoot);
|
|
77
|
+
const realDir = realpathSync(dir);
|
|
78
|
+
if (!inside(realRoot, realDir))
|
|
79
|
+
throw new Error('session path escapes the session root');
|
|
80
|
+
rmSync(dir, { recursive: true, force: true });
|
|
81
|
+
}
|
|
82
|
+
if (input.cacheFile !== '' && existsSync(input.cacheFile)) {
|
|
83
|
+
if (!lstatSync(input.cacheFile).isSymbolicLink())
|
|
84
|
+
rmSync(input.cacheFile, { force: true });
|
|
85
|
+
}
|
|
86
|
+
forgetWorkspaceId(input.workspaceFile, input.sessionId);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* @param {string} workspaceFile
|
|
90
|
+
* @param {string} sessionId
|
|
91
|
+
*/
|
|
92
|
+
export function forgetWorkspaceId(workspaceFile, sessionId) {
|
|
93
|
+
if (!existsSync(workspaceFile))
|
|
94
|
+
return;
|
|
95
|
+
const data = JSON.parse(readFileSync(workspaceFile, 'utf8'));
|
|
96
|
+
if (data?.global && Array.isArray(data.global.archivedSessionIds)) {
|
|
97
|
+
data.global.archivedSessionIds = data.global.archivedSessionIds.filter(id => id !== sessionId);
|
|
98
|
+
}
|
|
99
|
+
const workspaces = data?.tables?.workspaces;
|
|
100
|
+
if (workspaces && typeof workspaces === 'object') {
|
|
101
|
+
for (const row of Object.values(workspaces)) {
|
|
102
|
+
if (!row || typeof row !== 'object')
|
|
103
|
+
continue;
|
|
104
|
+
const record = row;
|
|
105
|
+
if (!Array.isArray(record.sessionIds))
|
|
106
|
+
continue;
|
|
107
|
+
record.sessionIds = record.sessionIds.filter(id => id !== sessionId);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
writeFileSync(workspaceFile, `${JSON.stringify(data, null, 2)}\n`);
|
|
111
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/** Last list line for each session. One JSON file, replaced atomically. */
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
const SESSION_ID = /^(?:session|worker)-[A-Za-z0-9-]+$/;
|
|
5
|
+
const MAX_PREVIEW = 80;
|
|
6
|
+
const MAX_ENTRIES = 500;
|
|
7
|
+
/**
|
|
8
|
+
* @param {string} file
|
|
9
|
+
*/
|
|
10
|
+
export function openSessionPreviews(file) {
|
|
11
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
12
|
+
let state = {};
|
|
13
|
+
try {
|
|
14
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'));
|
|
15
|
+
state = sanitize(parsed);
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
if (error && typeof error === 'object' && 'code' in error && error.code !== 'ENOENT')
|
|
19
|
+
throw error;
|
|
20
|
+
}
|
|
21
|
+
const save = () => {
|
|
22
|
+
const next = `${file}.${process.pid}.tmp`;
|
|
23
|
+
writeFileSync(next, JSON.stringify(state), { mode: 0o600 });
|
|
24
|
+
renameSync(next, file);
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
all() {
|
|
28
|
+
return { ...state };
|
|
29
|
+
},
|
|
30
|
+
/**
|
|
31
|
+
* @param {unknown} sessionId
|
|
32
|
+
* @param {unknown} preview
|
|
33
|
+
* @returns {{ ok: true, preview: string } | { ok: false, error: 'bad_session' | 'empty_preview' }}
|
|
34
|
+
*/
|
|
35
|
+
remember(sessionId, preview) {
|
|
36
|
+
if (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId))
|
|
37
|
+
return { ok: false, error: 'bad_session' };
|
|
38
|
+
const text = cleanPreview(preview);
|
|
39
|
+
if (text === '')
|
|
40
|
+
return { ok: false, error: 'empty_preview' };
|
|
41
|
+
if (state[sessionId] !== text) {
|
|
42
|
+
state[sessionId] = text;
|
|
43
|
+
save();
|
|
44
|
+
}
|
|
45
|
+
return { ok: true, preview: text };
|
|
46
|
+
},
|
|
47
|
+
/**
|
|
48
|
+
* Skip bad rows. A browser cache can contain ids this store will not keep.
|
|
49
|
+
* @param {unknown} incoming
|
|
50
|
+
*/
|
|
51
|
+
rememberAll(incoming) {
|
|
52
|
+
if (!incoming || typeof incoming !== 'object' || Array.isArray(incoming))
|
|
53
|
+
return { stored: 0 };
|
|
54
|
+
let changed = false;
|
|
55
|
+
let stored = 0;
|
|
56
|
+
for (const [sessionId, preview] of Object.entries(incoming)) {
|
|
57
|
+
if (stored >= MAX_ENTRIES)
|
|
58
|
+
break;
|
|
59
|
+
if (!SESSION_ID.test(sessionId))
|
|
60
|
+
continue;
|
|
61
|
+
const text = cleanPreview(preview);
|
|
62
|
+
if (text === '')
|
|
63
|
+
continue;
|
|
64
|
+
stored += 1;
|
|
65
|
+
if (state[sessionId] === text)
|
|
66
|
+
continue;
|
|
67
|
+
state[sessionId] = text;
|
|
68
|
+
changed = true;
|
|
69
|
+
}
|
|
70
|
+
if (changed)
|
|
71
|
+
save();
|
|
72
|
+
return { stored };
|
|
73
|
+
},
|
|
74
|
+
/**
|
|
75
|
+
* @param {string} sessionId
|
|
76
|
+
*/
|
|
77
|
+
forget(sessionId) {
|
|
78
|
+
if (!Object.prototype.hasOwnProperty.call(state, sessionId))
|
|
79
|
+
return;
|
|
80
|
+
delete state[sessionId];
|
|
81
|
+
save();
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* @param {unknown} parsed
|
|
87
|
+
* @returns {Record<string, string>}
|
|
88
|
+
*/
|
|
89
|
+
function sanitize(parsed) {
|
|
90
|
+
/** @type {Record<string, string>} */
|
|
91
|
+
const out = {};
|
|
92
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
93
|
+
return out;
|
|
94
|
+
for (const [sessionId, preview] of Object.entries(parsed)) {
|
|
95
|
+
if (!SESSION_ID.test(sessionId))
|
|
96
|
+
continue;
|
|
97
|
+
const text = cleanPreview(preview);
|
|
98
|
+
if (text === '')
|
|
99
|
+
continue;
|
|
100
|
+
out[sessionId] = text;
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* @param {unknown} value
|
|
106
|
+
*/
|
|
107
|
+
function cleanPreview(value) {
|
|
108
|
+
if (typeof value !== 'string')
|
|
109
|
+
return '';
|
|
110
|
+
return value.replace(/[\u0000-\u001f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_PREVIEW);
|
|
111
|
+
}
|