dsh-sidebar-sessions 0.1.5 → 0.2.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/lib/index.js CHANGED
@@ -1,3 +1,466 @@
1
- // Host half is intentionally empty: this plugin renders in the web client only.
2
- export const name = 'dsh-session-groups'
3
- export function apply() {}
1
+ /* dsh-sidebar-sessions — host half.
2
+ *
3
+ * Grouping state used to live in the browser's localStorage, which meant the
4
+ * Web GUI (http://127.0.0.1:3080) and the Desktop app (dsh-app://app) saw two
5
+ * unrelated copies, and a scheduled task that ran while the GUI was closed left
6
+ * its session ungrouped until someone opened the sidebar.
7
+ *
8
+ * This half owns one JSON file instead, and the client reaches it over the
9
+ * host webserver. Both shells serve that file from the same origin-independent
10
+ * path: Desktop forwards every `dsh-app://app/<path>` request to the same HTTP
11
+ * host, so a plain relative `fetch('/dsh-sidebar-sessions/api/...')` works in
12
+ * both without an extra bridge.
13
+ */
14
+ import fs from "node:fs";
15
+ import os from "node:os";
16
+ import path from "node:path";
17
+
18
+ import { applyOp, emptyState, normalizeRule, normalizeState, planProposals } from "./rules.js";
19
+
20
+ export const name = "dsh-sidebar-sessions";
21
+
22
+ /** Route prefix owned by this plugin; the client hard-codes the same base. */
23
+ const API_BASE = "/dsh-sidebar-sessions/api";
24
+
25
+ /** Marker header on writes: a cross-origin page cannot add it without a preflight. */
26
+ const WRITE_HEADER = "x-dsg-request";
27
+
28
+ const MAX_BODY_BYTES = 256 * 1024;
29
+
30
+ /** Hosts we answer for: the request must name this machine (kills DNS rebinding). */
31
+ const LOCAL_HOSTNAMES = new Set(["127.0.0.1", "localhost", "::1", "[::1]", "0.0.0.0", "[::]"]);
32
+ /** Names the Desktop shell presents when it forwards a request. */
33
+ const DESKTOP_HOSTS = new Set(["app", "dsh-app"]);
34
+
35
+ const LLM_TIMEOUT_MS = 25_000;
36
+ const LLM_MAX_PER_SYNC = 3;
37
+ const LLM_MIN_TITLE_LENGTH = 4;
38
+
39
+ function isLocalHost(hostHeader) {
40
+ const host = String(hostHeader || "").toLowerCase().trim();
41
+ if (!host) return false;
42
+ if (DESKTOP_HOSTS.has(host)) return true;
43
+ const bare = host.startsWith("[") ? host.slice(0, host.indexOf("]") + 1) : host.split(":")[0];
44
+ return LOCAL_HOSTNAMES.has(bare);
45
+ }
46
+
47
+ function sendJson(res, status, value) {
48
+ const payload = JSON.stringify(value);
49
+ res.writeHead(status, {
50
+ "content-type": "application/json; charset=utf-8",
51
+ "cache-control": "no-store",
52
+ "content-length": Buffer.byteLength(payload),
53
+ });
54
+ res.end(payload);
55
+ }
56
+
57
+ function readBody(req) {
58
+ return new Promise((resolve, reject) => {
59
+ const chunks = [];
60
+ let total = 0;
61
+ req.on("data", (chunk) => {
62
+ total += chunk.length;
63
+ if (total > MAX_BODY_BYTES) {
64
+ reject(new Error("请求体过大"));
65
+ req.destroy();
66
+ return;
67
+ }
68
+ chunks.push(chunk);
69
+ });
70
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
71
+ req.on("error", reject);
72
+ });
73
+ }
74
+
75
+ async function readJson(req) {
76
+ const text = await readBody(req);
77
+ if (!text.trim()) return {};
78
+ const value = JSON.parse(text);
79
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("请求体必须是 JSON 对象");
80
+ return value;
81
+ }
82
+
83
+ /** Atomic replace so a crash mid-write never truncates the state file. */
84
+ function writeFileAtomic(file, text) {
85
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
86
+ fs.mkdirSync(path.dirname(file), { recursive: true });
87
+ fs.writeFileSync(tmp, text, "utf8");
88
+ fs.renameSync(tmp, file);
89
+ }
90
+
91
+ function defaultStatePath() {
92
+ const home = (process.env.DSH_HOME || "").trim() || path.join(os.homedir(), ".dsh");
93
+ return path.join(home, "sidebar-sessions", "state.json");
94
+ }
95
+
96
+ /**
97
+ * The state file is the single authority: every read re-parses it and every
98
+ * write is a read-modify-write. Two shells (Web and Desktop) may be open at
99
+ * once, and a long-lived in-memory copy would clobber the other one.
100
+ */
101
+ class Store {
102
+ constructor(file) {
103
+ this.file = file;
104
+ }
105
+
106
+ read() {
107
+ try {
108
+ const text = fs.readFileSync(this.file, "utf8");
109
+ return normalizeState(JSON.parse(text));
110
+ } catch (error) {
111
+ if (error && error.code !== "ENOENT") {
112
+ try {
113
+ console.warn("[dsh-sidebar-sessions] state unreadable, starting empty:", error.message);
114
+ } catch {}
115
+ }
116
+ return normalizeState(emptyState());
117
+ }
118
+ }
119
+
120
+ write(state) {
121
+ try {
122
+ writeFileAtomic(this.file, JSON.stringify(state, null, 2));
123
+ } catch (error) {
124
+ try {
125
+ console.warn("[dsh-sidebar-sessions] state write failed:", error.message);
126
+ } catch {}
127
+ throw error;
128
+ }
129
+ return state;
130
+ }
131
+
132
+ /** Read-modify-write through a reducer. */
133
+ update(reducer) {
134
+ const outcome = reducer(this.read());
135
+ if (outcome && outcome.state && outcome.changed !== false) this.write(outcome.state);
136
+ return outcome;
137
+ }
138
+ }
139
+
140
+ let warnedNoWebServer = false;
141
+
142
+ function installRoutes(webServer, deps) {
143
+ if (!webServer || typeof webServer.register !== "function") {
144
+ if (!warnedNoWebServer) {
145
+ warnedNoWebServer = true;
146
+ try {
147
+ console.warn("[dsh-sidebar-sessions] no webServer service; the sidebar falls back to localStorage");
148
+ } catch {}
149
+ }
150
+ return () => {};
151
+ }
152
+ const collapse = (state) => ({
153
+ ...state,
154
+ // Virtual groups are a display concern; keep the wire payload honest.
155
+ virtualGroups: undefined,
156
+ });
157
+ const statePayload = (state, extra) => ({ ok: true, state: collapse(state), ...extra });
158
+
159
+ const dispose = webServer.register({
160
+ kind: "prefix",
161
+ path: "/dsh-sidebar-sessions",
162
+ handler: async (req, res) => {
163
+ try {
164
+ const store = deps.store;
165
+ if (!isLocalHost(req.headers && req.headers.host)) return sendJson(res, 403, { ok: false, error: "forbidden" });
166
+ const pathname = new URL(req.url || "/", "http://local").pathname;
167
+ if (req.method === "POST") {
168
+ const marker = req.headers && req.headers[WRITE_HEADER];
169
+ if (marker !== "1") return sendJson(res, 403, { ok: false, error: "missing request marker" });
170
+ const origin = String((req.headers && req.headers.origin) || "");
171
+ if (origin && !isLocalHost(origin.replace(/^https?:\/\//, ""))) {
172
+ return sendJson(res, 403, { ok: false, error: "bad origin" });
173
+ }
174
+ }
175
+
176
+ if (pathname === `${API_BASE}/state` && req.method === "GET") {
177
+ const state = store.read();
178
+ return sendJson(res, 200, statePayload(state, { meta: { statePath: store.file } }));
179
+ }
180
+
181
+ if (pathname === `${API_BASE}/models` && req.method === "GET") {
182
+ return sendJson(res, 200, { ok: true, ...(await collectModels(deps.llmRef.current)) });
183
+ }
184
+
185
+ if (pathname === `${API_BASE}/sync` && req.method === "POST") {
186
+ const body = await readJson(req);
187
+ const sessions = Array.isArray(body.sessions) ? body.sessions : [];
188
+ const schedules = Array.isArray(body.schedules) ? body.schedules : [];
189
+ const outcome = store.update((current) => {
190
+ const planned = planProposals(current, { sessions, schedules });
191
+ return { state: planned.state, changed: planned.changed, planned };
192
+ });
193
+ scheduleLlmSuggestions(deps, sessions);
194
+ const state = store.read();
195
+ return sendJson(res, 200, statePayload(state, {
196
+ meta: { statePath: store.file, proposed: outcome.planned ? outcome.planned.proposed : [], applied: outcome.planned ? outcome.planned.applied : [] },
197
+ }));
198
+ }
199
+
200
+ if (pathname === `${API_BASE}/op` && req.method === "POST") {
201
+ const body = await readJson(req);
202
+ const result = deps.store.update((current) => applyOp(current, body));
203
+ return sendJson(res, 200, statePayload(result.state, { applied: result.applied === true }));
204
+ }
205
+
206
+ return sendJson(res, 404, { ok: false, error: "not found" });
207
+ } catch (error) {
208
+ const message = error && error.message ? error.message : "request failed";
209
+ try {
210
+ console.warn("[dsh-sidebar-sessions] route error:", message);
211
+ } catch {}
212
+ if (!res.headersSent) sendJson(res, 400, { ok: false, error: message });
213
+ else {
214
+ try {
215
+ res.end();
216
+ } catch {}
217
+ }
218
+ }
219
+ },
220
+ });
221
+ return typeof dispose === "function" ? dispose : () => {};
222
+ }
223
+
224
+ async function collectModels(llm) {
225
+ if (!llm || typeof llm.listProviders !== "function") return { providers: [] };
226
+ try {
227
+ const providers = await llm.listProviders();
228
+ const rows = [];
229
+ for (const provider of Array.isArray(providers) ? providers : []) {
230
+ const id = String((provider && (provider.id || provider.name || provider.provider)) || "");
231
+ if (!id) continue;
232
+ let models = [];
233
+ try {
234
+ if (typeof llm.listModels === "function") models = await llm.listModels(id);
235
+ } catch {}
236
+ rows.push({
237
+ id,
238
+ name: String((provider && provider.name) || id),
239
+ models: (Array.isArray(models) ? models : []).map((model) => ({
240
+ id: String((model && (model.id || model.name)) || ""),
241
+ name: String((model && (model.name || model.id)) || ""),
242
+ })).filter((model) => model.id),
243
+ });
244
+ }
245
+ return { providers: rows };
246
+ } catch {
247
+ return { providers: [] };
248
+ }
249
+ }
250
+
251
+ /* ------------------------------------------------------------------ *
252
+ * Optional LLM fallback: when no rule explains a new session, ask a
253
+ * small model once. Its answer is only ever a proposal — the human still
254
+ * answers the consent bar, unless the group is on the "always allow" list.
255
+ * ------------------------------------------------------------------ */
256
+
257
+ const llmInFlight = new Set();
258
+ let llmLastCallAt = 0;
259
+
260
+ function llmPrompt(groups, sessions) {
261
+ const groupList = groups.map((group) => `- ${group.name}`).join("\n");
262
+ const sessionList = sessions.map((session) => `- ${session.id} :: ${session.title}`).join("\n");
263
+ return [
264
+ "你在给对话列表归组。下面给出已有分组和若干新会话标题。",
265
+ "对每个会话判断它最像哪个分组;拿不准就不要选。",
266
+ "",
267
+ "分组:",
268
+ groupList,
269
+ "",
270
+ "会话:",
271
+ sessionList,
272
+ "",
273
+ '只输出一行 JSON,形如 {"<sessionId>":"<分组名>"};不要输出任何解释或代码块。',
274
+ ].join("\n");
275
+ }
276
+
277
+ function parseLlmAnswer(text, groups, sessions) {
278
+ const raw = String(text || "");
279
+ const start = raw.indexOf("{");
280
+ const end = raw.lastIndexOf("}");
281
+ if (start < 0 || end <= start) return [];
282
+ let parsed;
283
+ try {
284
+ parsed = JSON.parse(raw.slice(start, end + 1));
285
+ } catch {
286
+ return [];
287
+ }
288
+ if (!parsed || typeof parsed !== "object") return [];
289
+ const names = new Set(groups.map((group) => group.name));
290
+ const ids = new Set(sessions.map((session) => session.id));
291
+ const out = [];
292
+ for (const [sessionId, groupName] of Object.entries(parsed)) {
293
+ if (!ids.has(sessionId)) continue;
294
+ const name = String(groupName || "").trim();
295
+ if (!names.has(name)) continue;
296
+ out.push({ sessionId, groupName: name });
297
+ }
298
+ return out;
299
+ }
300
+
301
+ function scheduleLlmSuggestions(deps, sessions) {
302
+ const llm = deps.llmRef.current;
303
+ const store = deps.store;
304
+ const state = store.read();
305
+ if (!llm || typeof llm.stream !== "function") return;
306
+ const classifier = state.settings.classifier;
307
+ if (classifier.mode !== "llm" || !classifier.provider || !classifier.model) return;
308
+ if (state.groups.length === 0) return;
309
+ if (Date.now() - llmLastCallAt < 20_000) return;
310
+ const candidates = [];
311
+ for (const session of Array.isArray(sessions) ? sessions : []) {
312
+ const id = session && session.id ? String(session.id) : "";
313
+ const title = String((session && session.title) || "").trim();
314
+ if (!id || title.length < LLM_MIN_TITLE_LENGTH) continue;
315
+ if (state.assign[id] || state.autoDone[id] || state.pending[id]) continue;
316
+ if (llmInFlight.has(id)) continue;
317
+ candidates.push({ id, title });
318
+ if (candidates.length >= LLM_MAX_PER_SYNC) break;
319
+ }
320
+ if (candidates.length === 0) return;
321
+ llmLastCallAt = Date.now();
322
+ for (const candidate of candidates) llmInFlight.add(candidate.id);
323
+ const finish = () => {
324
+ for (const candidate of candidates) llmInFlight.delete(candidate.id);
325
+ };
326
+ void (async () => {
327
+ const controller = new AbortController();
328
+ const timer = setTimeout(() => controller.abort(), LLM_TIMEOUT_MS);
329
+ try {
330
+ let text = "";
331
+ const stream = llm.stream({
332
+ provider: classifier.provider,
333
+ model: classifier.model,
334
+ messages: [{ role: "user", content: [{ type: "text", text: llmPrompt(state.groups, candidates) }] }],
335
+ signal: controller.signal,
336
+ });
337
+ for await (const chunk of stream) {
338
+ if (!chunk) continue;
339
+ if (chunk.type === "text-delta") text += String(chunk.text ?? chunk.delta ?? "");
340
+ else if (chunk.type === "text" && chunk.text) text += String(chunk.text);
341
+ }
342
+ for (const suggestion of parseLlmAnswer(text, state.groups, candidates)) {
343
+ try {
344
+ store.update((current) => applyOp(current, { op: "llm.proposal", sessionId: suggestion.sessionId, groupName: suggestion.groupName }));
345
+ } catch {}
346
+ }
347
+ } catch (error) {
348
+ try {
349
+ console.warn("[dsh-sidebar-sessions] llm classifier failed:", error && error.message);
350
+ } catch {}
351
+ } finally {
352
+ clearTimeout(timer);
353
+ finish();
354
+ }
355
+ })();
356
+ }
357
+
358
+ /* ------------------------------------------------------------------ *
359
+ * Agent tool: the agent may propose a group, but never outvote the human.
360
+ * ------------------------------------------------------------------ */
361
+
362
+ function registerTool(tools, store) {
363
+ if (!tools || typeof tools.register !== "function") return () => {};
364
+ const definition = {
365
+ name: "session_group",
366
+ description:
367
+ "Manage conversation groups in the sidebar. `list` shows groups, rules and pending proposals; `propose` suggests putting a conversation into a group (the human answers a consent bar, unless that group is already on the always-allow list); `status` reports where one conversation stands. Use it after finishing a scheduled task whose new conversation belongs in a fixed group.",
368
+ parameters: {
369
+ type: "object",
370
+ additionalProperties: false,
371
+ properties: {
372
+ action: { type: "string", enum: ["list", "propose", "status"], description: "Operation to perform." },
373
+ sessionId: {
374
+ type: "string",
375
+ description: "Target conversation id. Omit to use the current conversation (DSH_SESSION_ID).",
376
+ },
377
+ groupName: { type: "string", description: "Group to propose. Created on consent if it does not exist yet." },
378
+ reason: { type: "string", description: "Optional one-line reason shown in the consent bar." },
379
+ },
380
+ required: ["action"],
381
+ },
382
+ output: {
383
+ schema: {
384
+ type: "object",
385
+ additionalProperties: true,
386
+ properties: {
387
+ ok: { type: "boolean" },
388
+ message: { type: "string" },
389
+ groups: { type: "array", items: { type: "string" } },
390
+ pending: { type: "array", items: { type: "string" } },
391
+ },
392
+ },
393
+ render: (_args, value) => [{ type: "text", text: String((value && value.message) || "完成") }],
394
+ },
395
+ async execute(args, exec) {
396
+ const state = store.read();
397
+ const action = String(args.action || "");
398
+ const sessionId = String(args.sessionId || (exec && exec.agent && exec.agent.sessionId) || "");
399
+ if (action === "list") {
400
+ return {
401
+ ok: true,
402
+ groups: state.groups.map((group) => group.name),
403
+ rules: state.rules.map((rule) => ({ id: rule.id, groupName: rule.groupName, any: rule.any, schedules: rule.scheduleIds.length })),
404
+ pending: Object.entries(state.pending).map(([id, proposal]) => `${id} → ${proposal.groupName}`),
405
+ message:
406
+ `分组:${state.groups.map((group) => group.name).join("、") || "(无)"};` +
407
+ `规则 ${state.rules.length} 条;待确认 ${Object.keys(state.pending).length} 条。`,
408
+ };
409
+ }
410
+ if (action === "status") {
411
+ if (!sessionId) return { ok: false, message: "需要 sessionId" };
412
+ const groupId = state.assign[sessionId];
413
+ const group = state.groups.find((entry) => entry.id === groupId);
414
+ const proposal = state.pending[sessionId];
415
+ const done = state.autoDone[sessionId];
416
+ return {
417
+ ok: true,
418
+ groups: group ? [group.name] : [],
419
+ pending: proposal ? [proposal.groupName] : [],
420
+ message: group
421
+ ? `已在分组「${group.name}」`
422
+ : proposal
423
+ ? `待用户确认:是否归入「${proposal.groupName}」`
424
+ : done
425
+ ? `用户已处理过(${done}),不再自动归类`
426
+ : "未分组,也没有待确认建议",
427
+ };
428
+ }
429
+ if (action === "propose") {
430
+ if (!sessionId) return { ok: false, message: "需要 sessionId" };
431
+ const groupName = String(args.groupName || "").trim();
432
+ if (!groupName) return { ok: false, message: "需要 groupName" };
433
+ const result = store.update((current) => applyOp(current, { op: "propose", sessionId, groupName }));
434
+ if (result && result.skipped === "assigned") return { ok: true, message: "该会话已经在分组里,未改动。" };
435
+ if (result && result.applied === true) return { ok: true, message: `已归入「${groupName}」(该组已在白名单,无需确认)。` };
436
+ return { ok: true, message: `已提交建议:把该会话归入「${groupName}」。等用户在侧栏许可条上确认后才生效。` };
437
+ }
438
+ return { ok: false, message: `未知 action:${action}` };
439
+ },
440
+ };
441
+ const dispose = tools.register(definition);
442
+ return typeof dispose === "function" ? dispose : () => {};
443
+ }
444
+
445
+ export function apply(ctx, config) {
446
+ const file = (config && config.statePath) || process.env.DSH_SIDEBAR_SESSIONS_STATE || defaultStatePath();
447
+ const deps = { store: new Store(file), llmRef: { current: undefined } };
448
+
449
+ /* Services must be injected before use: cordis raises "cannot get property
450
+ * without inject" on an undeclared access, and a headless profile may have
451
+ * no webServer or llm at all. Each sub-plugin simply waits for its service. */
452
+ ctx.inject(["llm"], (llmCtx) => {
453
+ deps.llmRef.current = llmCtx.llm;
454
+ llmCtx.effect(() => () => {
455
+ deps.llmRef.current = undefined;
456
+ }, "dsh-sidebar-sessions: llm handle");
457
+ });
458
+
459
+ ctx.inject(["webServer"], (webCtx) => {
460
+ webCtx.effect(() => installRoutes(webCtx.webServer, deps), "dsh-sidebar-sessions: grouping api");
461
+ });
462
+
463
+ ctx.inject(["tools"], (toolCtx) => {
464
+ toolCtx.effect(() => registerTool(toolCtx.tools, deps.store), "dsh-sidebar-sessions: session_group tool");
465
+ });
466
+ }