dsh-plugin-bridge 0.2.11 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,1247 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-plugin-bridge",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let react = require("react");
8
+ let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
9
+ let react_jsx_runtime = require("react/jsx-runtime");
10
+ //#region src/client-contract.ts
11
+ /** Pure wire-to-view helpers shared by the native WebUI card and Node tests. */
12
+ const MAX_EDITED_SUMMARY_CHARS = 24e3;
13
+ const RUN_COMMAND = /\/bridge\s+([^\s]+)\s+--go(?:\s|$)/u;
14
+ const TEXT_SCHEMAS = {
15
+ zh: [
16
+ [
17
+ "goal",
18
+ "目标",
19
+ "text"
20
+ ],
21
+ [
22
+ "currentState",
23
+ "当前状态",
24
+ "text"
25
+ ],
26
+ [
27
+ "keyDecisions",
28
+ "关键决策与约定",
29
+ "list"
30
+ ],
31
+ [
32
+ "keyFiles",
33
+ "关键文件",
34
+ "list"
35
+ ],
36
+ [
37
+ "nextStep",
38
+ "下一步",
39
+ "text"
40
+ ]
41
+ ],
42
+ en: [
43
+ [
44
+ "goal",
45
+ "Goal",
46
+ "text"
47
+ ],
48
+ [
49
+ "currentState",
50
+ "Current state",
51
+ "text"
52
+ ],
53
+ [
54
+ "keyDecisions",
55
+ "Key decisions & conventions",
56
+ "list"
57
+ ],
58
+ [
59
+ "keyFiles",
60
+ "Key files",
61
+ "list"
62
+ ],
63
+ [
64
+ "nextStep",
65
+ "Next step",
66
+ "text"
67
+ ]
68
+ ]
69
+ };
70
+ const TEXT_APPENDICES = {
71
+ zh: /* @__PURE__ */ new Set(["视觉证据——原文搬运,未经二次摘要", "未解析图片"]),
72
+ en: /* @__PURE__ */ new Set(["Visual evidence — verbatim, not summarized", "Unresolved images"])
73
+ };
74
+ function sourceLines(markdown, lineEnding) {
75
+ const lines = [];
76
+ let start = 0;
77
+ while (start <= markdown.length) {
78
+ const next = markdown.indexOf(lineEnding, start);
79
+ if (next < 0) {
80
+ lines.push({
81
+ start,
82
+ contentEnd: markdown.length,
83
+ end: markdown.length,
84
+ text: markdown.slice(start)
85
+ });
86
+ break;
87
+ }
88
+ lines.push({
89
+ start,
90
+ contentEnd: next,
91
+ end: next + lineEnding.length,
92
+ text: markdown.slice(start, next)
93
+ });
94
+ start = next + lineEnding.length;
95
+ if (start === markdown.length) {
96
+ lines.push({
97
+ start,
98
+ contentEnd: start,
99
+ end: start,
100
+ text: ""
101
+ });
102
+ break;
103
+ }
104
+ }
105
+ return lines;
106
+ }
107
+ function markdownHeadings(markdown, lineEnding) {
108
+ const headings = [];
109
+ let fence;
110
+ for (const line of sourceLines(markdown, lineEnding)) {
111
+ const fenceMatch = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(line.text);
112
+ if (fence) {
113
+ if (fenceMatch && fenceMatch[1]?.[0] === fence.marker && (fenceMatch[1]?.length ?? 0) >= fence.length && (fenceMatch[2]?.trim() ?? "") === "") fence = void 0;
114
+ continue;
115
+ }
116
+ if (fenceMatch) {
117
+ const token = fenceMatch[1] ?? "";
118
+ fence = {
119
+ marker: token[0],
120
+ length: token.length
121
+ };
122
+ continue;
123
+ }
124
+ if (!line.text.startsWith("##")) continue;
125
+ const rest = line.text.slice(2);
126
+ if (rest[0] !== " " && rest[0] !== " ") continue;
127
+ let labelStart = 0;
128
+ while (labelStart < rest.length && (rest[labelStart] === " " || rest[labelStart] === " ")) labelStart += 1;
129
+ let labelEnd = rest.length;
130
+ while (labelEnd > labelStart && (rest[labelEnd - 1] === " " || rest[labelEnd - 1] === " ")) labelEnd -= 1;
131
+ if (labelEnd > labelStart) headings.push({
132
+ label: rest.slice(labelStart, labelEnd),
133
+ start: line.start,
134
+ lineEnd: line.end
135
+ });
136
+ }
137
+ return fence ? void 0 : headings;
138
+ }
139
+ function documentLineEnding(markdown) {
140
+ const endings = markdown.match(/\r\n|\n|\r/gu);
141
+ if (!endings?.length) return void 0;
142
+ const first = endings[0];
143
+ if (first !== "\n" && first !== "\r\n" || endings.some((ending) => ending !== first)) return void 0;
144
+ return first;
145
+ }
146
+ const MARKDOWN_BLOCK_START = /^([\t ]{0,3})(#{1,6}(?:[\t ]|$)|>(?:[\t ]|$)|[-+*](?:[\t ]|$)|\d+[.)](?:[\t ]|$)|`{3}|~{3})/u;
147
+ const THEMATIC_OR_SETEXT = /^ {0,3}(?:(?:\*[\t ]*){3,}|(?:-[\t ]*){3,}|(?:_[\t ]*){3,}|=+[\t ]*)$/u;
148
+ const TABLE_DELIMITER = /^ {0,3}\|?[\t ]*:?-{3,}:?[\t ]*(?:\|[\t ]*:?-{3,}:?[\t ]*)+\|?[\t ]*$/u;
149
+ const LINK_DEFINITION = /^ {0,3}\[[^\]]+\]:[\t ]*\S/u;
150
+ const HTML_BLOCK_START = /^ {0,3}<[/!?A-Za-z]/u;
151
+ function hasUnsafeBlock(line) {
152
+ return MARKDOWN_BLOCK_START.test(line) || THEMATIC_OR_SETEXT.test(line) || TABLE_DELIMITER.test(line) || LINK_DEFINITION.test(line) || /^(?: {4}|\t)/u.test(line) || line.includes("<!--") || line.includes("-->") || line.includes("--!>") || HTML_BLOCK_START.test(line);
153
+ }
154
+ function parseListItems(markdownBody, lineEnding, bodyStart, allowPlain) {
155
+ if (!markdownBody) return {
156
+ items: [],
157
+ style: "bullet",
158
+ text: ""
159
+ };
160
+ const lines = sourceLines(markdownBody, lineEnding);
161
+ if (lines.some((line) => !line.text.trim())) return void 0;
162
+ const style = /^- (.+)$/u.exec(lines[0]?.text ?? "") ? "bullet" : allowPlain ? "plain" : void 0;
163
+ if (!style) return void 0;
164
+ const items = [];
165
+ if (style === "plain") for (const line of lines) {
166
+ if (hasUnsafeBlock(line.text) || /^[\t ]*(?:[-+*]|\d+[.)])[\t ]+/u.test(line.text)) return void 0;
167
+ items.push({
168
+ text: line.text,
169
+ contentStart: bodyStart + line.start,
170
+ contentEnd: bodyStart + line.contentEnd,
171
+ itemStart: bodyStart + line.start,
172
+ itemEnd: bodyStart + line.end
173
+ });
174
+ }
175
+ else {
176
+ const starts = [];
177
+ for (const [index, line] of lines.entries()) {
178
+ if (/^- (.+)$/u.test(line.text)) {
179
+ starts.push(index);
180
+ continue;
181
+ }
182
+ if (!starts.length || hasUnsafeBlock(line.text) || /^[\t ]+(?:[-+*]|\d+[.)])[\t ]+/u.test(line.text) || /^[+*][\t ]+/u.test(line.text) || /^\d+[.)][\t ]+/u.test(line.text)) return void 0;
183
+ }
184
+ for (const [itemIndex, lineIndex] of starts.entries()) {
185
+ const first = lines[lineIndex];
186
+ const nextLineIndex = starts[itemIndex + 1] ?? lines.length;
187
+ const last = lines[nextLineIndex - 1];
188
+ const firstText = /^- (.+)$/u.exec(first.text)?.[1];
189
+ if (!firstText) return void 0;
190
+ const continuationLines = lines.slice(lineIndex + 1, nextLineIndex);
191
+ const continuationPrefixes = continuationLines.map((line) => /^[\t ]*/u.exec(line.text)?.[0] ?? "");
192
+ const continuation = continuationLines.map((line, index) => line.text.slice(continuationPrefixes[index]?.length ?? 0));
193
+ items.push({
194
+ text: [firstText, ...continuation].join(lineEnding),
195
+ contentStart: bodyStart + first.start + 2,
196
+ contentEnd: bodyStart + last.contentEnd,
197
+ itemStart: bodyStart + first.start,
198
+ itemEnd: bodyStart + (lines[nextLineIndex]?.start ?? markdownBody.length),
199
+ continuationPrefixes
200
+ });
201
+ }
202
+ }
203
+ return {
204
+ items,
205
+ style,
206
+ text: items.map((item) => item.text).join(lineEnding)
207
+ };
208
+ }
209
+ function plainBlockText(markdownBody, lineEnding) {
210
+ return markdownBody.split(lineEnding).map((line) => line.replace(/^([\t ]{0,3})\\(?=[#>*+`~_<\[|!=-])/u, "$1")).join(lineEnding);
211
+ }
212
+ function isPlainBlock(markdownBody, lineEnding) {
213
+ return sourceLines(markdownBody, lineEnding).every((line) => !hasUnsafeBlock(line.text));
214
+ }
215
+ function parseTextBlock(markdownBody, lineEnding) {
216
+ const lines = sourceLines(markdownBody, lineEnding);
217
+ if (lines.length && lines.every((line) => /^- (.+)$/u.test(line.text))) return {
218
+ style: "bullets",
219
+ text: lines.map((line) => /^- (.+)$/u.exec(line.text)?.[1] ?? "").join(lineEnding)
220
+ };
221
+ return isPlainBlock(markdownBody, lineEnding) ? {
222
+ style: "plain",
223
+ text: plainBlockText(markdownBody, lineEnding)
224
+ } : void 0;
225
+ }
226
+ function markdownSafePlainText(text, lineEnding) {
227
+ return text.split(lineEnding).map((line) => {
228
+ if (/^(?: {4}|\t)/u.test(line)) throw new Error("Plain-text lines cannot start with four spaces or a tab");
229
+ if (!hasUnsafeBlock(line)) return line;
230
+ return line.replace(/^([\t ]{0,3})(?=\S)/u, "$1\\");
231
+ }).join(lineEnding);
232
+ }
233
+ /**
234
+ * Project only Bridge's exact bilingual five-section schema into plain fields.
235
+ * Unknown structure fails closed; known visual appendices remain opaque Markdown.
236
+ */
237
+ function parseBridgeTextProjection(markdown) {
238
+ const lineEnding = documentLineEnding(markdown);
239
+ if (!lineEnding) return void 0;
240
+ const headings = markdownHeadings(markdown, lineEnding);
241
+ if (!headings?.length || headings[0]?.start !== 0) return void 0;
242
+ const lang = headings[0]?.label === TEXT_SCHEMAS.zh[0][1] ? "zh" : headings[0]?.label === TEXT_SCHEMAS.en[0][1] ? "en" : void 0;
243
+ if (!lang) return void 0;
244
+ const appendixIndex = headings.findIndex((heading) => TEXT_APPENDICES[lang].has(heading.label));
245
+ const schemaHeadings = appendixIndex < 0 ? headings : headings.slice(0, appendixIndex);
246
+ if (schemaHeadings.length !== TEXT_SCHEMAS[lang].length) return void 0;
247
+ if (schemaHeadings.some((heading, index) => heading.label !== TEXT_SCHEMAS[lang][index]?.[1])) return void 0;
248
+ const firstAppendix = appendixIndex < 0 ? void 0 : headings[appendixIndex];
249
+ const editableMarkdown = markdown.slice(0, firstAppendix?.start ?? markdown.length);
250
+ if (editableMarkdown.includes("<!--") || editableMarkdown.includes("-->") || editableMarkdown.includes("--!>")) return void 0;
251
+ const sections = [];
252
+ for (const [index, heading] of schemaHeadings.entries()) {
253
+ const [key, label, kind] = TEXT_SCHEMAS[lang][index];
254
+ const bodyStart = heading.lineEnd;
255
+ let bodyEnd = schemaHeadings[index + 1]?.start ?? firstAppendix?.start ?? markdown.length;
256
+ while (bodyEnd - lineEnding.length >= bodyStart && markdown.slice(bodyEnd - lineEnding.length, bodyEnd) === lineEnding) bodyEnd -= lineEnding.length;
257
+ const body = markdown.slice(bodyStart, bodyEnd);
258
+ const list = kind === "list" ? parseListItems(body, lineEnding, bodyStart, key === "keyFiles") : void 0;
259
+ const textBlock = kind === "text" ? parseTextBlock(body, lineEnding) : void 0;
260
+ if (kind === "list" && !list) return void 0;
261
+ if (kind === "text" && !textBlock) return void 0;
262
+ const text = list?.text ?? textBlock?.text ?? "";
263
+ sections.push({
264
+ key,
265
+ label,
266
+ kind,
267
+ text,
268
+ bodyStart,
269
+ bodyEnd,
270
+ ...list ? {
271
+ items: list.items,
272
+ listStyle: list.style
273
+ } : {},
274
+ ...textBlock ? { textStyle: textBlock.style } : {}
275
+ });
276
+ }
277
+ return {
278
+ lang,
279
+ markdown,
280
+ lineEnding,
281
+ sections,
282
+ opaqueSuffix: firstAppendix ? markdown.slice(firstAppendix.start) : ""
283
+ };
284
+ }
285
+ function normalizeLineEndings(text, lineEnding) {
286
+ return text.replace(/\r\n|\n|\r/gu, lineEnding);
287
+ }
288
+ /** Replace one editable body while preserving every byte outside that section. */
289
+ function replaceBridgeTextSection(projection, key, plainText) {
290
+ const section = projection.sections.find((candidate) => candidate.key === key);
291
+ if (!section) throw new Error(`Unknown Bridge text section: ${key}`);
292
+ if (plainText === section.text) return projection.markdown;
293
+ const normalized = normalizeLineEndings(plainText, projection.lineEnding);
294
+ let markdownBody;
295
+ if (section.kind === "list") {
296
+ const values = normalized.split(projection.lineEnding);
297
+ if (!section.items || values.length !== section.items.length || section.items.some((item) => item.text.includes(projection.lineEnding))) throw new Error("Use Bridge list-item helpers for this section");
298
+ markdownBody = section.listStyle === "plain" ? values.join(projection.lineEnding) : values.map((line) => `- ${line}`).join(projection.lineEnding);
299
+ } else markdownBody = section.textStyle === "bullets" ? normalized.split(projection.lineEnding).map((line) => `- ${line}`).join(projection.lineEnding) : markdownSafePlainText(normalized, projection.lineEnding);
300
+ return projection.markdown.slice(0, section.bodyStart) + markdownBody + projection.markdown.slice(section.bodyEnd);
301
+ }
302
+ function listSection(projection, key) {
303
+ const section = projection.sections.find((candidate) => candidate.key === key);
304
+ if (!section || section.kind !== "list" || !section.items || !section.listStyle) throw new Error(`Unknown Bridge list section: ${key}`);
305
+ return section;
306
+ }
307
+ function editedListItem(text, style, lineEnding, original) {
308
+ const normalized = normalizeLineEndings(text, lineEnding);
309
+ if (!normalized.trim()) throw new Error("Bridge list item is empty");
310
+ const lines = normalized.split(lineEnding);
311
+ if (lines.some((line) => hasUnsafeBlock(line))) throw new Error("Bridge list item contains Markdown block structure");
312
+ if (style === "plain" && lines.length > 1) throw new Error("Plain path rows must stay on one line");
313
+ return style === "bullet" ? [lines[0], ...lines.slice(1).map((line, index) => `${original?.continuationPrefixes?.[index] ?? " "}${line}`)].join(lineEnding) : normalized;
314
+ }
315
+ /** Replace one list item without rewriting siblings and while retaining wrapped-line indentation. */
316
+ function replaceBridgeTextListItem(projection, key, index, plainText) {
317
+ const section = listSection(projection, key);
318
+ const item = section.items?.[index];
319
+ if (!item) throw new Error(`Unknown Bridge list item: ${key}[${index}]`);
320
+ if (plainText === item.text) return projection.markdown;
321
+ const edited = editedListItem(plainText, section.listStyle, projection.lineEnding, item);
322
+ return projection.markdown.slice(0, item.contentStart) + edited + projection.markdown.slice(item.contentEnd);
323
+ }
324
+ /** Remove exactly one original list-item span. */
325
+ function removeBridgeTextListItem(projection, key, index) {
326
+ const items = listSection(projection, key).items ?? [];
327
+ const item = items[index];
328
+ if (!item) throw new Error(`Unknown Bridge list item: ${key}[${index}]`);
329
+ const removeStart = index > 0 && index === items.length - 1 ? item.itemStart - projection.lineEnding.length : item.itemStart;
330
+ return projection.markdown.slice(0, removeStart) + projection.markdown.slice(item.itemEnd);
331
+ }
332
+ /** Append one item using the section's existing bullet/plain convention. */
333
+ function appendBridgeTextListItem(projection, key, plainText) {
334
+ const section = listSection(projection, key);
335
+ const edited = editedListItem(plainText, section.listStyle, projection.lineEnding);
336
+ const prefix = section.bodyStart === section.bodyEnd ? "" : projection.lineEnding;
337
+ const item = section.listStyle === "bullet" ? `- ${edited}` : edited;
338
+ return projection.markdown.slice(0, section.bodyEnd) + prefix + item + projection.markdown.slice(section.bodyEnd);
339
+ }
340
+ function previewHeaderOf(line) {
341
+ const prefix = line.startsWith("─── Handoff · ") ? {
342
+ text: "─── Handoff · ",
343
+ lang: "en"
344
+ } : line.startsWith("─── 交接摘要 · ") ? {
345
+ text: "─── 交接摘要 · ",
346
+ lang: "zh"
347
+ } : void 0;
348
+ if (!prefix) return void 0;
349
+ const route = line.slice(prefix.text.length);
350
+ const arrow = route.indexOf("→");
351
+ if (arrow < 1) return void 0;
352
+ const sourcePreset = route.slice(0, arrow).trim();
353
+ const targetTail = route.slice(arrow + 1).trimStart();
354
+ let targetEnd = 0;
355
+ while (targetEnd < targetTail.length) {
356
+ const char = targetTail[targetEnd];
357
+ if (char === void 0 || /\s/u.test(char) || char === "(" || char === "(" || char === "─") break;
358
+ targetEnd += 1;
359
+ }
360
+ const targetPreset = targetTail.slice(0, targetEnd);
361
+ if (!sourcePreset || !targetPreset) return void 0;
362
+ return {
363
+ lang: prefix.lang,
364
+ sourcePreset,
365
+ targetPreset
366
+ };
367
+ }
368
+ function isDivider(line) {
369
+ const trimmed = line.trim();
370
+ return trimmed.length >= 10 && [...trimmed].every((char) => char === "─");
371
+ }
372
+ function languageOf(text) {
373
+ return /[\u3400-\u9fff]/u.test(text) ? "zh" : "en";
374
+ }
375
+ /** Map the official WebUI document language onto Bridge's supported UI copy. */
376
+ function uiLanguageOf(documentLang) {
377
+ return documentLang?.toLowerCase().startsWith("zh") === true ? "zh" : "en";
378
+ }
379
+ function parsePreview(text) {
380
+ const lines = text.split("\n");
381
+ const header = previewHeaderOf(lines[0] ?? "");
382
+ if (!header) return void 0;
383
+ const divider = lines.findIndex((line, index) => index > 0 && isDivider(line));
384
+ if (divider < 2) return void 0;
385
+ const targetPreset = RUN_COMMAND.exec(text)?.[1] ?? header.targetPreset;
386
+ if (!targetPreset) return void 0;
387
+ const tail = lines.slice(divider + 1);
388
+ const stats = tail.find((line) => line.trim() !== "" && !line.startsWith("⚠") && !RUN_COMMAND.test(line)) ?? "";
389
+ const warnings = tail.filter((line) => line.startsWith("⚠")).map((line) => line.replace(/^⚠\s*/u, ""));
390
+ const previewIdLine = tail.find((line) => line.startsWith("Preview ID:") || line.startsWith("预览 ID:"));
391
+ const previewId = previewIdLine?.slice(previewIdLine.indexOf(previewIdLine.startsWith("Preview") ? ":" : ":") + 1).trim();
392
+ const fileLine = tail.find((line) => line.includes(" --file "));
393
+ const fileMarker = fileLine?.lastIndexOf(" --file ") ?? -1;
394
+ const summaryFile = fileMarker < 0 ? void 0 : fileLine?.slice(fileMarker + 8).trim().split(/\s/u)[0];
395
+ return {
396
+ phase: "preview",
397
+ lang: header.lang,
398
+ sourcePreset: header.sourcePreset,
399
+ targetPreset,
400
+ ...previewId ? { previewId } : {},
401
+ summary: lines.slice(1, divider).join("\n").trim(),
402
+ ...summaryFile ? { summaryFile } : {},
403
+ stats,
404
+ warnings
405
+ };
406
+ }
407
+ function parseMigrated(text) {
408
+ const lines = text.split("\n").map((line) => line.trim()).filter(Boolean);
409
+ const first = lines[0] ?? "";
410
+ const lang = first.startsWith("Created a new session") ? "en" : "zh";
411
+ const presetPrefix = lang === "en" ? "Created a new session in the " : "已在 ";
412
+ const presetSuffix = lang === "en" ? " preset" : " 模式下建好新会话";
413
+ const presetEnd = first.indexOf(presetSuffix, presetPrefix.length);
414
+ const preset = presetEnd < 0 ? void 0 : first.slice(presetPrefix.length, presetEnd).trim();
415
+ if (!preset) return void 0;
416
+ const targetIndex = lines.findIndex((line) => line.startsWith("Target session:") || line.startsWith("目标会话:"));
417
+ if (targetIndex < 0) return void 0;
418
+ const targetLine = lines[targetIndex] ?? "";
419
+ const targetPrefix = targetLine.startsWith("Target session:") ? "Target session:" : "目标会话:";
420
+ const targetPayload = targetLine.slice(targetPrefix.length).trim();
421
+ const targetSeparator = targetPayload.lastIndexOf(" · ");
422
+ if (targetSeparator < 1) return void 0;
423
+ const title = targetPayload.slice(0, targetSeparator).trim();
424
+ const sessionId = targetPayload.slice(targetSeparator + 3).trim();
425
+ if (!title || !sessionId || /\s/u.test(sessionId)) return void 0;
426
+ const remaining = lines.filter((_, index) => index !== 0 && index !== targetIndex);
427
+ return {
428
+ phase: "migrated",
429
+ lang,
430
+ targetPreset: preset,
431
+ title,
432
+ sessionId,
433
+ details: remaining.filter((line) => !line.startsWith("⚠")),
434
+ warnings: remaining.filter((line) => line.startsWith("⚠")).map((line) => line.replace(/^⚠\s*/u, ""))
435
+ };
436
+ }
437
+ /** Convert one durable `/bridge` outcome into the native card's view model. */
438
+ function parseBridgeCard(outcome) {
439
+ if (outcome === null) return { phase: "running" };
440
+ const text = outcome.text?.trim() ?? "";
441
+ if (outcome.kind === "error") return {
442
+ phase: "error",
443
+ text
444
+ };
445
+ return parsePreview(text) ?? parseMigrated(text) ?? {
446
+ phase: "message",
447
+ text,
448
+ lang: languageOf(text)
449
+ };
450
+ }
451
+ /** Return a value only when the complete editor document is valid JSON. */
452
+ function parseJsonDocument(text) {
453
+ const trimmed = text.trim();
454
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return void 0;
455
+ try {
456
+ const parsed = JSON.parse(trimmed);
457
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
458
+ } catch {
459
+ return;
460
+ }
461
+ }
462
+ function encodeUtf8Base64Url(text) {
463
+ const bytes = new TextEncoder().encode(text);
464
+ let binary = "";
465
+ for (const byte of bytes) binary += String.fromCharCode(byte);
466
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
467
+ }
468
+ /** Build the hidden-input-safe command used by the native editor confirmation. */
469
+ function buildBridgeMigrationCommand(targetPreset, summary, lang, previewId) {
470
+ if (!/^[A-Za-z0-9._-]+$/u.test(targetPreset)) throw new Error("Unsupported target preset id");
471
+ if (lang !== "zh" && lang !== "en") throw new Error("Unsupported Bridge language");
472
+ if (!/^[A-Za-z0-9-]{8,}$/u.test(previewId)) throw new Error("Unsupported Bridge preview ID");
473
+ if (!summary.trim()) throw new Error("The handoff summary is empty");
474
+ if (summary.length > 24e3) throw new Error(`The handoff summary exceeds ${MAX_EDITED_SUMMARY_CHARS} characters`);
475
+ return `/bridge ${targetPreset} --go --lang ${lang} --preview-id ${previewId} --summary64 ${encodeUtf8Base64Url(summary)}`;
476
+ }
477
+ //#endregion
478
+ //#region src/client.tsx
479
+ /** Official WebUI half: one native `/bridge` command card, not a second WebUI. */
480
+ const STYLE_ID = "dsh-plugin-bridge/native-card";
481
+ const STYLE = `
482
+ .dsh-bridge-card{border:1px solid var(--dsw-alias-border-subtle,light-dark(#dedede,#3f3f46));border-radius:12px;background:var(--dsw-alias-background-primary,light-dark(#fff,#18181b));color:var(--dsw-alias-label-primary,light-dark(#171717,#f4f4f5));overflow:hidden;box-shadow:0 1px 2px rgba(0,0,0,.12)}
483
+ .dsh-bridge-head{display:flex;align-items:center;gap:10px;min-height:44px;padding:0 14px;border-bottom:1px solid var(--dsw-alias-border-subtle,light-dark(#e6e6e6,#3f3f46));background:var(--dsw-alias-background-secondary,light-dark(#fafafa,#202024))}
484
+ .dsh-bridge-mark{display:grid;place-items:center;width:22px;height:22px;border-radius:7px;background:var(--dsw-alias-state-business-secondary,light-dark(#e8f1ff,#22325c));color:var(--dsw-alias-state-business-primary,light-dark(#2869d8,#8eaeff));font:700 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace}
485
+ .dsh-bridge-title{min-width:0;flex:1;font-size:13px;font-weight:650;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dsh-bridge-route{font:500 11px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--dsw-alias-label-secondary,light-dark(#666,#a1a1aa))}
486
+ .dsh-bridge-body{padding:14px}.dsh-bridge-copy{font-size:13px;line-height:1.55;color:var(--dsw-alias-label-secondary,light-dark(#5f6368,#b4b4bd))}
487
+ .dsh-bridge-toolbar{display:flex;align-items:center;gap:10px;margin-bottom:10px;flex-wrap:wrap}.dsh-bridge-tabs{display:inline-flex;flex-shrink:0;padding:2px;border-radius:8px;background:var(--dsw-alias-background-tertiary,light-dark(#f1f2f4,#29292e))}
488
+ .dsh-bridge-button,.dsh-bridge-tab{border:0;border-radius:7px;font:600 12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;cursor:pointer;transition:background-color .15s ease,color .15s ease,transform .1s ease}
489
+ .dsh-bridge-tab{padding:7px 10px;background:transparent;color:var(--dsw-alias-label-secondary,light-dark(#666,#a1a1aa))}.dsh-bridge-tab[aria-selected=true]{background:var(--dsw-alias-background-primary,light-dark(#fff,#3a3a40));color:var(--dsw-alias-label-primary,light-dark(#171717,#f4f4f5));box-shadow:0 1px 2px rgba(0,0,0,.18)}
490
+ .dsh-bridge-button{padding:8px 11px;background:var(--dsw-alias-background-tertiary,light-dark(#f1f2f4,#303036));color:var(--dsw-alias-label-primary,light-dark(#171717,#f4f4f5))}.dsh-bridge-button[data-primary=true]{background:var(--dsw-alias-state-business-primary,light-dark(#2869d8,#4f7ee8));color:#fff}.dsh-bridge-button:disabled{cursor:not-allowed;opacity:.55}.dsh-bridge-button:not(:disabled):active{transform:translateY(1px)}
491
+ .dsh-bridge-actions{display:flex;gap:8px;flex-wrap:wrap;margin-left:auto}.dsh-bridge-panel{box-sizing:border-box;max-height:min(56vh,520px);overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable;padding:14px;border:1px solid var(--dsw-alias-border-subtle,light-dark(#e3e5e8,#3f3f46));border-radius:9px;background:var(--dsw-alias-background-primary,light-dark(#fff,#18181b))}
492
+ .dsh-bridge-preview{min-width:0}.dsh-bridge-markdown-editor,.dsh-bridge-text-editor,.dsh-bridge-list-input{box-sizing:border-box;width:100%;border:1px solid var(--dsw-alias-border-strong,light-dark(#c8ccd2,#52525b));border-radius:8px;outline:none;background:var(--dsw-alias-background-primary,light-dark(#fff,#202024));color:var(--dsw-alias-label-primary,light-dark(#171717,#f4f4f5))}
493
+ .dsh-bridge-markdown-editor{min-height:360px;resize:vertical;padding:13px 14px;font:12px/1.65 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;tab-size:2}.dsh-bridge-text-editor{min-height:92px;resize:vertical;padding:10px 11px;font:13px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.dsh-bridge-list-input{min-width:0;min-height:34px;resize:vertical;padding:9px 10px;font:13px/1.4 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
494
+ .dsh-bridge-markdown-editor:focus,.dsh-bridge-text-editor:focus,.dsh-bridge-list-input:focus{border-color:var(--dsw-alias-state-business-primary,#2869d8);box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-state-business-primary,#2869d8) 18%,transparent)}
495
+ .dsh-bridge-form{display:grid;gap:14px}.dsh-bridge-field{display:grid;gap:7px}.dsh-bridge-field-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.dsh-bridge-field-label{font-size:12px;font-weight:700;color:var(--dsw-alias-label-primary,light-dark(#171717,#f4f4f5))}.dsh-bridge-field-help{font-size:11px;color:var(--dsw-alias-label-tertiary,light-dark(#85898f,#a1a1aa))}
496
+ .dsh-bridge-list{display:grid;gap:7px}.dsh-bridge-list-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:7px;align-items:center}.dsh-bridge-list-button{align-self:center;padding:8px 9px}.dsh-bridge-add-button{justify-self:start}.dsh-bridge-appendix{display:grid;gap:7px;padding-top:12px;border-top:1px solid var(--dsw-alias-border-subtle,light-dark(#e3e5e8,#3f3f46))}.dsh-bridge-appendix-copy{font-size:11px;color:var(--dsw-alias-label-tertiary,light-dark(#85898f,#a1a1aa))}
497
+ .dsh-bridge-notice{padding:12px;border-radius:8px;background:var(--dsw-alias-background-secondary,light-dark(#f7f8fa,#29292e));font-size:12px;line-height:1.55;color:var(--dsw-alias-label-secondary,light-dark(#5f6368,#b4b4bd))}.dsh-bridge-notice-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.dsh-bridge-draft-notice{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px;padding:9px 10px;border-radius:8px;background:var(--dsw-alias-state-warn-secondary,light-dark(#fff5d8,#443814));color:var(--dsw-alias-state-warn-primary,light-dark(#785a00,#f3d36b));font-size:12px}.dsh-bridge-draft-notice .dsh-bridge-actions{margin-left:0}
498
+ .dsh-bridge-meta{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px;color:var(--dsw-alias-label-tertiary,light-dark(#85898f,#a1a1aa));font-size:11px}.dsh-bridge-chip{padding:4px 7px;border-radius:999px;background:var(--dsw-alias-background-tertiary,light-dark(#f2f3f5,#29292e))}
499
+ .dsh-bridge-warning,.dsh-bridge-error{margin-top:10px;padding:9px 10px;border-radius:8px;font-size:12px;line-height:1.45}.dsh-bridge-warning{background:var(--dsw-alias-state-warn-secondary,light-dark(#fff5d8,#443814));color:var(--dsw-alias-state-warn-primary,light-dark(#785a00,#f3d36b))}.dsh-bridge-error{background:var(--dsw-alias-state-error-secondary,light-dark(#ffe9e7,#4a2325));color:var(--dsw-alias-state-error-primary,light-dark(#b3261e,#ffaaa4));white-space:pre-wrap}
500
+ .dsh-bridge-progress{height:3px;margin-top:12px;border-radius:999px;overflow:hidden;background:var(--dsw-alias-background-tertiary,light-dark(#eceef1,#303036))}.dsh-bridge-progress::after{content:"";display:block;width:42%;height:100%;border-radius:inherit;background:var(--dsw-alias-state-business-primary,light-dark(#2869d8,#6d92ff));animation:dsh-bridge-scan 1.35s ease-in-out infinite}
501
+ .dsh-bridge-success{display:grid;gap:10px}.dsh-bridge-session{padding:10px;border-radius:8px;background:var(--dsw-alias-state-success-secondary,light-dark(#e8f7ed,#183a26));font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.dsh-bridge-status{min-height:18px;font-size:11px;color:var(--dsw-alias-label-tertiary,light-dark(#85898f,#a1a1aa))}
502
+ .dsh-bridge-button:focus-visible,.dsh-bridge-tab:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#2869d8);outline-offset:2px}@keyframes dsh-bridge-scan{0%{transform:translateX(-110%)}100%{transform:translateX(340%)}}
503
+ @media(max-width:640px){.dsh-bridge-head{align-items:flex-start;flex-wrap:wrap;padding-block:10px}.dsh-bridge-route{width:100%;padding-left:32px}.dsh-bridge-toolbar{align-items:stretch;flex-direction:column}.dsh-bridge-tabs{align-self:flex-start;max-width:100%;overflow-x:auto}.dsh-bridge-panel{max-height:52vh;padding:11px}.dsh-bridge-actions{width:100%;margin-left:0}.dsh-bridge-toolbar>.dsh-bridge-actions .dsh-bridge-button{flex:1}.dsh-bridge-draft-notice{align-items:flex-start;flex-direction:column}.dsh-bridge-list-row{grid-template-columns:minmax(0,1fr)}}
504
+ @media(prefers-reduced-motion:reduce){.dsh-bridge-progress::after{animation:none;width:65%}.dsh-bridge-button,.dsh-bridge-tab{transition:none}}
505
+ `;
506
+ const COPY = {
507
+ zh: {
508
+ title: "会话迁移",
509
+ preparing: "正在生成可编辑的交接摘要",
510
+ safe: "原会话不会被修改",
511
+ preview: "预览",
512
+ text: "文本编辑",
513
+ markdownSource: "Markdown",
514
+ copy: "复制摘要",
515
+ copied: "已复制",
516
+ confirm: "确认迁移",
517
+ confirming: "正在创建目标会话…",
518
+ open: "打开目标会话",
519
+ opening: "正在打开目标会话…",
520
+ json: "JSON 结构",
521
+ markdownPreview: "Markdown 预览",
522
+ markdownEditor: "交接摘要 Markdown 编辑器",
523
+ chars: "字符",
524
+ listHelp: "每行一项,无需输入 Markdown 符号",
525
+ addItem: "添加一项",
526
+ removeItem: "删除此项",
527
+ appendix: "附录(只读)",
528
+ appendixHelp: "视觉证据与未解析图片会原样保留;需要修改请切换到 Markdown。",
529
+ textUnavailable: "这份摘要不是可无损转换的标准五段格式。内容没有被修改,请使用 Markdown 编辑。",
530
+ editMarkdown: "使用 Markdown",
531
+ newPreview: "检测到新的预览;当前编辑稿不会被自动覆盖。",
532
+ keepDraft: "保留编辑稿",
533
+ loadPreview: "加载新预览",
534
+ renderFailure: "Bridge 卡片渲染失败;其他插件和会话不受影响。",
535
+ tooLong: `摘要超过 WebUI 的 ${MAX_EDITED_SUMMARY_CHARS.toLocaleString()} 字符安全上限,请使用摘要文件回退。`,
536
+ fileFallback: "摘要文件",
537
+ stalePreview: "这张旧预览没有安全确认标识。请重新运行 /bridge 生成预览,或使用摘要文件流程。"
538
+ },
539
+ en: {
540
+ title: "Session handoff",
541
+ preparing: "Generating an editable handoff preview",
542
+ safe: "The source session stays untouched",
543
+ preview: "Preview",
544
+ text: "Text",
545
+ markdownSource: "Markdown",
546
+ copy: "Copy summary",
547
+ copied: "Copied",
548
+ confirm: "Confirm migration",
549
+ confirming: "Creating the target session…",
550
+ open: "Open target session",
551
+ opening: "Opening target session…",
552
+ json: "JSON structure",
553
+ markdownPreview: "Markdown preview",
554
+ markdownEditor: "Handoff summary Markdown editor",
555
+ chars: "chars",
556
+ listHelp: "One item per line; no Markdown markers needed",
557
+ addItem: "Add item",
558
+ removeItem: "Remove item",
559
+ appendix: "Appendix (read only)",
560
+ appendixHelp: "Visual evidence and unresolved images stay exact; use Markdown to edit them.",
561
+ textUnavailable: "This handoff is not a losslessly editable five-section document. Nothing changed; use Markdown instead.",
562
+ editMarkdown: "Use Markdown",
563
+ newPreview: "A newer preview arrived. Your draft was not overwritten.",
564
+ keepDraft: "Keep draft",
565
+ loadPreview: "Load new preview",
566
+ renderFailure: "The Bridge card failed to render. Other plugins and sessions are unaffected.",
567
+ tooLong: `The handoff exceeds the ${MAX_EDITED_SUMMARY_CHARS.toLocaleString()}-character WebUI safety limit. Use the summary-file fallback.`,
568
+ fileFallback: "Summary file",
569
+ stalePreview: "This older preview has no secure confirmation ID. Run /bridge again or use the summary-file workflow."
570
+ }
571
+ };
572
+ function Header({ lang, route }) {
573
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
574
+ className: "dsh-bridge-head",
575
+ children: [
576
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
577
+ className: "dsh-bridge-mark",
578
+ "aria-hidden": true,
579
+ children: "B"
580
+ }),
581
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
582
+ className: "dsh-bridge-title",
583
+ children: COPY[lang].title
584
+ }),
585
+ route ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
586
+ className: "dsh-bridge-route",
587
+ children: route
588
+ }) : null
589
+ ]
590
+ });
591
+ }
592
+ function RunningCard() {
593
+ const lang = uiLanguageOf(typeof document === "undefined" ? void 0 : document.documentElement.lang);
594
+ const copy = COPY[lang];
595
+ const [seconds, setSeconds] = (0, react.useState)(0);
596
+ (0, react.useEffect)(() => {
597
+ const started = Date.now();
598
+ const timer = window.setInterval(() => {
599
+ setSeconds(Math.floor((Date.now() - started) / 1e3));
600
+ }, 1e3);
601
+ return () => {
602
+ window.clearInterval(timer);
603
+ };
604
+ }, []);
605
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
606
+ className: "dsh-bridge-card",
607
+ "aria-live": "polite",
608
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Header, { lang }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
609
+ className: "dsh-bridge-body",
610
+ children: [
611
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
612
+ className: "dsh-bridge-copy",
613
+ children: [
614
+ copy.preparing,
615
+ " · ",
616
+ seconds,
617
+ "s"
618
+ ]
619
+ }),
620
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
621
+ className: "dsh-bridge-status",
622
+ children: copy.safe
623
+ }),
624
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
625
+ className: "dsh-bridge-progress",
626
+ "aria-hidden": true
627
+ })
628
+ ]
629
+ })]
630
+ });
631
+ }
632
+ function SummaryView({ summary, lang }) {
633
+ const json = (0, react.useMemo)(() => parseJsonDocument(summary), [summary]);
634
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
635
+ className: "dsh-bridge-preview",
636
+ "aria-label": json === void 0 ? COPY[lang].markdownPreview : COPY[lang].json,
637
+ children: json === void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.MarkdownText, { text: summary }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonTree, {
638
+ data: json,
639
+ label: COPY[lang].json
640
+ })
641
+ });
642
+ }
643
+ function TextListEditor({ lang, onAppend, onChange, onRemove, section }) {
644
+ const copy = COPY[lang];
645
+ const items = section.items ?? [];
646
+ const [draftRows, setDraftRows] = (0, react.useState)([]);
647
+ const [itemDrafts, setItemDrafts] = (0, react.useState)({});
648
+ const removeDraft = (index) => {
649
+ setDraftRows((current) => current.filter((_, itemIndex) => itemIndex !== index));
650
+ };
651
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
652
+ className: "dsh-bridge-list",
653
+ children: [
654
+ items.map((item, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
655
+ className: "dsh-bridge-list-row",
656
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
657
+ "aria-label": `${section.label} ${index + 1}`,
658
+ className: "dsh-bridge-list-input",
659
+ maxLength: MAX_EDITED_SUMMARY_CHARS,
660
+ rows: Math.min(4, item.text.split(/\r\n|\n|\r/gu).length),
661
+ value: itemDrafts[index] ?? item.text,
662
+ onChange: (event) => {
663
+ const value = event.currentTarget.value;
664
+ setItemDrafts((current) => ({
665
+ ...current,
666
+ [index]: value
667
+ }));
668
+ if (value) onChange(index, value);
669
+ },
670
+ onBlur: () => {
671
+ if (itemDrafts[index] === "") onRemove(index);
672
+ setItemDrafts((current) => {
673
+ const next = { ...current };
674
+ delete next[index];
675
+ return next;
676
+ });
677
+ },
678
+ spellCheck: true
679
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
680
+ "aria-label": `${copy.removeItem}: ${section.label} ${index + 1}`,
681
+ className: "dsh-bridge-button dsh-bridge-list-button",
682
+ type: "button",
683
+ onPointerDown: (event) => {
684
+ event.preventDefault();
685
+ },
686
+ onClick: () => {
687
+ onRemove(index);
688
+ },
689
+ children: "−"
690
+ })]
691
+ }, `${section.key}-${item.itemStart}`)),
692
+ draftRows.map((item, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
693
+ className: "dsh-bridge-list-row",
694
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
695
+ "aria-label": `${section.label} ${items.length + index + 1}`,
696
+ autoFocus: index === draftRows.length - 1,
697
+ className: "dsh-bridge-list-input",
698
+ maxLength: MAX_EDITED_SUMMARY_CHARS,
699
+ rows: 1,
700
+ value: item,
701
+ onChange: (event) => {
702
+ const value = event.currentTarget.value;
703
+ setDraftRows((current) => current.map((row, rowIndex) => rowIndex === index ? value : row));
704
+ },
705
+ onBlur: () => {
706
+ if (!item.trim() || onAppend(item)) removeDraft(index);
707
+ },
708
+ spellCheck: true
709
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
710
+ "aria-label": `${copy.removeItem}: ${section.label} ${items.length + index + 1}`,
711
+ className: "dsh-bridge-button dsh-bridge-list-button",
712
+ type: "button",
713
+ onPointerDown: (event) => {
714
+ event.preventDefault();
715
+ },
716
+ onClick: () => {
717
+ removeDraft(index);
718
+ },
719
+ children: "−"
720
+ })]
721
+ }, `${section.key}-draft-${index}`)),
722
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
723
+ className: "dsh-bridge-button dsh-bridge-add-button",
724
+ type: "button",
725
+ onClick: () => {
726
+ setDraftRows((current) => [...current, ""]);
727
+ },
728
+ "aria-label": `${copy.addItem}: ${section.label}`,
729
+ children: ["+ ", copy.addItem]
730
+ })
731
+ ]
732
+ });
733
+ }
734
+ function TextHandoffEditor({ idPrefix, lang, onChange, onError, projection }) {
735
+ const copy = COPY[lang];
736
+ const safelyApply = (operation) => {
737
+ try {
738
+ onError("");
739
+ return onChange(operation());
740
+ } catch (cause) {
741
+ onError(cause instanceof Error ? cause.message : String(cause));
742
+ return false;
743
+ }
744
+ };
745
+ const updateSection = (section, value) => {
746
+ safelyApply(() => replaceBridgeTextSection(projection, section.key, value));
747
+ };
748
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
749
+ className: "dsh-bridge-form",
750
+ children: [projection.sections.map((section) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
751
+ "aria-labelledby": section.kind === "list" ? `${idPrefix}-${section.key}-label` : void 0,
752
+ className: "dsh-bridge-field",
753
+ role: section.kind === "list" ? "group" : void 0,
754
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
755
+ className: "dsh-bridge-field-head",
756
+ children: [section.kind === "text" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("label", {
757
+ className: "dsh-bridge-field-label",
758
+ htmlFor: `${idPrefix}-${section.key}`,
759
+ children: section.label
760
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
761
+ className: "dsh-bridge-field-label",
762
+ id: `${idPrefix}-${section.key}-label`,
763
+ children: section.label
764
+ }), section.kind === "list" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
765
+ className: "dsh-bridge-field-help",
766
+ children: copy.listHelp
767
+ }) : null]
768
+ }), section.kind === "text" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
769
+ className: "dsh-bridge-text-editor",
770
+ id: `${idPrefix}-${section.key}`,
771
+ maxLength: MAX_EDITED_SUMMARY_CHARS,
772
+ value: section.text,
773
+ onChange: (event) => {
774
+ updateSection(section, event.currentTarget.value);
775
+ },
776
+ spellCheck: true
777
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TextListEditor, {
778
+ lang,
779
+ section,
780
+ onAppend: (value) => safelyApply(() => appendBridgeTextListItem(projection, section.key, value)),
781
+ onChange: (index, value) => {
782
+ safelyApply(() => replaceBridgeTextListItem(projection, section.key, index, value));
783
+ },
784
+ onRemove: (index) => {
785
+ safelyApply(() => removeBridgeTextListItem(projection, section.key, index));
786
+ }
787
+ })]
788
+ }, section.key)), projection.opaqueSuffix ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
789
+ className: "dsh-bridge-appendix",
790
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
791
+ className: "dsh-bridge-field-label",
792
+ children: copy.appendix
793
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
794
+ className: "dsh-bridge-appendix-copy",
795
+ children: copy.appendixHelp
796
+ })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SummaryView, {
797
+ summary: projection.opaqueSuffix,
798
+ lang
799
+ })]
800
+ }) : null]
801
+ });
802
+ }
803
+ const EDITOR_MODES = [
804
+ "preview",
805
+ "text",
806
+ "markdown"
807
+ ];
808
+ function PreviewCard({ card, execute, openSession, sessionId }) {
809
+ const copy = COPY[card.lang];
810
+ const panelId = (0, react.useId)();
811
+ const [mode, setMode] = (0, react.useState)("preview");
812
+ const [summary, setSummary] = (0, react.useState)(card.summary);
813
+ const [busy, setBusy] = (0, react.useState)(false);
814
+ const [status, setStatus] = (0, react.useState)("");
815
+ const [error, setError] = (0, react.useState)("");
816
+ const [pendingSummary, setPendingSummary] = (0, react.useState)(null);
817
+ const [created, setCreated] = (0, react.useState)(null);
818
+ const lastCardSummary = (0, react.useRef)(card.summary);
819
+ const confirming = (0, react.useRef)(false);
820
+ const tooLong = summary.length > MAX_EDITED_SUMMARY_CHARS;
821
+ const textProjection = (0, react.useMemo)(() => tooLong ? void 0 : parseBridgeTextProjection(summary), [summary, tooLong]);
822
+ const updateSummary = (next) => {
823
+ if (next.length > 24e3) {
824
+ setError(copy.tooLong);
825
+ return false;
826
+ }
827
+ setError("");
828
+ setSummary(next);
829
+ return true;
830
+ };
831
+ (0, react.useEffect)(() => {
832
+ const prior = lastCardSummary.current;
833
+ if (card.summary === prior) return;
834
+ lastCardSummary.current = card.summary;
835
+ if (summary === prior) {
836
+ setSummary(card.summary);
837
+ setPendingSummary(null);
838
+ } else setPendingSummary(card.summary);
839
+ }, [card.summary, summary]);
840
+ const copySummary = async () => {
841
+ try {
842
+ await navigator.clipboard.writeText(summary);
843
+ setError("");
844
+ setStatus(copy.copied);
845
+ } catch (cause) {
846
+ setStatus("");
847
+ setError(cause instanceof Error ? cause.message : String(cause));
848
+ }
849
+ };
850
+ const confirm = async () => {
851
+ if (confirming.current) return;
852
+ confirming.current = true;
853
+ setBusy(true);
854
+ setError("");
855
+ setStatus(copy.confirming);
856
+ try {
857
+ const result = parseBridgeCard(await execute(sessionId, buildBridgeMigrationCommand(card.targetPreset, summary, card.lang, card.previewId ?? "")));
858
+ if (result.phase === "error") throw new Error(result.text);
859
+ if (result.phase !== "migrated") throw new Error(card.lang === "en" ? "The host returned no target session." : "宿主没有返回目标会话。");
860
+ setCreated(result);
861
+ setStatus(copy.opening);
862
+ await openSession(result.sessionId);
863
+ } catch (cause) {
864
+ setError(cause instanceof Error ? cause.message : String(cause));
865
+ setStatus("");
866
+ } finally {
867
+ confirming.current = false;
868
+ setBusy(false);
869
+ }
870
+ };
871
+ if (created) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MigratedCard, {
872
+ card: created,
873
+ openSession,
874
+ status,
875
+ error
876
+ });
877
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
878
+ className: "dsh-bridge-card",
879
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Header, {
880
+ lang: card.lang,
881
+ route: `${card.sourcePreset} → ${card.targetPreset}`
882
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
883
+ className: "dsh-bridge-body",
884
+ children: [
885
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
886
+ className: "dsh-bridge-toolbar",
887
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
888
+ className: "dsh-bridge-tabs",
889
+ role: "tablist",
890
+ "aria-label": copy.title,
891
+ onKeyDown: (event) => {
892
+ if (![
893
+ "ArrowLeft",
894
+ "ArrowRight",
895
+ "Home",
896
+ "End"
897
+ ].includes(event.key)) return;
898
+ event.preventDefault();
899
+ const current = EDITOR_MODES.indexOf(mode);
900
+ const next = event.key === "Home" ? 0 : event.key === "End" ? EDITOR_MODES.length - 1 : (current + (event.key === "ArrowRight" ? 1 : -1) + EDITOR_MODES.length) % EDITOR_MODES.length;
901
+ const nextMode = EDITOR_MODES[next] ?? "preview";
902
+ setMode(nextMode);
903
+ window.requestAnimationFrame(() => {
904
+ document.getElementById(`${panelId}-${nextMode}`)?.focus();
905
+ });
906
+ },
907
+ children: [
908
+ ["preview", copy.preview],
909
+ ["text", copy.text],
910
+ ["markdown", copy.markdownSource]
911
+ ].map(([value, label]) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
912
+ "aria-controls": panelId,
913
+ "aria-selected": mode === value,
914
+ className: "dsh-bridge-tab",
915
+ id: `${panelId}-${value}`,
916
+ role: "tab",
917
+ tabIndex: mode === value ? 0 : -1,
918
+ type: "button",
919
+ onClick: () => {
920
+ setMode(value);
921
+ },
922
+ children: label
923
+ }, value))
924
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
925
+ className: "dsh-bridge-actions",
926
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
927
+ className: "dsh-bridge-button",
928
+ type: "button",
929
+ onClick: () => {
930
+ copySummary();
931
+ },
932
+ children: copy.copy
933
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
934
+ className: "dsh-bridge-button",
935
+ "data-primary": true,
936
+ type: "button",
937
+ disabled: busy || !card.previewId || summary.trim() === "" || tooLong,
938
+ onClick: () => {
939
+ confirm();
940
+ },
941
+ children: busy ? copy.confirming : copy.confirm
942
+ })]
943
+ })]
944
+ }),
945
+ pendingSummary !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
946
+ className: "dsh-bridge-draft-notice",
947
+ role: "status",
948
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: copy.newPreview }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
949
+ className: "dsh-bridge-actions",
950
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
951
+ className: "dsh-bridge-button",
952
+ type: "button",
953
+ onClick: () => {
954
+ setPendingSummary(null);
955
+ },
956
+ children: copy.keepDraft
957
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
958
+ className: "dsh-bridge-button",
959
+ type: "button",
960
+ onClick: () => {
961
+ setSummary(pendingSummary);
962
+ setPendingSummary(null);
963
+ },
964
+ children: copy.loadPreview
965
+ })]
966
+ })]
967
+ }) : null,
968
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
969
+ "aria-labelledby": `${panelId}-${mode}`,
970
+ className: "dsh-bridge-panel",
971
+ id: panelId,
972
+ role: "tabpanel",
973
+ children: tooLong ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
974
+ className: "dsh-bridge-notice",
975
+ role: "alert",
976
+ children: [copy.tooLong, card.summaryFile ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
977
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("br", {}),
978
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("strong", { children: [copy.fileFallback, ":"] }),
979
+ " ",
980
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { children: card.summaryFile })
981
+ ] }) : null]
982
+ }) : mode === "preview" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SummaryView, {
983
+ summary,
984
+ lang: card.lang
985
+ }) : mode === "text" ? textProjection ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TextHandoffEditor, {
986
+ idPrefix: panelId,
987
+ lang: card.lang,
988
+ projection: textProjection,
989
+ onChange: updateSummary,
990
+ onError: setError
991
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
992
+ className: "dsh-bridge-notice",
993
+ role: "status",
994
+ children: [copy.textUnavailable, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
995
+ className: "dsh-bridge-notice-actions",
996
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
997
+ className: "dsh-bridge-button",
998
+ type: "button",
999
+ onClick: () => {
1000
+ setMode("markdown");
1001
+ },
1002
+ children: copy.editMarkdown
1003
+ })
1004
+ })]
1005
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
1006
+ className: "dsh-bridge-markdown-editor",
1007
+ "aria-label": copy.markdownEditor,
1008
+ maxLength: MAX_EDITED_SUMMARY_CHARS,
1009
+ value: summary,
1010
+ onChange: (event) => {
1011
+ updateSummary(event.currentTarget.value);
1012
+ },
1013
+ spellCheck: false
1014
+ })
1015
+ }),
1016
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1017
+ className: "dsh-bridge-meta",
1018
+ children: [card.stats ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1019
+ className: "dsh-bridge-chip",
1020
+ children: card.stats
1021
+ }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1022
+ className: "dsh-bridge-chip",
1023
+ children: [
1024
+ summary.length.toLocaleString(),
1025
+ " ",
1026
+ copy.chars
1027
+ ]
1028
+ })]
1029
+ }),
1030
+ card.warnings.map((warning) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1031
+ className: "dsh-bridge-warning",
1032
+ children: ["⚠ ", warning]
1033
+ }, warning)),
1034
+ !card.previewId ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1035
+ className: "dsh-bridge-warning",
1036
+ children: ["⚠ ", copy.stalePreview]
1037
+ }) : null,
1038
+ status ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1039
+ className: "dsh-bridge-status",
1040
+ "aria-live": "polite",
1041
+ children: status
1042
+ }) : null,
1043
+ error ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1044
+ className: "dsh-bridge-error",
1045
+ role: "alert",
1046
+ children: error
1047
+ }) : null
1048
+ ]
1049
+ })]
1050
+ });
1051
+ }
1052
+ function MigratedCard({ card, error = "", openSession, status = "" }) {
1053
+ const copy = COPY[card.lang];
1054
+ const [opening, setOpening] = (0, react.useState)(false);
1055
+ const [localError, setLocalError] = (0, react.useState)(error);
1056
+ const open = async () => {
1057
+ setOpening(true);
1058
+ setLocalError("");
1059
+ try {
1060
+ await openSession(card.sessionId);
1061
+ } catch (cause) {
1062
+ setLocalError(cause instanceof Error ? cause.message : String(cause));
1063
+ } finally {
1064
+ setOpening(false);
1065
+ }
1066
+ };
1067
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1068
+ className: "dsh-bridge-card",
1069
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Header, {
1070
+ lang: card.lang,
1071
+ route: `→ ${card.targetPreset}`
1072
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1073
+ className: "dsh-bridge-body dsh-bridge-success",
1074
+ children: [
1075
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1076
+ className: "dsh-bridge-session",
1077
+ children: [
1078
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: card.title }),
1079
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("br", {}),
1080
+ card.sessionId
1081
+ ]
1082
+ }),
1083
+ card.details.map((detail) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1084
+ className: "dsh-bridge-copy",
1085
+ children: detail
1086
+ }, detail)),
1087
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1088
+ className: "dsh-bridge-actions",
1089
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1090
+ className: "dsh-bridge-button",
1091
+ "data-primary": true,
1092
+ type: "button",
1093
+ disabled: opening,
1094
+ onClick: () => {
1095
+ open();
1096
+ },
1097
+ children: opening ? copy.opening : copy.open
1098
+ })
1099
+ }),
1100
+ status ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1101
+ className: "dsh-bridge-status",
1102
+ "aria-live": "polite",
1103
+ children: status
1104
+ }) : null,
1105
+ card.warnings.map((warning) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1106
+ className: "dsh-bridge-warning",
1107
+ children: ["⚠ ", warning]
1108
+ }, warning)),
1109
+ localError ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1110
+ className: "dsh-bridge-error",
1111
+ role: "alert",
1112
+ children: localError
1113
+ }) : null
1114
+ ]
1115
+ })]
1116
+ });
1117
+ }
1118
+ function MessageCard({ card }) {
1119
+ const lang = card.phase === "message" ? card.lang : /[㐀-鿿]/u.test(card.text) ? "zh" : "en";
1120
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1121
+ className: "dsh-bridge-card",
1122
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Header, { lang }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1123
+ className: "dsh-bridge-body",
1124
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1125
+ className: "dsh-bridge-panel",
1126
+ children: card.phase === "error" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1127
+ className: "dsh-bridge-error",
1128
+ role: "alert",
1129
+ children: card.text
1130
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SummaryView, {
1131
+ summary: card.text,
1132
+ lang: card.lang
1133
+ })
1134
+ })
1135
+ })]
1136
+ });
1137
+ }
1138
+ var BridgeCardBoundary = class extends react.Component {
1139
+ state = { failed: false };
1140
+ static getDerivedStateFromError() {
1141
+ return { failed: true };
1142
+ }
1143
+ componentDidCatch(error, info) {
1144
+ console.error("dsh-plugin-bridge card render failed", error, info.componentStack);
1145
+ }
1146
+ render() {
1147
+ if (!this.state.failed) return this.props.children;
1148
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1149
+ className: "dsh-bridge-card",
1150
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Header, { lang: this.props.lang }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1151
+ className: "dsh-bridge-body",
1152
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1153
+ className: "dsh-bridge-error",
1154
+ role: "alert",
1155
+ children: COPY[this.props.lang].renderFailure
1156
+ })
1157
+ })]
1158
+ });
1159
+ }
1160
+ };
1161
+ function BridgeCommandCardContent({ node, execute, openSession, sessionId }) {
1162
+ const card = (0, react.useMemo)(() => parseBridgeCard(node.outcome), [node.outcome]);
1163
+ if (card.phase === "running") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RunningCard, {});
1164
+ if (card.phase === "preview") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PreviewCard, {
1165
+ card,
1166
+ execute,
1167
+ openSession,
1168
+ sessionId
1169
+ });
1170
+ if (card.phase === "migrated") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MigratedCard, {
1171
+ card,
1172
+ openSession
1173
+ });
1174
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessageCard, { card });
1175
+ }
1176
+ /** Rich renderer for the durable command lifecycle keyed by name and isolated from every other plugin. */
1177
+ function BridgeCommandCard(props) {
1178
+ const lang = uiLanguageOf(typeof document === "undefined" ? void 0 : document.documentElement.lang);
1179
+ const outcomeKey = props.node.outcome === null ? "running" : `${props.node.outcome.kind}:${props.node.outcome.text ?? ""}`;
1180
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BridgeCardBoundary, {
1181
+ lang,
1182
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BridgeCommandCardContent, { ...props })
1183
+ }, outcomeKey);
1184
+ }
1185
+ async function openWhenVisible(ctx, sessionId) {
1186
+ if (ctx.sessions.list.getSnapshot().byId[sessionId] !== void 0) {
1187
+ ctx.sessions.open(sessionId);
1188
+ return;
1189
+ }
1190
+ await new Promise((resolve, reject) => {
1191
+ let dispose = () => {};
1192
+ const timeout = window.setTimeout(() => {
1193
+ dispose();
1194
+ reject(/* @__PURE__ */ new Error(`Target session ${sessionId} has not reached this browser yet.`));
1195
+ }, 5e3);
1196
+ dispose = ctx.sessions.list.subscribe(() => {
1197
+ if (ctx.sessions.list.getSnapshot().byId[sessionId] === void 0) return;
1198
+ window.clearTimeout(timeout);
1199
+ dispose();
1200
+ resolve();
1201
+ });
1202
+ });
1203
+ ctx.sessions.open(sessionId);
1204
+ }
1205
+ /** Client services are supplied by the official WebUI module table. */
1206
+ const inject = [
1207
+ "slots",
1208
+ "sessions",
1209
+ "remote",
1210
+ "remote.commands"
1211
+ ];
1212
+ function apply(ctx) {
1213
+ const commands = ctx.remote.commands;
1214
+ ctx.effect(() => {
1215
+ if (document.querySelector(`style[data-plugin-css="${STYLE_ID}"]`) !== null) return () => {};
1216
+ const style = document.createElement("style");
1217
+ style.dataset.plugin = "dsh-plugin-bridge";
1218
+ style.dataset.pluginCss = STYLE_ID;
1219
+ style.textContent = STYLE;
1220
+ document.head.append(style);
1221
+ return () => {
1222
+ style.remove();
1223
+ };
1224
+ }, "bridge: native card styles");
1225
+ ctx.slots.inject("conversation.chat.commandview", () => ctx.slots.register({
1226
+ name: "conversation.chat.commandview",
1227
+ key: "bridge",
1228
+ inject: () => ({
1229
+ execute: async (sessionId, line) => {
1230
+ const result = await commands.execute(sessionId, line, []);
1231
+ if (!result.ok) throw new Error(`${result.error?.code ?? "command-failed"}: ${result.error?.message ?? "The host rejected the command."}`);
1232
+ if (result.value === void 0) throw new Error("The /bridge command was not admitted by the host.");
1233
+ return result.value.result;
1234
+ },
1235
+ openSession: (sessionId) => openWhenVisible(ctx, sessionId)
1236
+ })
1237
+ }, BridgeCommandCard));
1238
+ }
1239
+ //#endregion
1240
+ exports.BridgeCommandCard = BridgeCommandCard;
1241
+ exports.apply = apply;
1242
+ exports.inject = inject;
1243
+ return module.exports;
1244
+ }
1245
+ });
1246
+
1247
+ //# sourceMappingURL=client.js.map