@kir_sleeping/dsh-relay 0.3.0 → 0.4.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/docs/demo.html ADDED
@@ -0,0 +1,874 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Relay 接入示例 · 收件箱小报</title>
7
+ <!--
8
+ ============================================================================
9
+ Relay 接入示例(单文件,无构建、无后端)
10
+ ============================================================================
11
+
12
+ 这个页面自己没有 AI。所有智能来自本机 Relay 插件暴露的 HTTP 接口(三处都用到它):
13
+ · 起草回复 —— 用户主动请求,流式
14
+ · 每日小报 —— 应用后台请求,结构化输出 + 校验重试
15
+ · 随手问 —— 最小形态的流式聊天
16
+
17
+ http://127.0.0.1:3080/x/relay
18
+
19
+ ── 它演示两件事 ───────────────────────────────────────────────────────────
20
+
21
+ 1) 用户主动请求:用户点「起草回复」,页面把邮件数据交出去,结果流式写回来。
22
+ trigger = "user"
23
+
24
+ 2) 应用后台请求:页面自己发起的批量任务(真实产品里由定时器触发),
25
+ 要求 agent 输出**可解析的 JSON**,解析失败自动重试一次。
26
+ trigger = "app"
27
+
28
+ 这两种的差别不在"谁更礼貌",而在协议字段:
29
+ - trigger 表示谁发起的。缺省 "app"(更保守)。
30
+ - approved 由 Relay 填,表示这次调用有没有被允许发生。
31
+
32
+ ★ 关键不变式:trigger="app" 的消息永远不会被标成"用户说的话",
33
+ 哪怕用户在确认框里点了「允许」。放行 ≠ 署名。
34
+
35
+ ── 后端契约(只列本页用到的) ──────────────────────────────────────────────
36
+
37
+ POST /enroll {source} → 返回 token
38
+ 首次接入。会在主机上弹出系统确认框,用户点「允许」才返回凭证。
39
+ 阻塞最长 60 秒,所以这个请求的 fetch 不能设置太短的超时。
40
+
41
+ POST /submit {content, source, session, trigger, wait, timeout}
42
+ 头:Authorization: Bearer <token>
43
+ wait=true → 200 {type:"final", content} | 202 {id,status:"pending"} | 410
44
+ stream=true → text/event-stream,事件见下面 streamAsk()
45
+ 失败 → 4xx/5xx + {code, message}
46
+
47
+ GET /result/{id} 202 未完成 | 200 已完成 | 404 不存在 | 410 作废
48
+ GET /sources 登记列表(无凭证),用来读自己的级别
49
+
50
+ ── 错误码怎么处理(注释在这里,页面不展示) ───────────────────────────────
51
+
52
+ 400 ERR_TRIGGER / ERR_CONTENT ... 请求写错了,改代码,不要重试
53
+ 401 ERR_INPUT_FINGERPRINT 凭证缺失或失效 → 清本地凭证 → 重新申请 → 重试一次
54
+ 403 ERR_ACCESS_DENIED 来源在禁止名单 → 不重试,提示去设置里解除
55
+ 403 ERR_AUTH_DENIED 用户当场拒绝 → 不重试,尊重拒绝
56
+ 409 ERR_SESSION_OUTSIDE_WORKSPACE 会话不在 Relay 工作区 → 用 default session "main"
57
+ 410 ERR_QUEUE_EXPIRED 排队超时作废 → 可以重试一次(这是"迟到了",不是"错了")
58
+ 503 ERR_AUTH_UNAVAILABLE 主机没有可用桌面 → 不重试,人去主机操作
59
+ 504 ERR_AUTH_TIMEOUT 确认超时 → 可以重试
60
+ 200 + type:"error" 任务执行失败 → 读 code/message,通常重试无用
61
+ 网络错误 服务没开 → 提示,不重试
62
+
63
+ 原则:**主动请求的错误要让人看见并能重试;后台请求的错误要安静,但代码里留痕。**
64
+
65
+ ── 怎么跑 ────────────────────────────────────────────────────────────────
66
+
67
+ 直接双击打开,或 python3 -m http.server 8000 后访问。
68
+ 从 file:// 打开时 Origin 是 null,Relay 允许。
69
+
70
+ 演示前建议:先点一次任意按钮完成授权,再去「设置 → 应用权限」把
71
+ inbox-demo 的级别从 1 调到 3。否则每条消息都会弹一次系统确认框——
72
+ 包括后台请求,因为它是 trigger="app",协议上就不该被当成用户的话。
73
+ -->
74
+ <style>
75
+ :root {
76
+ color-scheme: light dark;
77
+ --bg: #ffffff;
78
+ --fg: #1a1a1a;
79
+ --muted: #6b7280;
80
+ --line: #e5e7eb;
81
+ --card: #f9fafb;
82
+ --accent: #2563eb;
83
+ --warn: #b45309;
84
+ }
85
+ @media (prefers-color-scheme: dark) {
86
+ :root {
87
+ --bg: #0f1115;
88
+ --fg: #e5e7eb;
89
+ --muted: #9ca3af;
90
+ --line: #262b35;
91
+ --card: #171a21;
92
+ --accent: #60a5fa;
93
+ --warn: #fbbf24;
94
+ }
95
+ }
96
+ * { box-sizing: border-box; }
97
+ body {
98
+ margin: 0; padding: 24px;
99
+ font: 14px/1.6 -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
100
+ background: var(--bg); color: var(--fg);
101
+ }
102
+ .wrap { max-width: 1040px; margin: 0 auto; }
103
+ header { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
104
+ h1 { font-size: 17px; margin: 0; font-weight: 600; }
105
+ .status { color: var(--muted); font-size: 12px; }
106
+ .status b { color: var(--fg); font-weight: 600; }
107
+ .spacer { flex: 1; }
108
+ button {
109
+ font: inherit; font-size: 13px; padding: 6px 14px; cursor: pointer;
110
+ color: var(--fg); background: var(--card);
111
+ border: 1px solid var(--line); border-radius: 8px;
112
+ }
113
+ button:hover:not(:disabled) { border-color: var(--accent); }
114
+ button:disabled { opacity: .5; cursor: default; }
115
+ button.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
116
+ .grid { display: grid; grid-template-columns: 260px 1fr; gap: 16px; }
117
+ @media (max-width: 760px) { .grid { grid-template-columns: 1fr; } }
118
+ .list { border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
119
+ .item {
120
+ padding: 10px 12px; border-bottom: 1px solid var(--line); cursor: pointer;
121
+ display: flex; gap: 8px; align-items: flex-start;
122
+ }
123
+ .item:last-child { border-bottom: 0; }
124
+ .item:hover { background: var(--card); }
125
+ .item.active { background: var(--card); border-left: 3px solid var(--accent); padding-left: 9px; }
126
+ .item-main { min-width: 0; flex: 1; }
127
+ .item-from { font-size: 12px; color: var(--muted); }
128
+ .item-subject { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
129
+ .chip {
130
+ font-size: 11px; padding: 1px 7px; border-radius: 999px;
131
+ border: 1px solid var(--line); color: var(--muted); white-space: nowrap;
132
+ }
133
+ .chip.hot { color: var(--warn); border-color: var(--warn); }
134
+ .reader { border: 1px solid var(--line); border-radius: 10px; padding: 16px; min-height: 320px; }
135
+ .reader h2 { font-size: 15px; margin: 0 0 4px; }
136
+ .reader .meta { font-size: 12px; color: var(--muted); margin-bottom: 12px; }
137
+ .reader .body { white-space: pre-wrap; margin-bottom: 16px; }
138
+ textarea {
139
+ width: 100%; min-height: 130px; padding: 10px 12px; resize: vertical;
140
+ font: inherit; color: var(--fg); background: var(--bg);
141
+ border: 1px solid var(--line); border-radius: 8px;
142
+ }
143
+ .row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
144
+ .hint { font-size: 12px; color: var(--muted); margin-top: 8px; }
145
+ .digest { margin-top: 20px; border: 1px solid var(--line); border-radius: 10px; padding: 16px; }
146
+ .digest h2 { font-size: 15px; margin: 0 0 4px; }
147
+ .digest ol { margin: 12px 0 0; padding-left: 22px; }
148
+ .digest li { margin-bottom: 8px; }
149
+ .digest a { color: var(--accent); text-decoration: none; margin-left: 8px; font-size: 12px; }
150
+ .digest a:hover { text-decoration: underline; }
151
+ .dim { color: var(--muted); font-size: 12px; }
152
+ .error { color: var(--warn); font-size: 12px; margin-top: 8px; }
153
+ .chat { margin-top: 20px; border: 1px solid var(--line); border-radius: 10px; padding: 16px; }
154
+ .chat h2 { font-size: 15px; margin: 0 0 4px; }
155
+ .chat input {
156
+ flex: 1; min-width: 200px; padding: 8px 12px; font: inherit; color: var(--fg);
157
+ background: var(--bg); border: 1px solid var(--line); border-radius: 8px;
158
+ }
159
+ .chat .body { white-space: pre-wrap; min-height: 22px; }
160
+ .chat .preview { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-top: 10px; }
161
+ .chat .thumb { position: relative; }
162
+ .chat .thumb img { width: 64px; height: 64px; object-fit: cover; border-radius: 8px; border: 1px solid var(--line); display: block; }
163
+ .chat .thumb button {
164
+ position: absolute; top: -6px; right: -6px; width: 20px; height: 20px; padding: 0;
165
+ font-size: 11px; line-height: 18px; border-radius: 999px; cursor: pointer;
166
+ background: var(--bg); color: var(--fg); border: 1px solid var(--line);
167
+ }
168
+ pre.raw {
169
+ display: none; margin-top: 12px; padding: 10px; overflow: auto; max-height: 220px;
170
+ font-size: 12px; background: var(--card); border: 1px solid var(--line); border-radius: 8px;
171
+ }
172
+ </style>
173
+ </head>
174
+ <body>
175
+ <div class="wrap">
176
+ <header>
177
+ <h1>收件箱</h1>
178
+ <span class="status" id="status">未授权 · 会话 <b>main</b></span>
179
+ <span class="spacer"></span>
180
+ <button id="digestBtn">生成每日小报</button>
181
+ </header>
182
+
183
+ <div class="grid">
184
+ <div class="list" id="list"></div>
185
+ <div class="reader">
186
+ <h2 id="subject">—</h2>
187
+ <div class="meta" id="meta"></div>
188
+ <div class="body" id="body"></div>
189
+ <textarea id="draft" placeholder="回复草稿会出现在这里"></textarea>
190
+ <div class="row">
191
+ <button class="primary" id="draftBtn">起草回复</button>
192
+ <button id="refineBtn" disabled>再正式一点</button>
193
+ </div>
194
+ <div class="hint" id="draftHint"></div>
195
+ <div class="error" id="draftError"></div>
196
+ </div>
197
+ </div>
198
+
199
+ <div class="digest">
200
+ <h2>今日小报</h2>
201
+ <div class="dim" id="digestStatus">尚未生成。真实产品里这一步由每天的定时任务触发,这里用按钮模拟。</div>
202
+ <ol id="digestList"></ol>
203
+ <pre class="raw" id="digestRaw"></pre>
204
+ </div>
205
+
206
+ <div class="chat">
207
+ <h2>随手问</h2>
208
+ <div class="dim">这条走流式:回答边生成边显示,不用轮询。</div>
209
+ <div class="row">
210
+ <input id="chatInput" placeholder="问点什么…回车或点发送">
211
+ <button id="chatPick">图片</button>
212
+ <input id="chatFile" type="file" accept="image/png,image/jpeg,image/webp,image/gif" multiple hidden>
213
+ <button class="primary" id="chatBtn">发送</button>
214
+ </div>
215
+ <div class="preview" id="chatPreview"></div>
216
+ <div class="body" id="chatOut"></div>
217
+ <div class="error" id="chatError"></div>
218
+ </div>
219
+ </div>
220
+
221
+ <script type="module">
222
+ // ============================================================================
223
+ // 1. 配置
224
+ // ============================================================================
225
+ const CONFIG = {
226
+ base: 'http://127.0.0.1:3080/x/relay',
227
+ source: 'inbox-demo',
228
+ session: 'main',
229
+ storageKey: 'relay.fingerprint.inbox-demo',
230
+ pollMs: 1500,
231
+ pollDeadlineMs: 120000,
232
+ };
233
+
234
+ // ============================================================================
235
+ // 2. 传输层
236
+ // ----------------------------------------------------------------------------
237
+ // 统一出口。把"HTTP 状态码 + body"翻译成一个带 kind 的错误,上层按 kind 决定
238
+ // 是重试、提示、还是静默。不要把状态码判断散落到各处。
239
+ // ============================================================================
240
+ class RelayError extends Error {
241
+ constructor(kind, status, body) {
242
+ super(`[${kind}] ${body?.code ?? status}: ${body?.message ?? ''}`);
243
+ this.kind = kind;
244
+ this.status = status;
245
+ this.body = body;
246
+ }
247
+ }
248
+
249
+ function classify(status, body) {
250
+ if (status === 401) return 'credential';
251
+ if (status === 403) return body?.code === 'ERR_ACCESS_DENIED' ? 'denied' : 'rejected';
252
+ if (status === 404) return 'missing';
253
+ if (status === 409) return 'conflict';
254
+ if (status === 410) return 'expired';
255
+ if (status === 503) return 'unavailable';
256
+ if (status === 504) return 'auth-timeout';
257
+ if (status >= 500) return 'server';
258
+ return 'request';
259
+ }
260
+
261
+ async function call(path, payload, token) {
262
+ // 凭证走 Authorization 头,source 留在 body —— 前者是密钥,后者是给人看的标签。
263
+ const headers = {};
264
+ if (payload !== undefined) headers['Content-Type'] = 'application/json';
265
+ if (typeof token === 'string' && token !== '') headers.Authorization = `Bearer ${token}`;
266
+
267
+ let response;
268
+ try {
269
+ response = await fetch(CONFIG.base + path, {
270
+ method: payload === undefined ? 'GET' : 'POST',
271
+ headers: Object.keys(headers).length > 0 ? headers : undefined,
272
+ body: payload === undefined ? undefined : JSON.stringify(payload),
273
+ });
274
+ } catch {
275
+ // 连不上:服务没开、端口不对、被防火墙拦。重试没有意义,直接告诉用户。
276
+ throw new RelayError('network', 0, { code: 'ERR_NETWORK', message: '连不上 Relay 服务' });
277
+ }
278
+ const text = await response.text();
279
+ let body = {};
280
+ try {
281
+ body = text ? JSON.parse(text) : {};
282
+ } catch {
283
+ body = { code: 'ERR_BAD_JSON', message: text.slice(0, 200) };
284
+ }
285
+ return { status: response.status, body };
286
+ }
287
+
288
+ // ============================================================================
289
+ // 3. 授权
290
+ // ----------------------------------------------------------------------------
291
+ // 凭证存在 localStorage:丢了就会重新申请,而重新申请会再弹一次系统确认框。
292
+ // 注意:申请接口会阻塞到用户点完(最长 60 秒),所以这里不能套用短超时。
293
+ // ============================================================================
294
+ async function enroll() {
295
+ const { status, body } = await call('/enroll', { source: CONFIG.source });
296
+ if (status !== 200) {
297
+ // ERR_SOURCE_EXISTS 说明这个来源接过入了但本地凭证丢了:只能让用户去
298
+ // 「设置 → 应用权限」重置凭证,页面无法自救。
299
+ throw new RelayError(classify(status, body), status, body);
300
+ }
301
+ localStorage.setItem(CONFIG.storageKey, body.token);
302
+ await refreshStatus();
303
+ return body.token;
304
+ }
305
+
306
+ async function getToken() {
307
+ const cached = localStorage.getItem(CONFIG.storageKey);
308
+ return cached || await enroll();
309
+ }
310
+
311
+ async function refreshStatus() {
312
+ const el = document.getElementById('status');
313
+ try {
314
+ const { body } = await call('/sources');
315
+ const mine = (body.sources ?? []).find((row) => row.source === CONFIG.source);
316
+ if (!mine) {
317
+ el.innerHTML = `未授权 · 会话 <b>${CONFIG.session}</b>`;
318
+ return;
319
+ }
320
+ const advice = mine.level < 3
321
+ ? ' · 级别 &lt;3:每次调用都会弹确认框,后台请求也不例外'
322
+ : '';
323
+ el.innerHTML = `已授权 · 级别 <b>${mine.level}</b> · 会话 <b>${CONFIG.session}</b>${advice}`;
324
+ } catch {
325
+ el.innerHTML = `连不上 Relay 服务 · 会话 <b>${CONFIG.session}</b>`;
326
+ }
327
+ }
328
+
329
+ // 凭证失效(401)时清掉本地值,下一次调用会自动重新申请。
330
+ function dropCredential() {
331
+ localStorage.removeItem(CONFIG.storageKey);
332
+ }
333
+
334
+ // ============================================================================
335
+ // 4. 两种请求
336
+ // ----------------------------------------------------------------------------
337
+ // ask() 走"提交 + 轮询",适合后台请求:不打扰,拿完整结果。
338
+ // streamAsk() 走 SSE,适合用户主动请求:边生成边显示,用户在看。
339
+ // ============================================================================
340
+ async function submit({ content, trigger, wait, stream, timeoutSec }) {
341
+ const token = await getToken();
342
+ const payload = {
343
+ content,
344
+ source: CONFIG.source,
345
+ session: CONFIG.session,
346
+ trigger, // "user" | "app"
347
+ timeout: timeoutSec,
348
+ ...(stream ? { stream: true } : { wait: true }),
349
+ };
350
+ return call('/submit', payload, token);
351
+ }
352
+
353
+ async function pollResult(id) {
354
+ const deadline = Date.now() + CONFIG.pollDeadlineMs;
355
+ while (Date.now() < deadline) {
356
+ const { status, body } = await call(`/result/${encodeURIComponent(id)}`);
357
+ if (status === 200) {
358
+ if (body.type === 'final') return body.content;
359
+ throw new RelayError('task', 200, body);
360
+ }
361
+ if (status === 410) throw new RelayError('expired', 410, body);
362
+ if (status !== 202) throw new RelayError(classify(status, body), status, body);
363
+ await new Promise((resolve) => setTimeout(resolve, CONFIG.pollMs));
364
+ }
365
+ throw new RelayError('timeout', 0, { code: 'ERR_POLL_TIMEOUT', message: '轮询超时' });
366
+ }
367
+
368
+ async function ask({ content, trigger, timeoutSec = 120, retryCredential = true }) {
369
+ let result;
370
+ try {
371
+ result = await submit({ content, trigger, wait: true, timeoutSec });
372
+ } catch (error) {
373
+ if (error.kind === 'credential' && retryCredential) {
374
+ // 凭证失效:清掉、重新申请(会弹一次确认框)、再试一次。只重试一次。
375
+ dropCredential();
376
+ return ask({ content, trigger, timeoutSec, retryCredential: false });
377
+ }
378
+ throw error;
379
+ }
380
+
381
+ const { status, body } = result;
382
+ if (status === 200) {
383
+ if (body.type === 'final') return body.content;
384
+ throw new RelayError('task', 200, body);
385
+ }
386
+ if (status === 202) return pollResult(body.id);
387
+ if (status === 410) throw new RelayError('expired', 410, body);
388
+
389
+ if (status === 401 && retryCredential) {
390
+ dropCredential();
391
+ return ask({ content, trigger, timeoutSec, retryCredential: false });
392
+ }
393
+ throw new RelayError(classify(status, body), status, body);
394
+ }
395
+
396
+ async function streamAsk({ content, trigger, timeoutSec = 120, onDelta, images, retryCredential = true }) {
397
+ const token = await getToken();
398
+ let response;
399
+ try {
400
+ response = await fetch(CONFIG.base + '/submit', {
401
+ method: 'POST',
402
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
403
+ body: JSON.stringify({
404
+ content, source: CONFIG.source,
405
+ session: CONFIG.session, trigger, stream: true, timeout: timeoutSec,
406
+ ...(images && images.length > 0 ? { images } : {}),
407
+ }),
408
+ });
409
+ } catch {
410
+ throw new RelayError('network', 0, { code: 'ERR_NETWORK', message: '连不上 Relay 服务' });
411
+ }
412
+
413
+ // 准入失败时不会开流,仍然是普通 JSON —— 靠 Content-Type 区分。
414
+ const type = response.headers.get('content-type') ?? '';
415
+ if (!type.includes('text/event-stream')) {
416
+ const text = await response.text();
417
+ let body = {};
418
+ try { body = text ? JSON.parse(text) : {}; } catch { body = {}; }
419
+ if (response.status === 401) {
420
+ // 凭证失效:清掉、重新申请、整条请求重来一次。只重试一次。
421
+ dropCredential();
422
+ if (retryCredential) {
423
+ return streamAsk({ content, trigger, timeoutSec, onDelta, images, retryCredential: false });
424
+ }
425
+ throw new RelayError('credential', 401, body);
426
+ }
427
+ throw new RelayError(classify(response.status, body), response.status, body);
428
+ }
429
+
430
+ const reader = response.body.getReader();
431
+ const decoder = new TextDecoder();
432
+ let buffer = '';
433
+ let answer = '';
434
+ let event = null;
435
+
436
+ while (true) {
437
+ const { done, value } = await reader.read();
438
+ if (done) break;
439
+ buffer += decoder.decode(value, { stream: true });
440
+
441
+ let cut;
442
+ while ((cut = buffer.indexOf('\n\n')) !== -1) {
443
+ const block = buffer.slice(0, cut);
444
+ buffer = buffer.slice(cut + 2);
445
+ for (const line of block.split('\n')) {
446
+ if (line.startsWith('event: ')) {
447
+ event = line.slice(7).trim();
448
+ } else if (line.startsWith('data: ') && event) {
449
+ const data = JSON.parse(line.slice(6));
450
+ if (event === 'content') {
451
+ answer += data.text ?? '';
452
+ onDelta?.(data.text ?? '', answer);
453
+ } else if (event === 'error') {
454
+ throw new RelayError('task', 200, data);
455
+ } else if (event === 'end') {
456
+ if (data.status === 'completed') return data.content ?? answer;
457
+ throw new RelayError(data.status === 'timeout' ? 'timeout' : 'task', 200, {
458
+ code: `ERR_STREAM_${String(data.status).toUpperCase()}`,
459
+ message: `流式结束:${data.status}`,
460
+ });
461
+ }
462
+ event = null;
463
+ }
464
+ }
465
+ }
466
+ }
467
+ return answer;
468
+ }
469
+
470
+ // ============================================================================
471
+ // 5. 每日小报:让 agent 输出可解析的结构
472
+ // ----------------------------------------------------------------------------
473
+ // 这是本例的重点:agent 的输出是自由文本,不是 API。必须在提示词里写死形状,
474
+ // 回来之后严格校验,校验不过就带着原因重发一次。
475
+ // ============================================================================
476
+ const DIGEST_PROMPT_HEAD = `你是邮件助手。下面是过去一天收到的邮件,每封有 id、发件人、主题、时间、链接、正文。
477
+
478
+ 请生成一份小报:按重要性从高到低排序,每封给一句话总结(不超过 30 字)。
479
+
480
+ 只输出 JSON,不要任何解释,不要 Markdown 代码块。格式:
481
+ {"digest":[{"id":"邮件id","importance":3,"summary":"一句话","url":"邮件的链接"}]}
482
+
483
+ importance 是整数,越大越重要,条目必须按 importance 从大到小排列。
484
+ id 和 url 必须原样取自输入,不要改写,不要新增。
485
+
486
+ 邮件数据:`;
487
+
488
+ function repairPrompt(reason) {
489
+ return `上一次输出无法解析,原因:${reason}。
490
+ 只输出 JSON,不要解释,不要代码块。格式必须是:
491
+ {"digest":[{"id":"…","importance":3,"summary":"…","url":"…"}]}`;
492
+ }
493
+
494
+ function extractJson(text) {
495
+ const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
496
+ const candidate = fenced ? fenced[1] : text;
497
+ const start = candidate.indexOf('{');
498
+ const end = candidate.lastIndexOf('}');
499
+ if (start < 0 || end <= start) return null;
500
+ try {
501
+ return JSON.parse(candidate.slice(start, end + 1));
502
+ } catch {
503
+ return null;
504
+ }
505
+ }
506
+
507
+ function validateDigest(parsed, emails) {
508
+ if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.digest)) {
509
+ return { ok: false, reason: '顶层不是 {digest: [...]}' };
510
+ }
511
+ if (parsed.digest.length === 0) return { ok: false, reason: 'digest 是空数组' };
512
+
513
+ const byId = new Map(emails.map((mail) => [mail.id, mail]));
514
+ const seen = new Set();
515
+ let previous = Infinity;
516
+
517
+ for (const [index, item] of parsed.digest.entries()) {
518
+ const at = `第 ${index + 1} 条`;
519
+ if (!item || typeof item !== 'object') return { ok: false, reason: `${at}不是对象` };
520
+ if (typeof item.id !== 'string' || !byId.has(item.id)) return { ok: false, reason: `${at}的 id 不在输入里` };
521
+ if (seen.has(item.id)) return { ok: false, reason: `${at}的 id 重复` };
522
+ seen.add(item.id);
523
+ if (!Number.isInteger(item.importance)) return { ok: false, reason: `${at}的 importance 不是整数` };
524
+ if (typeof item.summary !== 'string' || item.summary.trim() === '') return { ok: false, reason: `${at}的 summary 为空` };
525
+ if (item.summary.length > 60) return { ok: false, reason: `${at}的 summary 超过 60 字` };
526
+ if (item.url !== byId.get(item.id).url) return { ok: false, reason: `${at}的 url 与输入不一致` };
527
+ if (item.importance > previous) return { ok: false, reason: `${at}没有按重要性从高到低排列` };
528
+ previous = item.importance;
529
+ }
530
+ return { ok: true, items: parsed.digest };
531
+ }
532
+
533
+ async function requestDigest(emails) {
534
+ const payload = emails.map(({ id, from, subject, receivedAt, url, body }) =>
535
+ ({ id, from, subject, receivedAt, url, body }));
536
+ const prompt = `${DIGEST_PROMPT_HEAD}\n${JSON.stringify(payload, null, 2)}`;
537
+
538
+ // trigger="app":这是应用自己在后台发起的,不是用户说的话。
539
+ // 级别 1/2 下它照样会弹确认框——这正说明"能不能在后台悄悄用 AI"
540
+ // 由用户给的信任级别决定,不由应用自己说了算。
541
+ const first = await ask({ content: prompt, trigger: 'app', timeoutSec: 90 });
542
+ let check = validateDigest(extractJson(first), emails);
543
+ if (check.ok) return check.items;
544
+
545
+ // 只重试一次:带上第一条失败原因。真实产品这里该有退避和降级,示例不铺开。
546
+ const second = await ask({ content: repairPrompt(check.reason), trigger: 'app', timeoutSec: 90 });
547
+ check = validateDigest(extractJson(second), emails);
548
+ if (check.ok) return check.items;
549
+
550
+ const error = new Error(`格式两次都不对:${check.reason}`);
551
+ error.raw = first;
552
+ throw error;
553
+ }
554
+
555
+ // ============================================================================
556
+ // 6. 模拟邮件
557
+ // ============================================================================
558
+ const EMAILS = [
559
+ {
560
+ id: 'm1', from: '张伟', subject: '周三评审会材料',
561
+ receivedAt: '2026-11-14T10:24:00+08:00', url: 'https://mail.example.com/m1',
562
+ body: `评审会改到周三下午两点,材料请在今天下班前发我。\n\n重点两页:本季度指标完成情况、下季度资源申请。`,
563
+ },
564
+ {
565
+ id: 'm2', from: '李娜', subject: '合同附件请确认',
566
+ receivedAt: '2026-11-14T09:05:00+08:00', url: 'https://mail.example.com/m2',
567
+ body: `附件是最终版合同,法务已经过了一遍。\n\n今天下午 18:00 前要回复确认,否则对方要顺延到下个工作日。`,
568
+ },
569
+ {
570
+ id: 'm3', from: '系统通知', subject: '本月账单已生成',
571
+ receivedAt: '2026-11-14T08:00:00+08:00', url: 'https://mail.example.com/m3',
572
+ body: `您 11 月的账单已生成,金额 1,284.00 元,可在控制台查看明细。`,
573
+ },
574
+ {
575
+ id: 'm4', from: '王强', subject: '周末团建报名',
576
+ receivedAt: '2026-11-13T19:40:00+08:00', url: 'https://mail.example.com/m4',
577
+ body: `这周六团建,地点在城西,报名表在群里,周三前填一下就行。`,
578
+ },
579
+ ];
580
+
581
+ // ============================================================================
582
+ // 7. 界面
583
+ // ============================================================================
584
+ let selectedId = EMAILS[0].id;
585
+ let digestByMail = new Map();
586
+
587
+ function renderList() {
588
+ const list = document.getElementById('list');
589
+ list.innerHTML = '';
590
+ for (const mail of EMAILS) {
591
+ const item = document.createElement('div');
592
+ item.className = 'item' + (mail.id === selectedId ? ' active' : '');
593
+ item.onclick = () => { selectedId = mail.id; renderList(); renderReader(); };
594
+
595
+ const main = document.createElement('div');
596
+ main.className = 'item-main';
597
+ main.innerHTML = `<div class="item-from">${mail.from}</div><div class="item-subject">${mail.subject}</div>`;
598
+ item.appendChild(main);
599
+
600
+ const digest = digestByMail.get(mail.id);
601
+ if (digest) {
602
+ const chip = document.createElement('span');
603
+ chip.className = 'chip' + (digest.importance >= 3 ? ' hot' : '');
604
+ chip.textContent = digest.importance >= 3 ? '急' : '可延后';
605
+ chip.title = digest.summary;
606
+ item.appendChild(chip);
607
+ }
608
+ list.appendChild(item);
609
+ }
610
+ }
611
+
612
+ function renderReader() {
613
+ const mail = EMAILS.find((row) => row.id === selectedId);
614
+ document.getElementById('subject').textContent = mail.subject;
615
+ document.getElementById('meta').textContent = `${mail.from} · ${new Date(mail.receivedAt).toLocaleString('zh-CN')}`;
616
+ document.getElementById('body').textContent = mail.body;
617
+ document.getElementById('draft').value = '';
618
+ document.getElementById('draftError').textContent = '';
619
+ document.getElementById('draftHint').textContent = '';
620
+ document.getElementById('refineBtn').disabled = true;
621
+ }
622
+
623
+ // 把内部错误翻成一句人话。页面只显示这一句,详细原因留给开发者看控制台。
624
+ function describeError(error) {
625
+ const detail = error.body?.message ?? '';
626
+ const map = {
627
+ credential: '凭证失效,再点一次会重新申请(会弹一次确认框)。',
628
+ denied: '这个应用被禁用了。请到「设置 → 应用权限」里解除。',
629
+ rejected: '你在确认框里拒绝了这次请求。',
630
+ conflict: '会话不在 Relay 工作区里,请使用 main。',
631
+ expired: '排队太久被作废了,可以再点一次。',
632
+ unavailable: '主机上没有可用的确认窗口,需要人到主机上操作。',
633
+ 'auth-timeout': '确认超时了,再点一次会重新弹框。',
634
+ network: '连不上 Relay 服务。确认插件已启用,且地址是 127.0.0.1:3080。',
635
+ request: `请求被拒绝:${detail}(这是调用方的问题,改代码,不要重试)`,
636
+ server: 'Relay 内部出错,稍后再试。',
637
+ missing: '找不到这次任务,可能已被清理。',
638
+ timeout: '等待超时,可以再点一次。',
639
+ task: `任务执行失败:${error.body?.code ?? ''} ${detail}`.trim(),
640
+ };
641
+ return map[error.kind] ?? `未知错误:${error.message ?? error}`;
642
+ }
643
+
644
+ function showDraftError(error) {
645
+ document.getElementById('draftError').textContent = describeError(error);
646
+ console.error('[relay]', error);
647
+ }
648
+
649
+ // 主动请求:用户点了按钮,所以 trigger="user"。
650
+ document.getElementById('draftBtn').onclick = async () => {
651
+ const mail = EMAILS.find((row) => row.id === selectedId);
652
+ const button = document.getElementById('draftBtn');
653
+ const draft = document.getElementById('draft');
654
+ button.disabled = true;
655
+ draft.value = '';
656
+ document.getElementById('draftError').textContent = '';
657
+ document.getElementById('draftHint').textContent = '正在生成…';
658
+
659
+ try {
660
+ const content = `请帮我回复这封邮件。
661
+
662
+ 发件人:${mail.from}
663
+ 主题:${mail.subject}
664
+ 正文:${mail.body}
665
+
666
+ 要求:中文,简洁,明确下一步,不要寒暄。`;
667
+ const answer = await streamAsk({
668
+ content, trigger: 'user',
669
+ onDelta: (text, sofar) => { draft.value = sofar; },
670
+ });
671
+ draft.value = answer;
672
+ document.getElementById('draftHint').textContent = '已生成。可以改,或点「再正式一点」。';
673
+ document.getElementById('refineBtn').disabled = false;
674
+ } catch (error) {
675
+ showDraftError(error);
676
+ document.getElementById('draftHint').textContent = '';
677
+ } finally {
678
+ button.disabled = false;
679
+ }
680
+ };
681
+
682
+ document.getElementById('refineBtn').onclick = async () => {
683
+ const button = document.getElementById('refineBtn');
684
+ const draft = document.getElementById('draft');
685
+ const previous = draft.value.trim();
686
+ if (!previous) return;
687
+ button.disabled = true;
688
+ document.getElementById('draftHint').textContent = '改写中…';
689
+
690
+ try {
691
+ // 只发一句话 + 上一稿:靠同一会话的上下文完成改写。
692
+ const answer = await streamAsk({
693
+ content: `把下面这封回复改得更正式一些,意思不变。\n\n上一稿:\n${previous}`,
694
+ trigger: 'user',
695
+ onDelta: (text, sofar) => { draft.value = sofar; },
696
+ });
697
+ draft.value = answer;
698
+ document.getElementById('draftHint').textContent = '已改写。';
699
+ } catch (error) {
700
+ showDraftError(error);
701
+ } finally {
702
+ button.disabled = false;
703
+ }
704
+ };
705
+
706
+ // 后台请求:由应用自己发起,trigger="app"。
707
+ // 这里的按钮只是模拟——真实产品里它由每天固定时间的定时器触发,例如:
708
+ // setInterval(runDigest, 24 * 60 * 60 * 1000)
709
+ // 或者由后端 cron / 系统计划任务发起,页面根本不需要打开。
710
+ // 失败时不打扰用户:不弹提示,只在状态行留一行字。
711
+ document.getElementById('digestBtn').onclick = async () => {
712
+ const button = document.getElementById('digestBtn');
713
+ const status = document.getElementById('digestStatus');
714
+ const raw = document.getElementById('digestRaw');
715
+ button.disabled = true;
716
+ status.textContent = '后台处理中…';
717
+ raw.style.display = 'none';
718
+
719
+ try {
720
+ const items = await requestDigest(EMAILS);
721
+ digestByMail = new Map(items.map((item) => [item.id, item]));
722
+ renderList();
723
+
724
+ const list = document.getElementById('digestList');
725
+ list.innerHTML = '';
726
+ for (const item of items) {
727
+ const mail = EMAILS.find((row) => row.id === item.id);
728
+ const li = document.createElement('li');
729
+ li.textContent = item.summary;
730
+ const link = document.createElement('a');
731
+ link.href = item.url;
732
+ link.textContent = '打开';
733
+ link.onclick = (event) => {
734
+ // 演示里链接指回本地这封信;真实产品会直接跳转到邮箱。
735
+ event.preventDefault();
736
+ selectedId = mail.id;
737
+ renderList();
738
+ renderReader();
739
+ };
740
+ li.appendChild(link);
741
+ list.appendChild(li);
742
+ }
743
+ status.textContent = `已生成 ${items.length} 条,按重要性排列。`;
744
+ } catch (error) {
745
+ // 后台失败要安静:不弹窗、不打断,只留一行状态。
746
+ status.textContent = `小报生成失败:${describeError(error)}`;
747
+ console.error('[relay]', error);
748
+ if (error.raw) {
749
+ raw.textContent = error.raw;
750
+ raw.style.display = 'block';
751
+ }
752
+ } finally {
753
+ button.disabled = false;
754
+ }
755
+ };
756
+
757
+ // 流式聊天:最小形态的 SSE 用法。同一套 streamAsk,只是把增量直接铺在页面上。
758
+ const chatInput = document.getElementById('chatInput');
759
+ const chatBtn = document.getElementById('chatBtn');
760
+ const chatOut = document.getElementById('chatOut');
761
+ const chatFile = document.getElementById('chatFile');
762
+ const chatPreview = document.getElementById('chatPreview');
763
+
764
+ // 最多 4 张,和 Host 的限制一致;本地先拦,别让用户白等一个注定失败的请求。
765
+ let chatImages = [];
766
+ const MAX_IMAGES = 4;
767
+ const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
768
+ const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'];
769
+
770
+ function renderPreviews() {
771
+ chatPreview.innerHTML = '';
772
+ chatImages.forEach((image, index) => {
773
+ const thumb = document.createElement('div');
774
+ thumb.className = 'thumb';
775
+ const img = document.createElement('img');
776
+ img.src = `data:${image.mediaType};base64,${image.data}`;
777
+ img.alt = image.name || '待发送的图片';
778
+ const remove = document.createElement('button');
779
+ remove.textContent = '✕';
780
+ remove.title = '移除这张';
781
+ remove.onclick = () => {
782
+ chatImages.splice(index, 1);
783
+ renderPreviews();
784
+ };
785
+ thumb.append(img, remove);
786
+ chatPreview.append(thumb);
787
+ });
788
+ }
789
+
790
+ function readImage(file) {
791
+ return new Promise((resolve) => {
792
+ const reader = new FileReader();
793
+ reader.onload = () => {
794
+ const result = String(reader.result);
795
+ const comma = result.indexOf(',');
796
+ resolve({
797
+ mediaType: file.type,
798
+ data: comma >= 0 ? result.slice(comma + 1) : result,
799
+ name: file.name,
800
+ });
801
+ };
802
+ reader.readAsDataURL(file);
803
+ });
804
+ }
805
+
806
+ document.getElementById('chatPick').onclick = () => chatFile.click();
807
+
808
+ chatFile.onchange = async () => {
809
+ const files = Array.from(chatFile.files || []);
810
+ chatFile.value = '';
811
+ if (files.length === 0) return;
812
+
813
+ const errorBox = document.getElementById('chatError');
814
+ errorBox.textContent = '';
815
+
816
+ for (const file of files) {
817
+ if (chatImages.length >= MAX_IMAGES) {
818
+ errorBox.textContent = `最多 ${MAX_IMAGES} 张图片`;
819
+ break;
820
+ }
821
+ if (!IMAGE_TYPES.includes(file.type)) {
822
+ errorBox.textContent = `${file.name}:不支持的格式 ${file.type || '未知'}`;
823
+ continue;
824
+ }
825
+ if (file.size > MAX_IMAGE_BYTES) {
826
+ errorBox.textContent = `${file.name}:超过 8MB`;
827
+ continue;
828
+ }
829
+ chatImages.push(await readImage(file));
830
+ renderPreviews();
831
+ }
832
+ };
833
+
834
+ async function sendChat() {
835
+ const text = chatInput.value.trim();
836
+ if (text === '' || chatBtn.disabled) return;
837
+ const images = chatImages.slice();
838
+ chatBtn.disabled = true;
839
+ chatOut.textContent = '';
840
+ document.getElementById('chatError').textContent = '';
841
+ try {
842
+ const answer = await streamAsk({
843
+ content: text,
844
+ trigger: 'user',
845
+ images,
846
+ onDelta: (_chunk, sofar) => { chatOut.textContent = sofar; },
847
+ });
848
+ if (answer) chatOut.textContent = answer;
849
+ } catch (error) {
850
+ document.getElementById('chatError').textContent = describeError(error);
851
+ console.error('[relay]', error);
852
+ } finally {
853
+ chatBtn.disabled = false;
854
+ // 图片已经随请求发出去了,不管成败都清掉,免得下一轮重复带
855
+ chatImages = [];
856
+ chatFile.value = '';
857
+ renderPreviews();
858
+ }
859
+ }
860
+
861
+ chatBtn.onclick = sendChat;
862
+ chatInput.addEventListener('keydown', (event) => {
863
+ if (event.key === 'Enter') {
864
+ event.preventDefault();
865
+ sendChat();
866
+ }
867
+ });
868
+
869
+ renderList();
870
+ renderReader();
871
+ refreshStatus();
872
+ </script>
873
+ </body>
874
+ </html>