@xi4z/dsh-utils-notify 0.0.0-stage → 0.7.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/lib/index.d.ts +290 -0
- package/lib/index.js +915 -0
- package/lib/index.js.map +1 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +51 -3
- package/src/index.ts +1126 -0
- package/README.md +0 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,915 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `dsh-utils` notify component: push a message through a Gotify gateway when a
|
|
3
|
+
* session finishes a turn, or when the agent is blocked on an approval or a
|
|
4
|
+
* question.
|
|
5
|
+
*
|
|
6
|
+
* The gateway is addressed by URL, so the component works from any machine that
|
|
7
|
+
* can reach it over the internet: one device token, one app token, no local
|
|
8
|
+
* NapCat/OneBot service required. Every message carries the sending device's
|
|
9
|
+
* name so multiple machines sharing one gateway stay distinguishable.
|
|
10
|
+
*
|
|
11
|
+
* Wiring (all read from the session log, never from a waterfall the root
|
|
12
|
+
* context cannot receive):
|
|
13
|
+
*
|
|
14
|
+
* session/event -> accumulate the finished turn's reason + final assistant text
|
|
15
|
+
* agent/status -> the idle edge is the moment the whole task is done
|
|
16
|
+
* tool/call -> ask_user_question / exit_plan_mode is the "parked waiting
|
|
17
|
+
* for a human" signal, debounced; tool/result cancels it
|
|
18
|
+
* approval/asked -> the agent is blocked on a yes/no decision, debounced;
|
|
19
|
+
* approval/decided (auto-decided) cancels it
|
|
20
|
+
*
|
|
21
|
+
* Delivery is plain `fetch` to `POST {gotifyUrl}/message`; no WebSocket, no
|
|
22
|
+
* heartbeat, no extra dependency. The legacy OneBot path is kept for
|
|
23
|
+
* compatibility but Gotify is the default outlet.
|
|
24
|
+
*
|
|
25
|
+
* The bundle mounts this component under the entry id `dsh-notify`
|
|
26
|
+
* (`dsh-utils/notify`); that entry id is also its settings namespace, so the
|
|
27
|
+
* browser half renders a live configuration page for it. Every Config field is
|
|
28
|
+
* volatile: the component re-reads the values on each event, so a save in the
|
|
29
|
+
* settings page takes effect without a restart.
|
|
30
|
+
*
|
|
31
|
+
* Ported from `@local/dsh-plugin-qq-notify` 0.2.0 — same message
|
|
32
|
+
* templates, same environment overrides (`DSH_QQ_NOTIFY_*`), same delivery
|
|
33
|
+
* semantics — with the settings schema, live config reads, and the
|
|
34
|
+
* `dsh-utils` bundle wiring added.
|
|
35
|
+
*
|
|
36
|
+
* @module dsh-utils/notify
|
|
37
|
+
*/
|
|
38
|
+
import { appendFileSync } from 'node:fs';
|
|
39
|
+
import { hostname } from 'node:os';
|
|
40
|
+
import z from '@deepseek-ai/schemastery';
|
|
41
|
+
export const name = 'dsh-notify';
|
|
42
|
+
export const inject = ['agents'];
|
|
43
|
+
/** Turn-end reasons a deployment may subscribe to. */
|
|
44
|
+
export const NOTIFY_REASONS = ['completed', 'error', 'aborted', 'blocked'];
|
|
45
|
+
/** Defaults applied when a Config field or an environment override is absent. */
|
|
46
|
+
const DEFAULTS = {
|
|
47
|
+
enabled: true,
|
|
48
|
+
/** 'gotify' = 统一网关(每个系列一把 token,公网可达);'onebot' = 历史直连,保留兼容。 */
|
|
49
|
+
transport: 'gotify',
|
|
50
|
+
endpoint: 'http://127.0.0.1:3000',
|
|
51
|
+
token: '',
|
|
52
|
+
targetType: 'private',
|
|
53
|
+
targetId: '',
|
|
54
|
+
/** transport=gotify 时使用;targets 非空时作为默认目标的兜底。 */
|
|
55
|
+
gotifyUrl: '',
|
|
56
|
+
gotifyToken: '',
|
|
57
|
+
gotifyPriority: 3,
|
|
58
|
+
/** 追加到每个 Gotify 请求上的头(反代 Basic Auth、自定义路由等)。 */
|
|
59
|
+
gotifyHeaders: {},
|
|
60
|
+
/** 多目标:每个目标是一把独立的网关凭据/系列;devices 非空时只有命中的设备才投递。 */
|
|
61
|
+
targets: [],
|
|
62
|
+
/** 设备标识:默认取主机名;deviceLabel 是给人看的名字(默认同 deviceName)。 */
|
|
63
|
+
deviceName: '',
|
|
64
|
+
deviceLabel: '',
|
|
65
|
+
/** 是否把设备名加到 Gotify 标题前缀(正文本就能带 {device})。 */
|
|
66
|
+
deviceInTitle: false,
|
|
67
|
+
notifyOnReasons: ['completed', 'error', 'aborted'],
|
|
68
|
+
notifyOnApproval: true,
|
|
69
|
+
notifyOnQuestion: true,
|
|
70
|
+
/** 提问/审批先等这么久;期间若拿到结果(人已在 UI 回答/策略已自动裁决)就取消推送。 */
|
|
71
|
+
questionDelayMs: 2500,
|
|
72
|
+
approvalDelayMs: 3000,
|
|
73
|
+
includeSubagents: false,
|
|
74
|
+
summaryChars: 120,
|
|
75
|
+
timeoutMs: 8000,
|
|
76
|
+
/** 默认只记日志不发消息:确认配置无误后再关。 */
|
|
77
|
+
dryRun: true,
|
|
78
|
+
traceFile: '',
|
|
79
|
+
/** Mustache-lite message templates; empty means the built-in default. */
|
|
80
|
+
template: '',
|
|
81
|
+
approvalTemplate: '',
|
|
82
|
+
questionTemplate: '',
|
|
83
|
+
};
|
|
84
|
+
/** Environment overrides, so a deployment can inject secrets without editing the patch. */
|
|
85
|
+
const ENV = {
|
|
86
|
+
endpoint: 'DSH_QQ_NOTIFY_URL',
|
|
87
|
+
token: 'DSH_QQ_NOTIFY_TOKEN',
|
|
88
|
+
targetType: 'DSH_QQ_NOTIFY_TARGET_TYPE',
|
|
89
|
+
targetId: 'DSH_QQ_NOTIFY_TARGET_ID',
|
|
90
|
+
gotifyUrl: 'DSH_QQ_NOTIFY_GOTIFY_URL',
|
|
91
|
+
gotifyToken: 'DSH_QQ_NOTIFY_GOTIFY_TOKEN',
|
|
92
|
+
deviceName: 'DSH_QQ_NOTIFY_DEVICE',
|
|
93
|
+
deviceLabel: 'DSH_QQ_NOTIFY_DEVICE_LABEL',
|
|
94
|
+
targets: 'DSH_QQ_NOTIFY_TARGETS',
|
|
95
|
+
gotifyHeaders: 'DSH_QQ_NOTIFY_GOTIFY_HEADERS',
|
|
96
|
+
};
|
|
97
|
+
/** Values that must be parsed as JSON when they come from the environment. */
|
|
98
|
+
const ENV_JSON = new Set(['targets', 'gotifyHeaders']);
|
|
99
|
+
/**
|
|
100
|
+
* Settings-page schema. Every key is volatile: the Loader hands `apply` live
|
|
101
|
+
* references and the component re-reads them on use, so the configuration page
|
|
102
|
+
* writes take effect immediately.
|
|
103
|
+
*/
|
|
104
|
+
export const Config = z.object({
|
|
105
|
+
enabled: z.boolean().default(DEFAULTS.enabled).description('Master switch for this device.').volatile(),
|
|
106
|
+
transport: z.union(['gotify', 'onebot']).default(DEFAULTS.transport).description('Delivery outlet; onebot is legacy.').volatile(),
|
|
107
|
+
endpoint: z.string().default(DEFAULTS.endpoint).description('Legacy OneBot HTTP endpoint.').volatile(),
|
|
108
|
+
token: z.string().default(DEFAULTS.token).description('Legacy OneBot access token.').volatile(),
|
|
109
|
+
targetType: z.union(['private', 'group']).default(DEFAULTS.targetType).description('Legacy OneBot recipient kind.').volatile(),
|
|
110
|
+
targetId: z.string().default(DEFAULTS.targetId).description('Legacy OneBot recipient id.').volatile(),
|
|
111
|
+
gotifyUrl: z.string().default(DEFAULTS.gotifyUrl).description('Gotify gateway base URL.').volatile(),
|
|
112
|
+
gotifyToken: z.string().default(DEFAULTS.gotifyToken).description('Gotify application token; supports ${ENV} references.').volatile(),
|
|
113
|
+
gotifyPriority: z.natural().default(DEFAULTS.gotifyPriority).description('Default message priority.').volatile(),
|
|
114
|
+
gotifyHeaders: z.any().default({}).description('Extra request headers for the gateway.').volatile(),
|
|
115
|
+
targets: z.any().default([]).description('Multiple gateway targets; supports ${ENV} in url/token and urlEnv/tokenEnv.').volatile(),
|
|
116
|
+
deviceName: z.string().default(DEFAULTS.deviceName).description('Device identity; empty = hostname.').volatile(),
|
|
117
|
+
deviceLabel: z.string().default(DEFAULTS.deviceLabel).description('Human-readable device name for {device}.').volatile(),
|
|
118
|
+
deviceInTitle: z.boolean().default(DEFAULTS.deviceInTitle).description('Prefix the Gotify title with the device label.').volatile(),
|
|
119
|
+
notifyOnReasons: z.array(z.union(NOTIFY_REASONS)).default([...DEFAULTS.notifyOnReasons]).description('Turn-end reasons that notify.').volatile(),
|
|
120
|
+
notifyOnApproval: z.boolean().default(DEFAULTS.notifyOnApproval).description('Notify when an approval decision is pending.').volatile(),
|
|
121
|
+
notifyOnQuestion: z.boolean().default(DEFAULTS.notifyOnQuestion).description('Notify when a question is waiting for you.').volatile(),
|
|
122
|
+
questionDelayMs: z.natural().default(DEFAULTS.questionDelayMs).description('Question debounce; an answer inside it suppresses the push.').volatile(),
|
|
123
|
+
approvalDelayMs: z.natural().default(DEFAULTS.approvalDelayMs).description('Approval debounce; an automatic decision inside it suppresses the push.').volatile(),
|
|
124
|
+
includeSubagents: z.boolean().default(DEFAULTS.includeSubagents).description('Also notify sessions that are not roots.').volatile(),
|
|
125
|
+
summaryChars: z.natural().default(DEFAULTS.summaryChars).description('Plain-text budget for {reply}.').volatile(),
|
|
126
|
+
timeoutMs: z.natural().min(100).default(DEFAULTS.timeoutMs).description('Single HTTP timeout; one retry follows.').volatile(),
|
|
127
|
+
dryRun: z.boolean().default(DEFAULTS.dryRun).description('Log the payload instead of sending it.').volatile(),
|
|
128
|
+
traceFile: z.string().default(DEFAULTS.traceFile).description('Optional JSONL diagnostics file.').volatile(),
|
|
129
|
+
template: z.string().default(DEFAULTS.template).description('Turn-end message template; empty = built-in default.').volatile(),
|
|
130
|
+
questionTemplate: z.string().default(DEFAULTS.questionTemplate).description('Question message template; empty = built-in default.').volatile(),
|
|
131
|
+
approvalTemplate: z.string().default(DEFAULTS.approvalTemplate).description('Approval message template; empty = built-in default.').volatile(),
|
|
132
|
+
});
|
|
133
|
+
/** Reading a Loader volatile reference, or a plain value, as one concrete value. */
|
|
134
|
+
function unwrap(value) {
|
|
135
|
+
if (value !== null && typeof value === 'object' && typeof value.get === 'function') {
|
|
136
|
+
return value.get();
|
|
137
|
+
}
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
/** A trimmed non-empty string, or the fallback. */
|
|
141
|
+
function str(value, fallback = '') {
|
|
142
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback;
|
|
143
|
+
}
|
|
144
|
+
/** A string that preserves its own whitespace (templates). */
|
|
145
|
+
function text(value, fallback = '') {
|
|
146
|
+
return typeof value === 'string' ? value : fallback;
|
|
147
|
+
}
|
|
148
|
+
/** Read one environment variable, trimmed; unset or blank yields ''. */
|
|
149
|
+
function envValue(name) {
|
|
150
|
+
const found = process.env[name];
|
|
151
|
+
return typeof found === 'string' ? found.trim() : '';
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Expand `${NAME}` and `${NAME:-fallback}` references against the process
|
|
155
|
+
* environment, so a deployment can keep gateway secrets outside the patch file.
|
|
156
|
+
* An unset or blank variable expands to the fallback (or to ''), leaving the
|
|
157
|
+
* target without a token instead of sending the literal reference.
|
|
158
|
+
*/
|
|
159
|
+
export function expandEnv(value) {
|
|
160
|
+
return String(value ?? '').replace(/\${([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?}/g, (_whole, name, fallback) => {
|
|
161
|
+
const found = envValue(name);
|
|
162
|
+
return found !== '' ? found : (fallback ?? '');
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/** A finite number at or above `minimum`, or the fallback. */
|
|
166
|
+
function num(value, fallback, minimum = 0) {
|
|
167
|
+
const parsed = Number(value);
|
|
168
|
+
return Number.isFinite(parsed) && parsed >= minimum ? parsed : fallback;
|
|
169
|
+
}
|
|
170
|
+
/** A boolean, accepting the YAML/env spellings `'true'` / `'false'`. */
|
|
171
|
+
function bool(value, fallback) {
|
|
172
|
+
if (typeof value === 'boolean')
|
|
173
|
+
return value;
|
|
174
|
+
if (value === 'true')
|
|
175
|
+
return true;
|
|
176
|
+
if (value === 'false')
|
|
177
|
+
return false;
|
|
178
|
+
return fallback;
|
|
179
|
+
}
|
|
180
|
+
/** The OS hostname, or 'unknown' when the platform refuses. */
|
|
181
|
+
function safeHostname() {
|
|
182
|
+
try {
|
|
183
|
+
return hostname() || 'unknown';
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
return 'unknown';
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Keep only string/number request headers; ignore everything else. */
|
|
190
|
+
export function normalizeHeaders(raw) {
|
|
191
|
+
const out = {};
|
|
192
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
193
|
+
return out;
|
|
194
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
195
|
+
if (typeof key !== 'string' || key.trim() === '')
|
|
196
|
+
continue;
|
|
197
|
+
if (typeof value !== 'string' && typeof value !== 'number')
|
|
198
|
+
continue;
|
|
199
|
+
out[key.trim()] = expandEnv(value);
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Normalize `targets` into a predictable list; bad entries are dropped.
|
|
205
|
+
* A target with only one of url/token is kept so delivery can warn about the
|
|
206
|
+
* exact target name instead of silently disappearing.
|
|
207
|
+
*/
|
|
208
|
+
export function normalizeTargets(raw, fallbackPriority = 3) {
|
|
209
|
+
if (!Array.isArray(raw))
|
|
210
|
+
return [];
|
|
211
|
+
const out = [];
|
|
212
|
+
for (const entry of raw) {
|
|
213
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry))
|
|
214
|
+
continue;
|
|
215
|
+
const record = entry;
|
|
216
|
+
let url = typeof record.url === 'string' ? expandEnv(record.url).trim() : '';
|
|
217
|
+
let token = typeof record.token === 'string' ? expandEnv(record.token).trim() : '';
|
|
218
|
+
// `urlEnv` / `tokenEnv` name the variable outright; they win over the
|
|
219
|
+
// literal reference form and keep per-target secrets out of the patch file.
|
|
220
|
+
if (typeof record.urlEnv === 'string' && record.urlEnv.trim() !== '')
|
|
221
|
+
url = envValue(record.urlEnv.trim());
|
|
222
|
+
if (typeof record.tokenEnv === 'string' && record.tokenEnv.trim() !== '')
|
|
223
|
+
token = envValue(record.tokenEnv.trim());
|
|
224
|
+
if (!url && !token)
|
|
225
|
+
continue;
|
|
226
|
+
out.push({
|
|
227
|
+
name: typeof record.name === 'string' && record.name.trim() !== ''
|
|
228
|
+
? record.name.trim()
|
|
229
|
+
: `target-${out.length + 1}`,
|
|
230
|
+
url,
|
|
231
|
+
token,
|
|
232
|
+
priority: Number.isFinite(record.priority) ? Number(record.priority) : fallbackPriority,
|
|
233
|
+
devices: Array.isArray(record.devices)
|
|
234
|
+
? record.devices.filter((device) => typeof device === 'string' && device.trim() !== '').map((device) => device.trim())
|
|
235
|
+
: [],
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
return out;
|
|
239
|
+
}
|
|
240
|
+
/** A target with no `devices` list applies everywhere; otherwise match name or label. */
|
|
241
|
+
export function targetMatchesDevice(target, cfg) {
|
|
242
|
+
if (!target || !Array.isArray(target.devices) || target.devices.length === 0)
|
|
243
|
+
return true;
|
|
244
|
+
return target.devices.includes(cfg.deviceName) || target.devices.includes(cfg.deviceLabel);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Resolve the live Config into one concrete option set: defaults, then the
|
|
248
|
+
* settings values, then the environment overrides (so a deployment can keep
|
|
249
|
+
* secrets out of the patch file).
|
|
250
|
+
*/
|
|
251
|
+
export function normalizeOptions(config) {
|
|
252
|
+
const value = (key) => unwrap(config?.[key]);
|
|
253
|
+
const options = {
|
|
254
|
+
enabled: bool(value('enabled'), DEFAULTS.enabled),
|
|
255
|
+
transport: value('transport') === 'onebot' ? 'onebot' : 'gotify',
|
|
256
|
+
endpoint: str(expandEnv(value('endpoint')), DEFAULTS.endpoint),
|
|
257
|
+
token: str(expandEnv(value('token')), DEFAULTS.token),
|
|
258
|
+
targetType: value('targetType') === 'group' ? 'group' : 'private',
|
|
259
|
+
targetId: str(expandEnv(value('targetId')), DEFAULTS.targetId),
|
|
260
|
+
gotifyUrl: str(expandEnv(value('gotifyUrl')), DEFAULTS.gotifyUrl),
|
|
261
|
+
gotifyToken: str(expandEnv(value('gotifyToken')), DEFAULTS.gotifyToken),
|
|
262
|
+
gotifyPriority: num(value('gotifyPriority'), DEFAULTS.gotifyPriority),
|
|
263
|
+
gotifyHeaders: normalizeHeaders(value('gotifyHeaders')),
|
|
264
|
+
targets: normalizeTargets(value('targets'), num(value('gotifyPriority'), DEFAULTS.gotifyPriority)),
|
|
265
|
+
deviceName: str(value('deviceName')),
|
|
266
|
+
deviceLabel: str(value('deviceLabel')),
|
|
267
|
+
deviceInTitle: bool(value('deviceInTitle'), DEFAULTS.deviceInTitle),
|
|
268
|
+
notifyOnReasons: reasonsOf(value('notifyOnReasons')),
|
|
269
|
+
notifyOnApproval: bool(value('notifyOnApproval'), DEFAULTS.notifyOnApproval),
|
|
270
|
+
notifyOnQuestion: bool(value('notifyOnQuestion'), DEFAULTS.notifyOnQuestion),
|
|
271
|
+
questionDelayMs: num(value('questionDelayMs'), DEFAULTS.questionDelayMs),
|
|
272
|
+
approvalDelayMs: num(value('approvalDelayMs'), DEFAULTS.approvalDelayMs),
|
|
273
|
+
includeSubagents: bool(value('includeSubagents'), DEFAULTS.includeSubagents),
|
|
274
|
+
summaryChars: num(value('summaryChars'), DEFAULTS.summaryChars, 1),
|
|
275
|
+
timeoutMs: num(value('timeoutMs'), DEFAULTS.timeoutMs, 1),
|
|
276
|
+
dryRun: bool(value('dryRun'), DEFAULTS.dryRun),
|
|
277
|
+
traceFile: str(value('traceFile'), DEFAULTS.traceFile),
|
|
278
|
+
template: text(value('template'), DEFAULTS.template),
|
|
279
|
+
questionTemplate: text(value('questionTemplate'), DEFAULTS.questionTemplate),
|
|
280
|
+
approvalTemplate: text(value('approvalTemplate'), DEFAULTS.approvalTemplate),
|
|
281
|
+
};
|
|
282
|
+
for (const [key, envKey] of Object.entries(ENV)) {
|
|
283
|
+
const raw = process.env[envKey];
|
|
284
|
+
if (typeof raw !== 'string' || raw.trim() === '')
|
|
285
|
+
continue;
|
|
286
|
+
if (ENV_JSON.has(key)) {
|
|
287
|
+
try {
|
|
288
|
+
const parsed = JSON.parse(raw);
|
|
289
|
+
if (key === 'targets')
|
|
290
|
+
options.targets = normalizeTargets(parsed, options.gotifyPriority);
|
|
291
|
+
else
|
|
292
|
+
options.gotifyHeaders = normalizeHeaders(parsed);
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
// A malformed JSON env var must not stop the component; keep the YAML value.
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
else if (key === 'targetType') {
|
|
299
|
+
options.targetType = raw.trim() === 'group' ? 'group' : 'private';
|
|
300
|
+
}
|
|
301
|
+
else if (key === 'deviceName' || key === 'deviceLabel') {
|
|
302
|
+
options[key] = raw.trim();
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
const target = key;
|
|
306
|
+
if (target === 'targets' || target === 'gotifyHeaders')
|
|
307
|
+
continue;
|
|
308
|
+
options[target] = raw.trim();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
// Device identity: an empty value falls back to the OS hostname, which is
|
|
312
|
+
// what makes notifications from several machines distinguishable.
|
|
313
|
+
options.deviceName = options.deviceName || safeHostname();
|
|
314
|
+
options.deviceLabel = options.deviceLabel || options.deviceName;
|
|
315
|
+
options.targets = options.targets.length > 0
|
|
316
|
+
? options.targets
|
|
317
|
+
: [{
|
|
318
|
+
name: 'default',
|
|
319
|
+
url: options.gotifyUrl,
|
|
320
|
+
token: options.gotifyToken,
|
|
321
|
+
priority: options.gotifyPriority,
|
|
322
|
+
devices: [],
|
|
323
|
+
}];
|
|
324
|
+
return options;
|
|
325
|
+
}
|
|
326
|
+
/** Keep only known reasons; an empty list falls back to the defaults. */
|
|
327
|
+
function reasonsOf(raw) {
|
|
328
|
+
const kept = Array.isArray(raw) ? raw.filter((reason) => NOTIFY_REASONS.includes(reason)) : [];
|
|
329
|
+
return kept.length > 0 ? kept : DEFAULTS.notifyOnReasons;
|
|
330
|
+
}
|
|
331
|
+
/** Join the text blocks of one assistant message. */
|
|
332
|
+
function textOf(content) {
|
|
333
|
+
if (!Array.isArray(content))
|
|
334
|
+
return '';
|
|
335
|
+
const parts = [];
|
|
336
|
+
for (const block of content) {
|
|
337
|
+
if (block && typeof block === 'object' && block.type === 'text') {
|
|
338
|
+
const value = block.text;
|
|
339
|
+
if (typeof value === 'string' && value.trim() !== '')
|
|
340
|
+
parts.push(value.trim());
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return parts.join('\n');
|
|
344
|
+
}
|
|
345
|
+
/** Flatten to one line and cut at `limit` characters (ellipsis included). */
|
|
346
|
+
function truncate(value, limit) {
|
|
347
|
+
const flat = String(value ?? '').replace(/\s+/g, ' ').trim();
|
|
348
|
+
return flat.length <= limit ? flat : `${flat.slice(0, Math.max(0, limit - 1))}…`;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Turn assistant Markdown into a short plain-text snippet for the gateway.
|
|
352
|
+
*
|
|
353
|
+
* Fenced code blocks are dropped entirely (they are long and unreadable once
|
|
354
|
+
* flattened); inline code keeps its text; emphasis markers, headings, list
|
|
355
|
+
* bullets, table pipes and HTML tags are removed. Single underscores are left
|
|
356
|
+
* alone so `session_id` survives. The result is then cut at `limit`, preferring
|
|
357
|
+
* a sentence boundary when one is reasonably close to the end.
|
|
358
|
+
*/
|
|
359
|
+
export function plain(text, limit = 120) {
|
|
360
|
+
let value = String(text ?? '').replace(/\r\n?/g, '\n');
|
|
361
|
+
value = value.replace(/```[\s\S]*?```/g, ' ');
|
|
362
|
+
value = value.replace(/```[\s\S]*$/g, ' ');
|
|
363
|
+
value = value.replace(/!\[[^\]]*\]\([^)]*\)/g, ' ');
|
|
364
|
+
value = value.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1');
|
|
365
|
+
value = value.replace(/^\s{0,3}#{1,6}\s+/gm, '');
|
|
366
|
+
value = value.replace(/^\s{0,3}>\s?/gm, '');
|
|
367
|
+
value = value.replace(/^\s{0,3}[-*+]\s+/gm, '');
|
|
368
|
+
value = value.replace(/^\s{0,3}\d+[.)]\s+/gm, '');
|
|
369
|
+
// Markdown table rows: drop the whole row (two or more pipes) rather than
|
|
370
|
+
// flattening cells into an unreadable "a b 1 2".
|
|
371
|
+
value = value.replace(/^[^\n]*\|[^\n]*\|[^\n]*$/gm, ' ');
|
|
372
|
+
value = value.replace(/\|/g, ' ');
|
|
373
|
+
value = value.replace(/^\s*([-*_])\1{2,}\s*$/gm, ' ');
|
|
374
|
+
value = value.replace(/`{1,3}([^`]*)`{1,3}/g, '$1');
|
|
375
|
+
value = value.replace(/(\*\*|__)(.*?)\1/g, '$2');
|
|
376
|
+
value = value.replace(/~~(.*?)~~/g, '$1');
|
|
377
|
+
value = value.replace(/(?<![\w*])\*(?=\S)([^*]*?)(?<=\S)\*(?![\w*])/g, '$1');
|
|
378
|
+
// Underscore emphasis only when it is not inside an identifier (session_id).
|
|
379
|
+
value = value.replace(/(?<![\w])_(?=\S)([^_]*?)(?<=\S)_(?![\w])/g, '$1');
|
|
380
|
+
value = value.replace(/<[^>\n]{1,80}>/g, ' ');
|
|
381
|
+
value = value.replace(/\s+/g, ' ').trim();
|
|
382
|
+
if (value.length <= limit)
|
|
383
|
+
return value;
|
|
384
|
+
const head = value.slice(0, limit);
|
|
385
|
+
const cut = Math.max(head.lastIndexOf('。'), head.lastIndexOf('!'), head.lastIndexOf('?'), head.lastIndexOf('.'), head.lastIndexOf('!'), head.lastIndexOf('?'));
|
|
386
|
+
const kept = cut >= Math.floor(limit * 0.6) ? head.slice(0, cut + 1) : head.slice(0, Math.max(0, limit - 1));
|
|
387
|
+
return `${kept.trimEnd()}…`;
|
|
388
|
+
}
|
|
389
|
+
/** Chinese labels for the four turn-end reasons. */
|
|
390
|
+
const REASON_LABEL = {
|
|
391
|
+
completed: '完成',
|
|
392
|
+
error: '出错',
|
|
393
|
+
aborted: '被中止',
|
|
394
|
+
blocked: '被阻塞',
|
|
395
|
+
};
|
|
396
|
+
/** The model-facing tool whose call means the task is parked waiting for a human. */
|
|
397
|
+
const ASK_USER_TOOL = 'ask_user_question';
|
|
398
|
+
/** Plan-mode exit also raises a review question through the unlogged channel. */
|
|
399
|
+
const EXIT_PLAN_TOOL = 'exit_plan_mode';
|
|
400
|
+
/** Parse `ask_user_question` tool arguments defensively (older logs, odd providers). */
|
|
401
|
+
export function parseQuestions(raw) {
|
|
402
|
+
let parsed;
|
|
403
|
+
try {
|
|
404
|
+
parsed = JSON.parse(String(raw ?? ''));
|
|
405
|
+
}
|
|
406
|
+
catch {
|
|
407
|
+
return [];
|
|
408
|
+
}
|
|
409
|
+
const list = parsed?.questions;
|
|
410
|
+
if (!Array.isArray(list))
|
|
411
|
+
return [];
|
|
412
|
+
const out = [];
|
|
413
|
+
for (const entry of list) {
|
|
414
|
+
if (!entry || typeof entry !== 'object')
|
|
415
|
+
continue;
|
|
416
|
+
const record = entry;
|
|
417
|
+
if (typeof record.question !== 'string')
|
|
418
|
+
continue;
|
|
419
|
+
out.push({
|
|
420
|
+
question: record.question,
|
|
421
|
+
...(typeof record.detail === 'string' ? { detail: record.detail } : {}),
|
|
422
|
+
...(typeof record.header === 'string' ? { header: record.header } : {}),
|
|
423
|
+
options: Array.isArray(record.options)
|
|
424
|
+
? record.options
|
|
425
|
+
.filter((option) => !!option && typeof option === 'object' && typeof option.label === 'string')
|
|
426
|
+
.map((option) => option.label)
|
|
427
|
+
: [],
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
return out;
|
|
431
|
+
}
|
|
432
|
+
/** Parse `exit_plan_mode` tool arguments into the reviewed plan text. */
|
|
433
|
+
export function parsePlan(raw) {
|
|
434
|
+
try {
|
|
435
|
+
const parsed = JSON.parse(String(raw ?? ''));
|
|
436
|
+
const plan = parsed?.plan;
|
|
437
|
+
return typeof plan === 'string' ? plan : undefined;
|
|
438
|
+
}
|
|
439
|
+
catch {
|
|
440
|
+
return undefined;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
/** Placeholder syntax: `{name}`. Unknown placeholders are left untouched. */
|
|
444
|
+
const PLACEHOLDER = /\{([a-zA-Z][a-zA-Z0-9_]*)\}/g;
|
|
445
|
+
/**
|
|
446
|
+
* Fill a template. A line containing only a label whose value is empty
|
|
447
|
+
* (`目录: ` / `回复: `) is dropped, so one template serves every outcome.
|
|
448
|
+
*/
|
|
449
|
+
export function fill(template, values) {
|
|
450
|
+
return String(template)
|
|
451
|
+
.replace(PLACEHOLDER, (whole, key) => (Object.hasOwn(values, key) ? String(values[key] ?? '') : whole))
|
|
452
|
+
.split('\n')
|
|
453
|
+
.map((line) => line.replace(/[ \t]+$/, ''))
|
|
454
|
+
.filter((line) => !/^[^::]*[::]$/.test(line))
|
|
455
|
+
.join('\n')
|
|
456
|
+
.trim();
|
|
457
|
+
}
|
|
458
|
+
/** Local date/time placeholders. */
|
|
459
|
+
function stamp() {
|
|
460
|
+
const now = new Date();
|
|
461
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
462
|
+
return {
|
|
463
|
+
date: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`,
|
|
464
|
+
time: `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
/** Default turn-end template. */
|
|
468
|
+
export const DEFAULT_TEMPLATE = [
|
|
469
|
+
'[DSH] 会话{status}',
|
|
470
|
+
'设备: {device}',
|
|
471
|
+
'会话: {sessionId}',
|
|
472
|
+
'目录: {cwd}',
|
|
473
|
+
'结果: {status}',
|
|
474
|
+
'错误: {error}',
|
|
475
|
+
'回复: {reply}',
|
|
476
|
+
].join('\n');
|
|
477
|
+
/** Default question template. */
|
|
478
|
+
export const DEFAULT_QUESTION_TEMPLATE = [
|
|
479
|
+
'[DSH] 需要你回答',
|
|
480
|
+
'设备: {device}',
|
|
481
|
+
'会话: {sessionId}',
|
|
482
|
+
'目录: {cwd}',
|
|
483
|
+
'问题: {question}',
|
|
484
|
+
'补充: {detail}',
|
|
485
|
+
'选项: {options}',
|
|
486
|
+
].join('\n');
|
|
487
|
+
/** Default approval template. */
|
|
488
|
+
export const DEFAULT_APPROVAL_TEMPLATE = [
|
|
489
|
+
'[DSH] 需要授权',
|
|
490
|
+
'设备: {device}',
|
|
491
|
+
'会话: {sessionId}',
|
|
492
|
+
'目录: {cwd}',
|
|
493
|
+
'操作: {tool}',
|
|
494
|
+
'原因: {reason}',
|
|
495
|
+
].join('\n');
|
|
496
|
+
/** Compact body of a turn-completion message. */
|
|
497
|
+
export function renderMessage(input) {
|
|
498
|
+
const values = {
|
|
499
|
+
sessionId: String(input.sessionId).replace(/^session-/, '').slice(0, 8),
|
|
500
|
+
cwd: input.cwd ?? '',
|
|
501
|
+
status: REASON_LABEL[input.reason ?? ''] ?? String(input.reason ?? ''),
|
|
502
|
+
kind: input.reason ?? '',
|
|
503
|
+
reply: plain(input.reply, input.summaryChars ?? 120),
|
|
504
|
+
error: plain(input.error, 120),
|
|
505
|
+
device: input.device ?? '',
|
|
506
|
+
host: input.host ?? input.device ?? '',
|
|
507
|
+
...stamp(),
|
|
508
|
+
};
|
|
509
|
+
return fill(input.template || DEFAULT_TEMPLATE, values) || `[DSH] 会话${values.status}`;
|
|
510
|
+
}
|
|
511
|
+
/** Compact body of a question-request message (the agent is blocked on you). */
|
|
512
|
+
export function renderQuestionMessage(input) {
|
|
513
|
+
const values = {
|
|
514
|
+
sessionId: String(input.sessionId).replace(/^session-/, '').slice(0, 8),
|
|
515
|
+
cwd: input.cwd ?? '',
|
|
516
|
+
question: plain(input.question, 200),
|
|
517
|
+
detail: plain(input.detail, 160),
|
|
518
|
+
options: plain(input.options, 160),
|
|
519
|
+
device: input.device ?? '',
|
|
520
|
+
host: input.host ?? input.device ?? '',
|
|
521
|
+
...stamp(),
|
|
522
|
+
};
|
|
523
|
+
return fill(input.template || DEFAULT_QUESTION_TEMPLATE, values) || '[DSH] 需要你回答';
|
|
524
|
+
}
|
|
525
|
+
/** Compact body of an approval-request message. */
|
|
526
|
+
export function renderApprovalMessage(input) {
|
|
527
|
+
const values = {
|
|
528
|
+
sessionId: String(input.sessionId).replace(/^session-/, '').slice(0, 8),
|
|
529
|
+
cwd: input.cwd ?? '',
|
|
530
|
+
tool: input.toolName ?? '',
|
|
531
|
+
reason: plain(input.reason, 200),
|
|
532
|
+
device: input.device ?? '',
|
|
533
|
+
host: input.host ?? input.device ?? '',
|
|
534
|
+
...stamp(),
|
|
535
|
+
};
|
|
536
|
+
return fill(input.template || DEFAULT_APPROVAL_TEMPLATE, values) || '[DSH] 需要授权';
|
|
537
|
+
}
|
|
538
|
+
/** Build a trace sink that appends JSONL to `file` (read live, so the setting is hot). */
|
|
539
|
+
function makeTrace(file) {
|
|
540
|
+
return (stage, data = {}) => {
|
|
541
|
+
const path = file();
|
|
542
|
+
if (!path)
|
|
543
|
+
return;
|
|
544
|
+
try {
|
|
545
|
+
appendFileSync(path, `${JSON.stringify({ t: new Date().toISOString(), stage, ...data })}\n`);
|
|
546
|
+
}
|
|
547
|
+
catch {
|
|
548
|
+
// Diagnostics must never break notification delivery.
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
/** POST one OneBot 11 action; throws on transport failure or a non-ok retcode. */
|
|
553
|
+
export async function callAction(cfg, action, body) {
|
|
554
|
+
const base = cfg.endpoint.endsWith('/') ? cfg.endpoint : `${cfg.endpoint}/`;
|
|
555
|
+
const url = new URL(action, base);
|
|
556
|
+
const headers = { 'content-type': 'application/json' };
|
|
557
|
+
if (cfg.token)
|
|
558
|
+
headers.authorization = `Bearer ${cfg.token}`;
|
|
559
|
+
const response = await fetch(url, {
|
|
560
|
+
method: 'POST',
|
|
561
|
+
headers,
|
|
562
|
+
body: JSON.stringify(body),
|
|
563
|
+
signal: AbortSignal.timeout(cfg.timeoutMs),
|
|
564
|
+
});
|
|
565
|
+
const raw = await response.text();
|
|
566
|
+
if (!response.ok)
|
|
567
|
+
throw new Error(`HTTP ${response.status}: ${truncate(raw, 200)}`);
|
|
568
|
+
let parsed;
|
|
569
|
+
try {
|
|
570
|
+
parsed = JSON.parse(raw);
|
|
571
|
+
}
|
|
572
|
+
catch {
|
|
573
|
+
return raw;
|
|
574
|
+
}
|
|
575
|
+
if (parsed && typeof parsed === 'object' && parsed.status === 'failed') {
|
|
576
|
+
const record = parsed;
|
|
577
|
+
throw new Error(`OneBot retcode ${String(record.retcode)}: ${truncate(String(record.message ?? record.wording ?? ''), 200)}`);
|
|
578
|
+
}
|
|
579
|
+
return parsed;
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* 经 Gotify 网关投递。把渲染好的正文拆成「首行作标题、其余作正文」,
|
|
583
|
+
* relay 端再拼回 `标题\n正文`,与直连模式输出一致。
|
|
584
|
+
*
|
|
585
|
+
* One message can fan out to several targets (several gateways, or several
|
|
586
|
+
* app tokens / recipients). Targets may be pinned to devices, so the same
|
|
587
|
+
* config can be shared by every machine and each one only sends to its own
|
|
588
|
+
* recipients. Failures are isolated per target.
|
|
589
|
+
*/
|
|
590
|
+
async function deliverViaGotify(ctx, cfg, payload, trace) {
|
|
591
|
+
const targets = cfg.targets.filter((target) => targetMatchesDevice(target, cfg));
|
|
592
|
+
if (targets.length === 0) {
|
|
593
|
+
ctx.logger.warn(`dsh-notify: no gotify target matches device "${cfg.deviceLabel}", skipping send`);
|
|
594
|
+
trace('deliver', { mode: 'skip', why: 'no target for device', device: cfg.deviceLabel });
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
const [title, ...rest] = String(payload).split('\n');
|
|
598
|
+
const finalTitle = cfg.deviceInTitle ? `[${cfg.deviceLabel}] ${title}` : title;
|
|
599
|
+
const message = rest.join('\n');
|
|
600
|
+
const results = await Promise.allSettled(targets.map((target) => sendGotifyTarget(ctx, cfg, target, finalTitle, message, trace)));
|
|
601
|
+
logGotifyFailures(ctx, cfg, results);
|
|
602
|
+
}
|
|
603
|
+
/** Fire one Gotify POST at one target, retrying once on transient failure. */
|
|
604
|
+
async function sendGotifyTarget(ctx, cfg, target, title, message, trace) {
|
|
605
|
+
if (cfg.dryRun) {
|
|
606
|
+
ctx.logger.info(`dsh-notify: dryRun, would POST gotify target=${target.name} url=${target.url} `
|
|
607
|
+
+ `device=${cfg.deviceLabel} ${JSON.stringify({ title, message, priority: target.priority })}`);
|
|
608
|
+
trace('deliver', { mode: 'dryRun', transport: 'gotify', target: target.name, device: cfg.deviceLabel });
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
if (!target.url || !target.token) {
|
|
612
|
+
ctx.logger.warn(`dsh-notify: target "${target.name}" is missing url or token, skipping`);
|
|
613
|
+
trace('deliver', { mode: 'skip', why: 'target config missing', target: target.name });
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
const url = `${target.url.replace(/\/+$/, '')}/message`;
|
|
617
|
+
const body = { title, message, priority: target.priority };
|
|
618
|
+
// Custom headers come first so the auth/content headers cannot be clobbered.
|
|
619
|
+
const headers = { ...cfg.gotifyHeaders, 'content-type': 'application/json', 'X-Gotify-Key': target.token };
|
|
620
|
+
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
621
|
+
try {
|
|
622
|
+
const response = await fetch(url, {
|
|
623
|
+
method: 'POST',
|
|
624
|
+
headers,
|
|
625
|
+
body: JSON.stringify(body),
|
|
626
|
+
signal: AbortSignal.timeout(cfg.timeoutMs),
|
|
627
|
+
});
|
|
628
|
+
const raw = await response.text();
|
|
629
|
+
if (!response.ok)
|
|
630
|
+
throw new Error(`HTTP ${response.status}: ${raw.slice(0, 160)}`);
|
|
631
|
+
ctx.logger.info(`dsh-notify: delivered via gotify target=${target.name} device=${cfg.deviceLabel} (${title})`);
|
|
632
|
+
trace('deliver', { mode: 'ok', transport: 'gotify', target: target.name, attempt });
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
catch (error) {
|
|
636
|
+
trace('deliver', {
|
|
637
|
+
mode: 'fail', transport: 'gotify', target: target.name, attempt, error: errorMessage(error),
|
|
638
|
+
});
|
|
639
|
+
if (attempt === 2)
|
|
640
|
+
throw error;
|
|
641
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
/** Log a per-target summary without leaking tokens. */
|
|
646
|
+
function logGotifyFailures(ctx, cfg, results) {
|
|
647
|
+
const failed = results.filter((result) => result.status === 'rejected');
|
|
648
|
+
if (failed.length === 0)
|
|
649
|
+
return;
|
|
650
|
+
const detail = failed
|
|
651
|
+
.map((result) => String(result.reason?.message ?? result.reason))
|
|
652
|
+
.join('; ');
|
|
653
|
+
ctx.logger.warn(`dsh-notify: ${failed.length}/${results.length} gotify target(s) failed on ${cfg.deviceLabel}: ${detail}`);
|
|
654
|
+
}
|
|
655
|
+
/** One delivery attempt with a single retry for transient failures. */
|
|
656
|
+
async function deliver(ctx, cfg, payload, trace) {
|
|
657
|
+
if (cfg.transport === 'gotify')
|
|
658
|
+
return deliverViaGotify(ctx, cfg, payload, trace);
|
|
659
|
+
const action = cfg.targetType === 'group' ? 'send_group_msg' : 'send_private_msg';
|
|
660
|
+
// Segment form: the text is never parsed as CQ codes, so a reply containing
|
|
661
|
+
// `[CQ:at,qq=all]` cannot inject an action into the group.
|
|
662
|
+
const message = [{ type: 'text', data: { text: payload } }];
|
|
663
|
+
const body = cfg.targetType === 'group'
|
|
664
|
+
? { group_id: cfg.targetId, message }
|
|
665
|
+
: { user_id: cfg.targetId, message };
|
|
666
|
+
if (cfg.dryRun) {
|
|
667
|
+
ctx.logger.info(`dsh-notify: dryRun, would POST ${action} ${JSON.stringify(body)}`);
|
|
668
|
+
trace('deliver', { mode: 'dryRun', action, targetId: cfg.targetId });
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
if (!cfg.targetId) {
|
|
672
|
+
ctx.logger.warn('dsh-notify: targetId is empty, skipping send');
|
|
673
|
+
trace('deliver', { mode: 'skip', why: 'targetId empty' });
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
677
|
+
try {
|
|
678
|
+
await callAction(cfg, action, body);
|
|
679
|
+
ctx.logger.info(`dsh-notify: delivered ${action} to ${cfg.targetType} ${cfg.targetId}`);
|
|
680
|
+
trace('deliver', { mode: 'ok', action, targetId: cfg.targetId, attempt });
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
catch (error) {
|
|
684
|
+
trace('deliver', { mode: 'fail', action, attempt, error: errorMessage(error) });
|
|
685
|
+
if (attempt === 2) {
|
|
686
|
+
ctx.logger.warn(`dsh-notify: delivery failed after ${attempt} attempts: ${errorMessage(error)}`);
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
/** Read `error.message` off an unknown thrown value. */
|
|
694
|
+
function errorMessage(error) {
|
|
695
|
+
return error instanceof Error ? error.message : String(error);
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Activate the component.
|
|
699
|
+
* @param ctx - host Cordis context.
|
|
700
|
+
* @param config - row config from cordis.patch.yml or the settings document;
|
|
701
|
+
* volatile fields arrive as live references.
|
|
702
|
+
*/
|
|
703
|
+
export function apply(ctx, config = {}) {
|
|
704
|
+
const read = () => normalizeOptions(config);
|
|
705
|
+
const trace = makeTrace(() => normalizeOptions(config).traceFile);
|
|
706
|
+
const logger = ctx.logger;
|
|
707
|
+
const initial = read();
|
|
708
|
+
const targetSummary = initial.targets
|
|
709
|
+
.filter((target) => targetMatchesDevice(target, initial))
|
|
710
|
+
.map((target) => target.name)
|
|
711
|
+
.join(',') || '<none>';
|
|
712
|
+
logger.info(`dsh-notify: active (device=${initial.deviceLabel}, transport=${initial.transport}, targets=${targetSummary}, `
|
|
713
|
+
+ `reasons=${initial.notifyOnReasons.join(',')}, approval=${initial.notifyOnApproval}, dryRun=${initial.dryRun})`);
|
|
714
|
+
trace('activate', {
|
|
715
|
+
deviceName: initial.deviceName,
|
|
716
|
+
deviceLabel: initial.deviceLabel,
|
|
717
|
+
transport: initial.transport,
|
|
718
|
+
targets: initial.targets.map((target) => target.name),
|
|
719
|
+
reasons: initial.notifyOnReasons,
|
|
720
|
+
notifyOnApproval: initial.notifyOnApproval,
|
|
721
|
+
dryRun: initial.dryRun,
|
|
722
|
+
});
|
|
723
|
+
/** Per-session record of the most recent finished turn. */
|
|
724
|
+
const turns = new Map();
|
|
725
|
+
/**
|
|
726
|
+
* Get (or seed) the record for one session. State must not depend on having
|
|
727
|
+
* seen `turn/start`: a component activated mid-turn never sees it.
|
|
728
|
+
*/
|
|
729
|
+
const stateOf = (id) => {
|
|
730
|
+
let current = turns.get(id);
|
|
731
|
+
if (!current) {
|
|
732
|
+
current = { turn: undefined, reason: undefined, error: undefined, reply: '', notified: false };
|
|
733
|
+
turns.set(id, current);
|
|
734
|
+
}
|
|
735
|
+
return current;
|
|
736
|
+
};
|
|
737
|
+
/** Debounce timers keyed by call/approval id; a matching result cancels them. */
|
|
738
|
+
const pending = new Map();
|
|
739
|
+
const schedule = (key, delayMs, produce) => {
|
|
740
|
+
if (pending.has(key))
|
|
741
|
+
return;
|
|
742
|
+
const timer = setTimeout(() => {
|
|
743
|
+
pending.delete(key);
|
|
744
|
+
try {
|
|
745
|
+
void deliver(ctx, read(), produce(), trace);
|
|
746
|
+
}
|
|
747
|
+
catch (error) {
|
|
748
|
+
trace('schedule-error', { key, error: errorMessage(error) });
|
|
749
|
+
}
|
|
750
|
+
}, Number(delayMs) > 0 ? Number(delayMs) : 2500);
|
|
751
|
+
pending.set(key, timer);
|
|
752
|
+
};
|
|
753
|
+
const cancel = (key) => {
|
|
754
|
+
const timer = pending.get(key);
|
|
755
|
+
if (timer !== undefined) {
|
|
756
|
+
clearTimeout(timer);
|
|
757
|
+
pending.delete(key);
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
const onSessionEvent = (session, event) => {
|
|
761
|
+
const cfg = read();
|
|
762
|
+
if (!cfg.enabled)
|
|
763
|
+
return;
|
|
764
|
+
const id = session.id;
|
|
765
|
+
// SessionEvent is an envelope: { type, seq, time, data }. Tolerate a bare
|
|
766
|
+
// payload too, so a shape change degrades instead of silently no-op'ing.
|
|
767
|
+
const data = (event.data ?? event);
|
|
768
|
+
switch (event.type) {
|
|
769
|
+
case 'turn/start':
|
|
770
|
+
turns.set(id, { turn: data.turn, reason: undefined, error: undefined, reply: '', notified: false });
|
|
771
|
+
break;
|
|
772
|
+
case 'assistant/message':
|
|
773
|
+
stateOf(id).reply = textOf(data.message?.content);
|
|
774
|
+
break;
|
|
775
|
+
case 'turn/end': {
|
|
776
|
+
const current = stateOf(id);
|
|
777
|
+
current.turn = data.turn;
|
|
778
|
+
current.reason = data.reason?.kind ?? 'unknown';
|
|
779
|
+
current.error = data.reason?.error?.message;
|
|
780
|
+
trace('turn/end', { sessionId: id, turn: data.turn, reason: data.reason?.kind });
|
|
781
|
+
break;
|
|
782
|
+
}
|
|
783
|
+
// 用户提问:会话日志里没有 user-questions 事件,工具调用本身就是"挂起等人"的信号。
|
|
784
|
+
case 'tool/call': {
|
|
785
|
+
if (!cfg.notifyOnQuestion)
|
|
786
|
+
break;
|
|
787
|
+
const callId = String(data.callId ?? '');
|
|
788
|
+
if (!callId)
|
|
789
|
+
break;
|
|
790
|
+
if (data.name === ASK_USER_TOOL) {
|
|
791
|
+
trace('wait/question', { sessionId: id, callId });
|
|
792
|
+
schedule(`q:${callId}`, cfg.questionDelayMs, () => {
|
|
793
|
+
const questions = parseQuestions(data.arguments);
|
|
794
|
+
return renderQuestionMessage({
|
|
795
|
+
sessionId: id,
|
|
796
|
+
cwd: session.header?.cwd,
|
|
797
|
+
question: questions[0]?.question,
|
|
798
|
+
detail: questions[0]?.detail,
|
|
799
|
+
options: (questions[0]?.options ?? []).join(' / '),
|
|
800
|
+
template: cfg.questionTemplate,
|
|
801
|
+
device: cfg.deviceLabel,
|
|
802
|
+
host: cfg.deviceName,
|
|
803
|
+
});
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
else if (data.name === EXIT_PLAN_TOOL) {
|
|
807
|
+
trace('wait/plan', { sessionId: id, callId });
|
|
808
|
+
schedule(`p:${callId}`, cfg.questionDelayMs, () => renderQuestionMessage({
|
|
809
|
+
sessionId: id,
|
|
810
|
+
cwd: session.header?.cwd,
|
|
811
|
+
question: '计划已提交,等待你确认',
|
|
812
|
+
detail: parsePlan(data.arguments),
|
|
813
|
+
template: cfg.questionTemplate,
|
|
814
|
+
device: cfg.deviceLabel,
|
|
815
|
+
host: cfg.deviceName,
|
|
816
|
+
}));
|
|
817
|
+
}
|
|
818
|
+
break;
|
|
819
|
+
}
|
|
820
|
+
case 'tool/result': {
|
|
821
|
+
const callId = String(data.message?.toolCallId ?? data.callId ?? '');
|
|
822
|
+
if (callId) {
|
|
823
|
+
cancel(`q:${callId}`);
|
|
824
|
+
cancel(`p:${callId}`);
|
|
825
|
+
}
|
|
826
|
+
break;
|
|
827
|
+
}
|
|
828
|
+
// 审批:日志里有 approval/asked;短时间内拿到 decided 说明是自动裁决,不必打扰。
|
|
829
|
+
case 'approval/asked': {
|
|
830
|
+
if (!cfg.notifyOnApproval)
|
|
831
|
+
break;
|
|
832
|
+
const askId = String(data.id ?? '');
|
|
833
|
+
if (!askId)
|
|
834
|
+
break;
|
|
835
|
+
trace('wait/approval', { sessionId: id, toolName: data.toolName });
|
|
836
|
+
schedule(`a:${askId}`, cfg.approvalDelayMs, () => renderApprovalMessage({
|
|
837
|
+
sessionId: id,
|
|
838
|
+
cwd: session.header?.cwd,
|
|
839
|
+
toolName: typeof data.toolName === 'string' ? data.toolName : undefined,
|
|
840
|
+
reason: typeof data.reason === 'string' ? data.reason : undefined,
|
|
841
|
+
template: cfg.approvalTemplate,
|
|
842
|
+
device: cfg.deviceLabel,
|
|
843
|
+
host: cfg.deviceName,
|
|
844
|
+
}));
|
|
845
|
+
break;
|
|
846
|
+
}
|
|
847
|
+
case 'approval/decided': {
|
|
848
|
+
cancel(`a:${String(data.id ?? '')}`);
|
|
849
|
+
break;
|
|
850
|
+
}
|
|
851
|
+
default:
|
|
852
|
+
break;
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
const onAgentStatus = (payload) => {
|
|
856
|
+
const cfg = read();
|
|
857
|
+
if (!cfg.enabled)
|
|
858
|
+
return;
|
|
859
|
+
// Only the idle edge matters. It is not paired with a `running` edge on
|
|
860
|
+
// purpose: a component activated mid-turn never saw that edge, and
|
|
861
|
+
// `turn/end` already marks exactly one notify-worthy turn.
|
|
862
|
+
if (payload.status !== 'idle')
|
|
863
|
+
return;
|
|
864
|
+
const agent = payload.agent;
|
|
865
|
+
let isRoot = true;
|
|
866
|
+
try {
|
|
867
|
+
const registry = ctx.agents;
|
|
868
|
+
const roots = registry.roots?.() ?? registry.list?.() ?? [];
|
|
869
|
+
isRoot = roots.some((root) => root.id === agent.id);
|
|
870
|
+
}
|
|
871
|
+
catch (error) {
|
|
872
|
+
trace('roots-error', { error: errorMessage(error) });
|
|
873
|
+
}
|
|
874
|
+
const state = turns.get(agent.id);
|
|
875
|
+
trace('agent/idle', {
|
|
876
|
+
sessionId: agent.id,
|
|
877
|
+
isRoot,
|
|
878
|
+
turn: state?.turn,
|
|
879
|
+
reason: state?.reason,
|
|
880
|
+
notified: state?.notified,
|
|
881
|
+
matched: state ? cfg.notifyOnReasons.includes(state.reason) : false,
|
|
882
|
+
});
|
|
883
|
+
if (!cfg.includeSubagents && !isRoot)
|
|
884
|
+
return;
|
|
885
|
+
if (!state || state.notified)
|
|
886
|
+
return;
|
|
887
|
+
if (!cfg.notifyOnReasons.includes(state.reason))
|
|
888
|
+
return;
|
|
889
|
+
state.notified = true;
|
|
890
|
+
const payloadText = renderMessage({
|
|
891
|
+
sessionId: agent.id,
|
|
892
|
+
cwd: agent.session?.header?.cwd,
|
|
893
|
+
reason: state.reason,
|
|
894
|
+
error: state.error,
|
|
895
|
+
reply: state.reply,
|
|
896
|
+
summaryChars: cfg.summaryChars,
|
|
897
|
+
template: cfg.template,
|
|
898
|
+
device: cfg.deviceLabel,
|
|
899
|
+
host: cfg.deviceName,
|
|
900
|
+
});
|
|
901
|
+
void deliver(ctx, cfg, payloadText, trace);
|
|
902
|
+
};
|
|
903
|
+
const disposeSession = ctx.on('session/event', onSessionEvent);
|
|
904
|
+
const disposeStatus = ctx.on('agent/status', onAgentStatus);
|
|
905
|
+
ctx.effect(() => () => {
|
|
906
|
+
if (typeof disposeSession === 'function')
|
|
907
|
+
disposeSession();
|
|
908
|
+
if (typeof disposeStatus === 'function')
|
|
909
|
+
disposeStatus();
|
|
910
|
+
for (const timer of pending.values())
|
|
911
|
+
clearTimeout(timer);
|
|
912
|
+
pending.clear();
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
//# sourceMappingURL=index.js.map
|