@idoall/dsh-notify 0.2.2

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/core.js ADDED
@@ -0,0 +1,170 @@
1
+ export const USER_KINDS = new Set(['approval', 'question', 'plan-review', 'completed', 'failed', 'job-end', 'subagent-end', 'workflow-end']);
2
+
3
+ /**
4
+ * `exit_plan_mode` has no question text of its own, so the tool/call path uses this until the
5
+ * matching `user-questions/request` (which does carry "Approve this plan…") can replace it.
6
+ * Never let it clobber a real question if both paths fire.
7
+ */
8
+ export const PLAN_REVIEW_FALLBACK = '计划待审:请在页面里查看并批准或拒绝';
9
+
10
+ const isUnlinkedKey = (mergeKey) => typeof mergeKey === 'string' && mergeKey.includes(':unlinked:');
11
+
12
+ function preferredQuestionBody(existing, incoming) {
13
+ const next = sanitizeBody(incoming);
14
+ const previous = existing?.body;
15
+ if (!previous) return next;
16
+ if (next === PLAN_REVIEW_FALLBACK) return previous;
17
+ if (previous === PLAN_REVIEW_FALLBACK && next) return next;
18
+ return next || previous;
19
+ }
20
+
21
+ export function sanitizeBody(body = '', verbosity = 'normal') {
22
+ const text = String(body)
23
+ .replace(/(?:[A-Za-z]:\\|\/)[^\s]+/g, '[path]')
24
+ .replace(/\b(?:token|secret|key|password)\s*[:=]\s*\S+/gi, '[redacted]')
25
+ .replace(/\$\{?\w+\}?/g, '[redacted]');
26
+ return (verbosity === 'detailed' ? text : text.replace(/\s+/g, ' ').slice(0, 120)).slice(0, 240);
27
+ }
28
+
29
+ export function isNotifiableEnd(reason) {
30
+ const kind = typeof reason === 'string' ? reason : reason?.kind;
31
+ return kind === 'completed' || kind === 'error';
32
+ }
33
+
34
+ /**
35
+ * Events become records. The map is memory-only and deliberately small: a record exists so the live
36
+ * delivery can merge an interaction that is asked and then decided into one notification, and so the
37
+ * toast can tell a still-pending question from a settled one. Nothing survives the process, so the
38
+ * oldest settled entries are simply dropped once the map grows past `RECORD_MEMORY`.
39
+ */
40
+ export const RECORD_MEMORY = 100;
41
+
42
+ export class EventReducer {
43
+ #seq = 0;
44
+ constructor(now = () => Date.now()) {
45
+ this.now = now;
46
+ this.records = new Map();
47
+ }
48
+ makeId() { this.#seq += 1; const nonce = globalThis.crypto?.randomUUID?.() || Math.random().toString(36).slice(2); return `nt-${this.now()}-${this.#seq}-${nonce}`; }
49
+ #trim() {
50
+ while (this.records.size > RECORD_MEMORY) {
51
+ let oldest = null;
52
+ for (const record of this.records.values()) {
53
+ if (record.phase === 'open') continue; // something still waits on the user: never the one dropped
54
+ if (!oldest || record.at < oldest.at) oldest = record;
55
+ }
56
+ if (!oldest) return; // every record is pending; keep them all
57
+ this.records.delete(oldest.mergeKey);
58
+ }
59
+ }
60
+ upsert(input) {
61
+ if (!USER_KINDS.has(input.kind) || typeof input.mergeKey !== 'string') return null;
62
+ const existing = this.records.get(input.mergeKey);
63
+ if (existing) {
64
+ // An interrupted turn emits no `approval/decided`, so a replay re-asks an interaction the user
65
+ // already settled. A resolved interaction stays resolved; a replay of it is not news.
66
+ if (existing.phase !== 'open' && (input.phase ?? 'settled') === 'open') return null;
67
+ return Object.assign(existing, input, { eventId: existing.eventId });
68
+ }
69
+ const record = { eventId: this.makeId(), kind: input.kind, mergeKey: input.mergeKey, sessionId: input.sessionId, title: sanitizeBody(input.title || input.kind), body: sanitizeBody(input.body, input.verbosity), at: this.now(), phase: input.phase || 'settled', outcome: input.outcome, deepLink: input.deepLink, ...(Number.isSafeInteger(input.turn) && input.turn > 0 ? { turn: input.turn } : {}) };
70
+ this.records.set(input.mergeKey, record);
71
+ this.#trim();
72
+ return record;
73
+ }
74
+ approvalAsked(event, sessionId) {
75
+ return this.upsert({ kind: 'approval', mergeKey: `approval:${event.id}`, sessionId, title: '需要审批', body: event.reason || event.toolName, phase: 'open', turn: event.turn });
76
+ }
77
+ approvalRequest(next) { try { /* observation only */ } finally { return next?.(); } }
78
+ approvalDecided(id, outcome) {
79
+ const record = this.records.get(`approval:${id}`);
80
+ if (!record) return null;
81
+ record.phase = outcome === 'unavailable' || outcome === 'cancelled' ? 'expired' : 'settled';
82
+ record.outcome = outcome;
83
+ return record;
84
+ }
85
+ #openOf(sessionId, kind) {
86
+ const open = [];
87
+ for (const record of this.records.values()) {
88
+ if (record.sessionId === sessionId && record.kind === kind && record.phase === 'open') open.push(record);
89
+ }
90
+ return open;
91
+ }
92
+ question(event) {
93
+ const kind = event.intent?.kind === 'plan-review' ? 'plan-review' : 'question';
94
+ const title = kind === 'plan-review' ? '计划待审' : '需要回复';
95
+ const incomingCallId = typeof event.callId === 'string' && event.callId !== '' ? event.callId : '';
96
+ const turn = Number.isSafeInteger(event.turn) && event.turn > 0 ? { turn: event.turn } : {};
97
+ // A profile plugin sees both the live `tool/call` (real callId) and the `user-questions/request`
98
+ // waterfall (no source-proven callId). Those are one interaction, not two: merge only that
99
+ // complementary pair. Never FIFO-bind two unlinked records or two different callIds — concurrent
100
+ // requests can reverse, and that is why unlinked keys exist.
101
+ const open = this.#openOf(event.sessionId, kind);
102
+ if (open.length === 1) {
103
+ const current = open[0];
104
+ const currentLinked = !isUnlinkedKey(current.mergeKey);
105
+ const incomingLinked = incomingCallId !== '';
106
+ if (currentLinked !== incomingLinked) {
107
+ if (incomingLinked) {
108
+ const mergeKey = `question:${event.sessionId}:${incomingCallId}`;
109
+ if (current.mergeKey !== mergeKey) {
110
+ this.records.delete(current.mergeKey);
111
+ current.mergeKey = mergeKey;
112
+ this.records.set(mergeKey, current);
113
+ }
114
+ }
115
+ return this.upsert({ kind, mergeKey: current.mergeKey, sessionId: event.sessionId, title, body: preferredQuestionBody(current, event.title), phase: 'open', ...turn });
116
+ }
117
+ }
118
+ const callId = incomingCallId || `unlinked:${event.uniqueId || this.makeId()}`;
119
+ return this.upsert({ kind, mergeKey: `question:${event.sessionId}:${callId}`, sessionId: event.sessionId, title, body: event.title, phase: 'open', ...turn });
120
+ }
121
+ settleQuestionKey(mergeKey, outcome = 'settled') {
122
+ if (typeof mergeKey !== 'string') return null;
123
+ const record = this.records.get(mergeKey);
124
+ if (!record || record.phase !== 'open' || (record.kind !== 'question' && record.kind !== 'plan-review')) return null;
125
+ record.phase = outcome === 'settled' ? 'settled' : 'expired';
126
+ record.outcome = outcome;
127
+ return record;
128
+ }
129
+ questionResult({ sessionId, callId, outcome = 'settled' }) {
130
+ if (!callId) return null;
131
+ return this.settleQuestionKey(`question:${sessionId}:${callId}`, outcome);
132
+ }
133
+ /**
134
+ * At the end of a turn nothing can still be waiting on that session, so any record left open is a
135
+ * leftover whose decision event we never saw. Expiring it here matters: a single stale open record
136
+ * used to shadow every later notification (see the client toast queue).
137
+ */
138
+ expireOpenForSession(sessionId, endedTurn = Number.POSITIVE_INFINITY) {
139
+ const expired = [];
140
+ for (const record of this.records.values()) {
141
+ if (record.sessionId !== sessionId || record.phase !== 'open') continue;
142
+ // During a rebuild we only know which turns already ended; a record asked during a later turn
143
+ // (or without a turn) is left alone so a live question is never closed by a restart.
144
+ if (Number.isSafeInteger(record.turn) ? record.turn > endedTurn : endedTurn !== Number.POSITIVE_INFINITY) continue;
145
+ record.phase = 'expired';
146
+ record.outcome = 'expired';
147
+ expired.push(record);
148
+ }
149
+ return expired;
150
+ }
151
+ turnEnd(event) {
152
+ if (event.origin === 'subagent' || !isNotifiableEnd(event.reason)) return null;
153
+ const reason = typeof event.reason === 'string' ? event.reason : event.reason.kind;
154
+ const failed = reason === 'error';
155
+ return this.upsert({ kind: failed ? 'failed' : 'completed', mergeKey: `${failed ? 'fail' : 'turn'}:${event.sessionId}:${event.turn}`, sessionId: event.sessionId, title: failed ? '运行失败' : '任务完成', body: event.body || event.reason?.error?.message, phase: 'settled', outcome: reason, turn: event.turn });
156
+ }
157
+ agentError(event) {
158
+ return this.upsert({ kind: 'failed', mergeKey: `fail:${event.sessionId}:${event.turn}`, sessionId: event.sessionId, title: '运行失败', body: event.message || event.error?.message || String(event.error || ''), phase: 'settled', outcome: 'error', turn: event.turn });
159
+ }
160
+ }
161
+
162
+ export function validateRequest({ rejection, authenticated, originOK = true, bodyBytes = 0, limit = 16384, fields = {}, allowed = [] }) {
163
+ if (rejection === undefined && authenticated === false) return 401;
164
+ if (rejection === 401 || rejection === 403) return rejection;
165
+ if (rejection !== undefined) return 403;
166
+ if (!originOK) return 403;
167
+ if (bodyBytes > limit || Object.keys(fields).some((key) => !allowed.includes(key))) return 400;
168
+ return 200;
169
+ }
170
+
package/dist/index.js ADDED
@@ -0,0 +1,481 @@
1
+ import { createHash } from 'node:crypto';
2
+ import z from '@deepseek-ai/schemastery';
3
+ import { EventReducer, PLAN_REVIEW_FALLBACK, validateRequest } from './core.js';
4
+ import { createBuffer, createSettings } from './buffer.js';
5
+ import { createSoundLibrary } from './sounds.js';
6
+ import { BUILTIN_SOUNDS, SOUND_BYTES } from './sound-choices.js';
7
+
8
+ export const name = 'dsh-notify';
9
+ export const inject = [];
10
+ export const Config = z.object({
11
+ dataDir: z.string().description('Absolute path to the profile-owned dsh-notify data directory.'),
12
+ // 0 restores the old "notify on every finished turn" behaviour.
13
+ completionGraceMs: z.number().step(1).min(0).max(600_000).default(8_000).description('How long a finished turn must stay quiet before it counts as a finished task (ms).'),
14
+ });
15
+ export { EventReducer, PLAN_REVIEW_FALLBACK, sanitizeBody, validateRequest } from './core.js';
16
+ export { createBuffer, createSettings, BUFFER_LIMIT } from './buffer.js';
17
+ export { createSoundLibrary } from './sounds.js';
18
+ export { BUILTIN_SOUNDS, SOUND_BYTES, parseSoundChoice, validSoundName } from './sound-choices.js';
19
+
20
+ const BASE = '/plugins/dsh-notify';
21
+ const BODY_CAP = 16 * 1024;
22
+ const COMMAND_LIKE = /&&|\|\||[|;]|\$\(|`/;
23
+ /**
24
+ * A job label is usually the raw command line, which makes an unusable notification title. Keep the
25
+ * title human and only carry a label into the body when it reads like a description, not a command.
26
+ */
27
+ const JOB_STATUS_LABEL = Object.freeze({ completed: '已完成', failed: '失败', error: '出错', aborted: '已中止', cancelled: '已取消', killed: '已终止' });
28
+ export function jobNotification(snapshot = {}) {
29
+ const status = typeof snapshot.status === 'string' ? snapshot.status.trim().toLowerCase() : '';
30
+ const label = typeof snapshot.label === 'string' ? snapshot.label.trim() : '';
31
+ const failed = /fail|error|abort/.test(status);
32
+ const readable = label !== '' && !COMMAND_LIKE.test(label) && label.length <= 60;
33
+ const outcome = JOB_STATUS_LABEL[status] ?? status;
34
+ return { title: failed ? '后台任务失败' : '后台任务结束', body: readable ? label : (outcome || undefined) };
35
+ }
36
+ const DEFAULT_SETTINGS = Object.freeze({ verbosity: 'normal', toastPosition: 'conversation', toastEnabled: true, subtaskNotify: false, soundEnabled: true, sound: 'chime' });
37
+ const SETTING_KEYS = Object.freeze(Object.keys(DEFAULT_SETTINGS));
38
+ /**
39
+ * Only the settings this version knows about are adopted — or written back. A file left by an older
40
+ * version must not smuggle its own shape into the config, and a request must not add keys that the
41
+ * plugin would then hand straight back to the page.
42
+ */
43
+ const pickSettings = (value = {}) => Object.fromEntries(Object.entries(value ?? {}).filter(([key]) => SETTING_KEYS.includes(key)));
44
+
45
+ function contextService(ctx, name) {
46
+ const explicit = ctx?.get?.(name);
47
+ if (explicit !== undefined && explicit !== null) return explicit;
48
+ const reflected = ctx?.reflect?.get?.(name, true);
49
+ if (reflected !== undefined && reflected !== null) return reflected;
50
+ // Plain test doubles expose services as direct properties. A real Cordis
51
+ // proxy intentionally throws for undeclared direct service reads.
52
+ try { return ctx?.[name]; } catch { return undefined; }
53
+ }
54
+ const sessionIdOf = (agent) => agent?.session?.id ?? agent?.id;
55
+ const originOf = (session) => session?.header?.origin;
56
+
57
+ function sendJson(res, status, payload) {
58
+ res.statusCode = status;
59
+ res.setHeader('content-type', 'application/json; charset=utf-8');
60
+ res.setHeader('cache-control', 'no-store');
61
+ res.end(JSON.stringify(payload));
62
+ }
63
+ function sameOriginRequest(req) {
64
+ const site = String(req.headers?.['sec-fetch-site'] ?? '').toLowerCase();
65
+ if (site && site !== 'same-origin' && site !== 'same-site' && site !== 'none') return false;
66
+ const origin = req.headers?.origin;
67
+ if (!origin) return true;
68
+ const host = req.headers?.host;
69
+ try { return new URL(String(origin)).host === host; } catch { return false; }
70
+ }
71
+ function digest(value) { return createHash('sha256').update(String(value)).digest('base64url'); }
72
+ function requestOwnerHash(req) {
73
+ const credential = String(req.headers?.cookie || req.headers?.authorization || '');
74
+ return credential ? digest(credential) : '';
75
+ }
76
+ function requestSessionKey(req) {
77
+ const peer = String(req.socket?.remoteAddress || 'unknown');
78
+ return digest(`${requestOwnerHash(req)}\0${peer}`);
79
+ }
80
+ function createSessionLimiter({ now = () => Date.now(), windowMs = 60_000 } = {}) {
81
+ const buckets = new Map();
82
+ return (req, action, limit) => {
83
+ const time = now();
84
+ const key = `${requestSessionKey(req)}:${action}`;
85
+ let bucket = buckets.get(key);
86
+ if (!bucket || time >= bucket.resetAt) { bucket = { count: 0, resetAt: time + windowMs }; buckets.set(key, bucket); }
87
+ if (bucket.count >= limit) return Math.max(1, Math.ceil((bucket.resetAt - time) / 1000));
88
+ bucket.count += 1;
89
+ return 0;
90
+ };
91
+ }
92
+ function enforceLimit(req, res, limiter, action, limit) {
93
+ const retryAfter = limiter(req, action, limit);
94
+ if (!retryAfter) return true;
95
+ res.statusCode = 429;
96
+ res.setHeader('retry-after', String(retryAfter));
97
+ res.setHeader('cache-control', 'no-store');
98
+ res.end('too many requests');
99
+ return false;
100
+ }
101
+ async function readBody(req, limit) {
102
+ const declared = Number(req.headers?.['content-length'] ?? 0);
103
+ if (Number.isFinite(declared) && declared > limit) throw Object.assign(new Error('request body too large'), { status: 413 });
104
+ const chunks = []; let size = 0;
105
+ for await (const chunk of req) {
106
+ size += chunk.byteLength;
107
+ if (size > limit) throw Object.assign(new Error('request body too large'), { status: 413 });
108
+ chunks.push(chunk);
109
+ }
110
+ return Buffer.concat(chunks);
111
+ }
112
+ async function readJson(req, limit = BODY_CAP) {
113
+ const contentType = String(req.headers?.['content-type'] ?? '').split(';', 1)[0].trim().toLowerCase();
114
+ if (contentType !== 'application/json') throw Object.assign(new Error('content-type must be application/json'), { status: 415 });
115
+ const declared = Number(req.headers?.['content-length'] ?? 0);
116
+ if (Number.isFinite(declared) && declared > limit) throw Object.assign(new Error('request body too large'), { status: 413 });
117
+ const chunks = [];
118
+ let size = 0;
119
+ for await (const chunk of req) {
120
+ size += chunk.byteLength;
121
+ if (size > limit) { req.resume?.(); throw Object.assign(new Error('request body too large'), { status: 413 }); }
122
+ chunks.push(chunk);
123
+ }
124
+ try {
125
+ const value = JSON.parse(Buffer.concat(chunks, size).toString('utf8'));
126
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('body must be an object');
127
+ return { value, size };
128
+ } catch (error) { throw Object.assign(error, { status: 400 }); }
129
+ }
130
+ function schemaStatus(fields, allowed) {
131
+ return validateRequest({ rejection: undefined, originOK: true, fields, allowed });
132
+ }
133
+ function registerRoute(ctx, webServer, route) {
134
+ const register = () => webServer.register(route);
135
+ return ctx?.effect ? ctx.effect(register, `dsh-notify: ${route.path}`) : register();
136
+ }
137
+ function registerSensitive(ctx, webServer, connection, path, methods, handler) {
138
+ const allowed = Array.isArray(methods) ? methods : [methods];
139
+ return registerRoute(ctx, webServer, {
140
+ kind: 'exact', path: `${BASE}${path}`,
141
+ handler: async (req, res) => {
142
+ const rejection = connection.requestRejection(req);
143
+ if (rejection !== undefined) { res.statusCode = rejection; res.end(rejection === 401 ? 'unauthorized' : 'forbidden'); return; }
144
+ if (!allowed.includes(req.method)) { res.statusCode = 405; res.setHeader('allow', allowed.join(', ')); res.end(); return; }
145
+ if (req.method !== 'GET' && !sameOriginRequest(req)) { res.statusCode = 403; res.end('forbidden'); return; }
146
+ try { await handler(req, res); } catch (error) { sendJson(res, error?.status ?? 500, { error: error?.status ? error.message : 'internal error' }); }
147
+ },
148
+ });
149
+ }
150
+
151
+ export async function apply(ctx, config = {}) {
152
+ // No store, no history: the buffer holds what has not been delivered yet, and preferences are the
153
+ // only thing that outlives the process.
154
+ const buffer = createBuffer();
155
+ const preferences = createSettings({ dataDir: config.dataDir, keys: SETTING_KEYS });
156
+ const settings = { ...DEFAULT_SETTINGS, ...pickSettings(preferences.get()) };
157
+ const reducer = new EventReducer(() => Date.now());
158
+ const diagnostics = { eventErrors: 0, services: {} };
159
+ const sounds = createSoundLibrary({ dataDir: config.dataDir });
160
+ // Tool call IDs remain available for authoritative replay/result handling.
161
+ // A live user-questions/request has no source-proven causal callId, therefore
162
+ // this host must not infer one from an arrival queue or FIFO ordering.
163
+ const pendingToolCalls = new Map();
164
+ const pendingFor = (sessionId) => {
165
+ let calls = pendingToolCalls.get(sessionId);
166
+ if (!calls) { calls = new Set(); pendingToolCalls.set(sessionId, calls); }
167
+ return calls;
168
+ };
169
+ const removePending = (sessionId, callId) => {
170
+ const calls = pendingToolCalls.get(sessionId);
171
+ if (!calls) return;
172
+ calls.delete(callId);
173
+ if (!calls.size) pendingToolCalls.delete(sessionId);
174
+ };
175
+ const pendingErrors = new Map();
176
+ const limitSession = createSessionLimiter({ now: config.now, windowMs: config.rateLimitWindowMs });
177
+
178
+ /**
179
+ * One record, one delivery: the buffer is the whole hand-off. `ctx.emit` stays for anything that
180
+ * wants to observe records in-process (the CLI diagnostics and the tests do).
181
+ */
182
+ const dispatch = async (record) => {
183
+ if (!record) return null;
184
+ buffer.push(record);
185
+ ctx?.emit?.('dsh-notify/record', record);
186
+ return record;
187
+ };
188
+ const safely = (work) => { Promise.resolve().then(work).catch(() => { diagnostics.eventErrors += 1; }); };
189
+ /**
190
+ * A turn ending is not the task finishing. With goals, queued prompts or an agent that keeps
191
+ * working, one job produces several turns — and therefore several "任务完成" toasts, which is
192
+ * exactly the noise the user could not reconcile. So a notifiable turn end is *deferred*: if the
193
+ * session starts working again inside the grace window (which is what a goal round does), nothing is
194
+ * recorded at all; if a goal is engaged, nothing is recorded until that goal ends.
195
+ */
196
+ const completionGraceMs = Number.isSafeInteger(config.completionGraceMs) ? config.completionGraceMs : 8_000;
197
+ const deferredCompletions = new Map(); // sessionId -> { payload, timer }
198
+ const engagedGoals = new Set(); // sessionIds whose goal loop is still running
199
+ const clearDeferred = (sessionId) => { const entry = deferredCompletions.get(sessionId); if (entry?.timer) clearTimeout(entry.timer); };
200
+ const flushCompletion = async (sessionId) => {
201
+ const entry = deferredCompletions.get(sessionId);
202
+ if (!entry) return;
203
+ deferredCompletions.delete(sessionId);
204
+ if (entry.timer) clearTimeout(entry.timer);
205
+ await dispatch(reducer.turnEnd(entry.payload));
206
+ };
207
+ const cancelCompletion = (sessionId) => {
208
+ const entry = deferredCompletions.get(sessionId);
209
+ if (!entry) return;
210
+ clearDeferred(sessionId);
211
+ deferredCompletions.delete(sessionId);
212
+ diagnostics.deferredCancelled = (diagnostics.deferredCancelled ?? 0) + 1;
213
+ };
214
+ const deferCompletion = (sessionId, payload) => {
215
+ const existing = deferredCompletions.get(sessionId);
216
+ if (existing?.timer) clearTimeout(existing.timer);
217
+ // An engaged goal holds the payload with no timer: the announcement waits for the goal to end.
218
+ // Grace 0 is the old "every finished turn" behaviour and flushes immediately.
219
+ if (engagedGoals.has(sessionId)) {
220
+ deferredCompletions.set(sessionId, { payload, timer: null });
221
+ return;
222
+ }
223
+ if (completionGraceMs === 0) {
224
+ deferredCompletions.set(sessionId, { payload, timer: null });
225
+ void flushCompletion(sessionId).catch(() => { diagnostics.eventErrors += 1; });
226
+ return;
227
+ }
228
+ const timer = setTimeout(() => { void flushCompletion(sessionId).catch(() => { diagnostics.eventErrors += 1; }); }, completionGraceMs);
229
+ if (typeof timer.unref === 'function') timer.unref();
230
+ deferredCompletions.set(sessionId, { payload, timer });
231
+ };
232
+ /**
233
+ * Never let one of our listeners hold the host's event chain forever. Cordis awaits listener
234
+ * promises, so a listener that waits on a stuck write would wedge session creation, the HTTP API
235
+ * and every other plugin. This bounds our own work: past the deadline we resolve with the fallback
236
+ * and record the timeout, so the host always moves on.
237
+ */
238
+ const bounded = async (work, ms = 20_000, fallback = undefined) => {
239
+ let timer;
240
+ try {
241
+ return await Promise.race([
242
+ Promise.resolve().then(work),
243
+ new Promise((resolve) => { timer = setTimeout(() => { diagnostics.eventErrors += 1; resolve(fallback); }, ms); }),
244
+ ]);
245
+ } catch { diagnostics.eventErrors += 1; return fallback; } finally { clearTimeout(timer); }
246
+ };
247
+
248
+ // A live `tool/call` is the ONLY authoritative live signal for a human interaction:
249
+ // dsh-user-questions emits `user-questions/request` through scopeTarget(agent, agent), which a
250
+ // root-scope plugin never receives, so a profile plugin must read the session event stream.
251
+ // It carries the real callId and the raw arguments, so this is not FIFO guessing.
252
+ const interactionBody = (name, rawArguments) => {
253
+ if (name === 'exit_plan_mode') return PLAN_REVIEW_FALLBACK;
254
+ try {
255
+ const parsed = JSON.parse(rawArguments || '{}');
256
+ const list = Array.isArray(parsed.questions) ? parsed.questions.filter((item) => item && typeof item === 'object') : [];
257
+ const first = list[0] ?? {};
258
+ const text = [first.header, first.question].map((part) => typeof part === 'string' ? part.trim() : '').filter(Boolean).join(':');
259
+ return `${text || '有人在等你回复'}${list.length > 1 ? `(共 ${list.length} 个问题)` : ''}`;
260
+ } catch { return '有人在等你回复'; }
261
+ };
262
+
263
+ /**
264
+ * `approval/asked` is the one interactive event that carries no `turn` of its own (its payload is
265
+ * `{id, toolName, callId, reason}`), while every event around it does. Without the turn a record is
266
+ * indistinguishable from a live question at rebuild time, so `expireOpenForSession` leaves it alone
267
+ * and an interrupted approval can never be healed. Remember the newest turn per session instead.
268
+ */
269
+ const liveTurns = new Map();
270
+ const turnOf = (sessionId, event) => (Number.isSafeInteger(event?.turn) && event.turn > 0 ? event.turn : liveTurns.get(sessionId));
271
+
272
+ ctx?.on?.('session/event', (session, event) => {
273
+ const data = event?.data ?? {};
274
+ const sessionId = session?.id;
275
+ if (Number.isSafeInteger(data.turn) && data.turn > 0) liveTurns.set(sessionId, data.turn);
276
+ if (event?.type === 'tool/call' && data.callId && (data.name === 'ask_user_question' || data.name === 'exit_plan_mode')) {
277
+ pendingFor(sessionId).add(data.callId);
278
+ const interaction = reducer.question({ sessionId, callId: data.callId, intent: data.name === 'exit_plan_mode' ? { kind: 'plan-review' } : undefined, title: interactionBody(data.name, data.arguments), turn: turnOf(sessionId, data) });
279
+ safely(() => dispatch(interaction));
280
+ return;
281
+ }
282
+ if (event?.type === 'tool/result') {
283
+ const result = data.message?.content?.find?.((block) => block?.type === 'tool-result');
284
+ const callId = result?.toolCallId;
285
+ if (!callId) return; // Unlinked records cannot be guessed closed by an uncorrelated result.
286
+ removePending(sessionId, callId);
287
+ const outcome = result?.isError || data.outcome === 'abort' ? 'abort' : 'settled';
288
+ const existing = reducer.questionResult({ sessionId, callId, outcome });
289
+ if (existing) safely(() => dispatch(existing));
290
+ return;
291
+ }
292
+ safely(async () => {
293
+ // Work resumed: whatever turn end is still pending for this session was not the end of the task.
294
+ if (event?.type === 'turn/start' || event?.type === 'tool/call') cancelCompletion(sessionId);
295
+ if (event?.type === 'approval/asked') await dispatch(reducer.approvalAsked({ ...data, turn: turnOf(sessionId, data) }, sessionId));
296
+ else if (event?.type === 'approval/decided') await dispatch(reducer.approvalDecided(data.id, data.outcome));
297
+ else if (event?.type === 'turn/end') {
298
+ const error = pendingErrors.get(`${sessionId}:${data.turn}`);
299
+ pendingErrors.delete(`${sessionId}:${data.turn}`);
300
+ // A turn just ended, so nothing can still be waiting on this session: a record left open is a
301
+ // leftover whose decision event was never observed, and one leftover used to shadow every
302
+ // later toast. Persist the expiry before the completion notification.
303
+ for (const stale of reducer.expireOpenForSession(sessionId)) await dispatch(stale);
304
+ deferCompletion(sessionId, { sessionId, turn: data.turn, reason: data.reason, body: error?.message || String(error || ''), origin: originOf(session) });
305
+ }
306
+ });
307
+ });
308
+ // A reopened session replays its history, and this plugin used to rebuild still-open interactions
309
+ // from that snapshot to keep the sidebar badge honest. There is no badge and no history any more:
310
+ // the past is not news, so a rebuild would only re-announce an approval the user can already see in
311
+ // the DSH UI, and it would do it on every session open.
312
+ ctx?.on?.('approval/request', (request, next) => { try { /* live reason is non-authoritative */ } catch { diagnostics.eventErrors += 1; } return next(); });
313
+ // A goal loop keeps starting rounds after each turn ends, so a completion is not news until the goal
314
+ // itself is done. `goal` is omitted from the payload exactly when there is no goal for the session.
315
+ ctx?.on?.('goal/activation-changed', (payload) => safely(async () => {
316
+ const sessionId = sessionIdOf(payload?.sessionId) ?? payload?.sessionId;
317
+ if (typeof sessionId !== 'string' || sessionId === '') return;
318
+ if (payload?.goal) {
319
+ engagedGoals.add(sessionId);
320
+ // A goal engaging after a turn ended holds that announcement: the loop is still working, so the
321
+ // pending payload waits for the goal to finish instead of firing on the grace timer.
322
+ const entry = deferredCompletions.get(sessionId);
323
+ if (entry?.timer) { clearTimeout(entry.timer); entry.timer = null; }
324
+ return;
325
+ }
326
+ engagedGoals.delete(sessionId);
327
+ await flushCompletion(sessionId);
328
+ }));
329
+ ctx?.on?.('user-questions/request', (request, next) => {
330
+ let record; let signal; let opening = Promise.resolve(); let settlement;
331
+ try {
332
+ signal = request?.signal;
333
+ const sessionId = sessionIdOf(request.agent);
334
+ const questions = Array.isArray(request.questions) ? request.questions.filter((item) => item && typeof item === 'object') : [];
335
+ const wantsPlan = questions.some((item) => item.intent?.kind === 'plan-review');
336
+ const title = questions.map((item) => String(item.question || item.header || '')).filter(Boolean).join(' · ');
337
+ // This record belongs to this exact waterfall invocation. No FIFO or later
338
+ // tool/result is allowed to guess its authoritative call identity.
339
+ record = reducer.question({ sessionId, intent: wantsPlan ? { kind: 'plan-review' } : undefined, title, turn: liveTurns.get(sessionId) });
340
+ opening = Promise.resolve(dispatch(record)).catch(() => { diagnostics.eventErrors += 1; });
341
+ } catch { diagnostics.eventErrors += 1; }
342
+ const settle = (outcome) => {
343
+ if (settlement) return settlement;
344
+ const closed = record && reducer.settleQuestionKey(record.mergeKey, outcome);
345
+ settlement = opening.then(() => closed ? dispatch(closed) : undefined).catch(() => { diagnostics.eventErrors += 1; });
346
+ return settlement;
347
+ };
348
+ const abort = () => { void settle('abort'); };
349
+ signal?.addEventListener?.('abort', abort, { once: true });
350
+ if (signal?.aborted) abort();
351
+ let delegated;
352
+ try { delegated = next(); } catch (error) { delegated = Promise.reject(error); }
353
+ return Promise.resolve(delegated).then(
354
+ // The host awaits this waterfall, so the bookkeeping is bounded: the answer is returned to the
355
+ // official flow even if our own write is stuck.
356
+ async (answer) => { await bounded(() => settle(signal?.aborted ? 'abort' : 'settled'), 10_000); return answer; },
357
+ async (error) => { await bounded(() => settle(signal?.aborted || error?.code === 'ASK_ABORTED' ? 'abort' : 'error'), 10_000); throw error; },
358
+ ).finally(() => signal?.removeEventListener?.('abort', abort));
359
+ });
360
+ ctx?.on?.('agent/error', ({ agent, turn, error }) => { pendingErrors.set(`${sessionIdOf(agent)}:${turn}`, error); });
361
+ // v1 user preference: subagent completion is intentionally silent. Keep the
362
+ // historical kind schema for stored legacy records, but do not create records
363
+ // or dispatch A/B/C/D for new subagent/end events.
364
+ // Subtask/background completions are the biggest noise source (one record per subagent run and
365
+ // per background job, often titled with the raw command). They are opt-in via `subtaskNotify`.
366
+ const subtasksWanted = () => ({ ...settings, ...preferences.get() }).subtaskNotify === true;
367
+ /**
368
+ * Which session a workflow run belongs to.
369
+ *
370
+ * `workflow/end` cannot say. The engine emits it from its own unscoped context and the payload is
371
+ * `{id, meta}` only, so a 工作流结束 card shipped with no session at all and could never jump anywhere —
372
+ * the one kind that was not clickable. The session is in the log instead: `dsh-tool-workflow` appends
373
+ * `tool-workflow/run-start {runId, name}` to the parent Session before the run begins, and every append
374
+ * reaches `session/event`. So the owner is learned from the log and remembered for the `workflow/end`
375
+ * that follows. The entry is dropped when it is consumed, and the map is capped so a run that never
376
+ * ends cannot grow it forever; nothing depends on which of the two events lands first.
377
+ */
378
+ const workflowOwners = new Map();
379
+ const WORKFLOW_OWNER_LIMIT = 50;
380
+ ctx?.on?.('session/event', (session, event) => {
381
+ const sessionId = session?.id; const runId = event?.data?.runId;
382
+ if (event?.type !== 'tool-workflow/run-start' || typeof sessionId !== 'string' || typeof runId !== 'string') return;
383
+ workflowOwners.delete(runId);
384
+ workflowOwners.set(runId, sessionId);
385
+ while (workflowOwners.size > WORKFLOW_OWNER_LIMIT) workflowOwners.delete(workflowOwners.keys().next().value);
386
+ });
387
+ ctx?.on?.('workflow/end', (info, result) => {
388
+ if (!subtasksWanted()) return;
389
+ const sessionId = workflowOwners.get(info.id);
390
+ workflowOwners.delete(info.id);
391
+ safely(() => dispatch(reducer.upsert({ kind: 'workflow-end', mergeKey: `wf:${info.id}`, ...(sessionId ? { sessionId } : {}), title: info.meta?.name || '工作流结束', body: result.error || result.stopReason, phase: 'settled', outcome: result.stopReason })));
392
+ });
393
+ const onJobDone = (snapshot, owner) => {
394
+ if (!subtasksWanted()) return;
395
+ safely(() => dispatch(reducer.upsert({ kind: 'job-end', mergeKey: `job:${snapshot?.id}`, sessionId: snapshot?.ownerSession ?? sessionIdOf(owner), ...jobNotification(snapshot ?? {}), phase: 'settled', outcome: snapshot?.status })));
396
+ };
397
+ /**
398
+ * The job registry is a process-wide service, and this plugin is not the composition that provides
399
+ * it. Registering through `contextService` alone failed silently for a long time — the listener was
400
+ * simply never called, so "notify me when a background job finishes" did nothing — while the web
401
+ * mount right below has always worked because it declares `ctx.inject([...])` and lets Cordis hand
402
+ * it the service. So: inject first (the same seam as webServer/connection), keep the reflective read
403
+ * as the fallback for plain test doubles, and report which one took.
404
+ */
405
+ let jobListenerAttached = false;
406
+ const attachJobs = (registry) => {
407
+ if (jobListenerAttached || typeof registry?.onJobDone !== 'function') return false;
408
+ jobListenerAttached = true;
409
+ registry.onJobDone(onJobDone);
410
+ diagnostics.services.jobs = 'injected';
411
+ return true;
412
+ };
413
+ if (typeof ctx?.inject === 'function') { try { ctx.inject(['jobs'], (jobCtx) => { attachJobs(jobCtx?.jobs); }); } catch { /* no registry in this composition */ } }
414
+ if (!jobListenerAttached) {
415
+ const reflected = contextService(ctx, 'jobs');
416
+ if (attachJobs(reflected)) diagnostics.services.jobs = 'reflected';
417
+ }
418
+ if (!jobListenerAttached) diagnostics.services.jobs = 'unavailable';
419
+
420
+ let guiAvailable = false;
421
+ const mountWeb = (lifecycleCtx, webServer, connection) => {
422
+ guiAvailable = true;
423
+ registerSensitive(lifecycleCtx, webServer, connection, '/pull', 'GET', async (req, res) => {
424
+ const url = new URL(req.url, 'http://dsh.invalid');
425
+ const raw = url.searchParams.get('since');
426
+ const since = raw === null ? 0 : Number(raw);
427
+ sendJson(res, 200, buffer.pull({ since }));
428
+ });
429
+ registerSensitive(lifecycleCtx, webServer, connection, '/config', ['GET', 'POST'], async (req, res) => {
430
+ if (req.method === 'GET') { sendJson(res, 200, { ...settings, storage: preferences.status }); return; }
431
+ const { value } = await readJson(req);
432
+ if (schemaStatus(value, SETTING_KEYS) !== 200
433
+ || ('sound' in value && typeof value.sound === 'string' && value.sound.length > 96)) { sendJson(res, 400, { error: 'invalid config' }); return; }
434
+ Object.assign(settings, value);
435
+ preferences.set(pickSettings(value));
436
+ sendJson(res, 200, { ...settings, storage: preferences.status });
437
+ });
438
+ registerSensitive(lifecycleCtx, webServer, connection, '/sounds', ['GET', 'POST'], async (req, res) => {
439
+ if (req.method === 'GET') { sendJson(res, 200, { builtins: BUILTIN_SOUNDS, custom: await sounds.list(), maxBytes: SOUND_BYTES }); return; }
440
+ const name = String(req.headers?.['x-sound-name'] ?? '');
441
+ if (!enforceLimit(req, res, limitSession, 'sounds-upload', 6)) return;
442
+ let bytes;
443
+ try { bytes = await readBody(req, SOUND_BYTES); } catch (error) { sendJson(res, error?.status ?? 400, { error: error?.status === 413 ? 'sound too large' : 'invalid upload' }); return; }
444
+ const stored = await sounds.put(name, bytes);
445
+ if (!stored.ok) { sendJson(res, stored.reason === 'too-large' ? 413 : stored.reason === 'persistence-disabled' ? 503 : 400, { error: stored.reason }); return; }
446
+ sendJson(res, 200, { ok: true, ...stored });
447
+ });
448
+ registerSensitive(lifecycleCtx, webServer, connection, '/sounds/delete', 'POST', async (req, res) => {
449
+ const { value, size } = await readJson(req, 1024);
450
+ const code = validateRequest({ rejection: undefined, originOK: true, bodyBytes: size, fields: value, allowed: ['confirm', 'name'] });
451
+ if (code !== 200 || value.confirm !== true || typeof value.name !== 'string') { sendJson(res, 400, { error: 'invalid delete request' }); return; }
452
+ if (!enforceLimit(req, res, limitSession, 'sounds-delete', 6)) return;
453
+ sendJson(res, 200, { ok: await sounds.remove(value.name) });
454
+ });
455
+ // Serving a sound stays an EXACT route (the project invariant: raw routes are exact objects, so
456
+ // no path parsing can be tricked) with the name carried as a validated query parameter.
457
+ registerSensitive(lifecycleCtx, webServer, connection, '/sound', 'GET', async (req, res) => {
458
+ const name = new URL(String(req.url ?? ''), 'http://localhost').searchParams.get('name') ?? '';
459
+ const sound = await sounds.read(name);
460
+ if (!sound) { res.statusCode = 404; res.end(); return; }
461
+ res.statusCode = 200;
462
+ res.setHeader('content-type', sound.type);
463
+ res.setHeader('cache-control', 'no-store');
464
+ res.end(sound.bytes);
465
+ });
466
+ registerSensitive(lifecycleCtx, webServer, connection, '/health', 'GET', async (_req, res) => sendJson(res, 200, { storage: preferences.status, buffered: buffer.size, guiAvailable, diagnostics }));
467
+ return () => { guiAvailable = false; };
468
+ };
469
+ if (typeof ctx?.inject === 'function') {
470
+ ctx.inject(['webServer', 'connection'], (lifecycleCtx) => mountWeb(lifecycleCtx, Reflect.get(lifecycleCtx, 'webServer'), Reflect.get(lifecycleCtx, 'connection')));
471
+ } else {
472
+ const webServer = contextService(ctx, 'webServer');
473
+ const connection = contextService(ctx, 'connection');
474
+ if (webServer?.register && connection?.requestRejection) mountWeb(ctx, webServer, connection);
475
+ }
476
+ // Cordis plugins may resolve asynchronously, but an async effect must resolve
477
+ // to a disposer (or null), never an arbitrary runtime object. Keep the
478
+ // diagnostics surface on the callable disposer for controlled tests/tools.
479
+ const dispose = () => {};
480
+ return Object.assign(dispose, { buffer, preferences, reducer, diagnostics, guiAvailable, reason: guiAvailable ? undefined : 'authenticated web routes unavailable' });
481
+ }