dsh-builtin-browser 1.0.1 → 1.0.4

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.
Files changed (222) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/assets/browser-panel-locales.mjs +37 -5
  4. package/assets/browser-policy.d.mts +29 -0
  5. package/assets/browser-policy.mjs +40 -0
  6. package/desktop-bridge/desktop-discovery.d.mts +1 -1
  7. package/desktop-bridge/desktop-discovery.mjs +59 -9
  8. package/desktop-bridge/desktop-identity.json +12 -0
  9. package/desktop-bridge/install.mjs +14 -7
  10. package/desktop-bridge/plugin-browser-bridge.js +19 -7
  11. package/docs/acceptance-2026-11-27.md +67 -0
  12. package/docs/architecture.md +1 -1
  13. package/docs/development.md +33 -4
  14. package/docs/dsh-0.2.3-host-patch-task.md +34 -0
  15. package/docs/hardcoding-audit.md +28 -8
  16. package/docs/known-issues.md +26 -0
  17. package/docs/limitations.md +6 -2
  18. package/docs/tool-reference.md +1 -1
  19. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  20. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  21. package/dsh-host-patch/README.md +4 -0
  22. package/dsh-host-patch/apply.mjs +61 -13
  23. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  24. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  25. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  26. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  27. package/dsh-host-patch/tauri-revision1.json +39 -0
  28. package/dsh-host-patch/tauri.json +43 -0
  29. package/dsh-host-patch/v023-alpha2.json +153 -0
  30. package/lib/browser/anti-bot.js +215 -0
  31. package/lib/browser/deep-dom.js +39 -0
  32. package/lib/browser/runtime.js +15 -0
  33. package/lib/browser/takeover-target.js +13 -6
  34. package/lib/browser/types.js +30 -1
  35. package/lib/browser-electron/authenticated-route.js +16 -2
  36. package/lib/browser-electron/automatic-maintenance.js +16 -10
  37. package/lib/browser-electron/bridge-connection.js +3 -8
  38. package/lib/browser-electron/bridge-install.js +2 -1
  39. package/lib/browser-electron/bridge-status.js +55 -26
  40. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  41. package/lib/browser-electron/desktop-identity.js +28 -5
  42. package/lib/browser-electron/desktop-shell.js +64 -0
  43. package/lib/browser-electron/electron-provision.js +105 -18
  44. package/lib/browser-electron/entry.js +129 -44
  45. package/lib/browser-electron/extension-browser.js +4 -4
  46. package/lib/browser-electron/foreground-watch.js +134 -0
  47. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  48. package/lib/browser-electron/guest-route.js +181 -32
  49. package/lib/browser-electron/guest-runtime.js +61 -10
  50. package/lib/browser-electron/guest-storage.js +2 -2
  51. package/lib/browser-electron/history-store.js +1 -5
  52. package/lib/browser-electron/host-main.js +8 -4
  53. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  54. package/lib/browser-electron/maintenance-route.js +2 -1
  55. package/lib/browser-electron/missing-system-browser.js +5 -9
  56. package/lib/browser-electron/preferred-browser.js +7 -3
  57. package/lib/browser-electron/preview-route.js +9 -13
  58. package/lib/browser-electron/process-ownership.js +1 -1
  59. package/lib/browser-electron/profile-command.js +2 -1
  60. package/lib/browser-electron/profile-extension.js +5 -0
  61. package/lib/browser-electron/profile-lease.js +152 -47
  62. package/lib/browser-electron/provider-core.js +527 -0
  63. package/lib/browser-electron/provider-interaction.js +963 -0
  64. package/lib/browser-electron/provider-media.js +518 -0
  65. package/lib/browser-electron/provider-navigation.js +301 -0
  66. package/lib/browser-electron/provider-observation.js +623 -0
  67. package/lib/browser-electron/provider-tabs.js +372 -0
  68. package/lib/browser-electron/provider.js +150 -3301
  69. package/lib/browser-electron/reference-route.js +9 -18
  70. package/lib/browser-electron/remote-host.js +79 -34
  71. package/lib/browser-electron/runtime-status.js +56 -6
  72. package/lib/browser-electron/settings-store.js +3 -6
  73. package/lib/browser-electron/sidebar-only-host.js +1 -1
  74. package/lib/browser-electron/system-browser.js +539 -172
  75. package/lib/browser-electron/tauri-host.js +208 -0
  76. package/lib/browser-electron/virtual-cursor.js +23 -13
  77. package/lib/browser-reference/service.js +22 -4
  78. package/lib/browser-reference/web-sources.js +1 -1
  79. package/lib/client.js +43409 -0
  80. package/lib/compat/host-features.js +75 -0
  81. package/lib/reference-source.js +1 -1
  82. package/lib/reference-text.js +23 -1
  83. package/lib/takeover-protocol.js +1 -1
  84. package/lib/tool-browser/block-recovery.js +69 -0
  85. package/lib/tool-browser/code-tool.js +170 -19
  86. package/lib/tool-browser/code-worker.js +115 -20
  87. package/lib/tool-browser/errors.js +34 -0
  88. package/lib/tool-browser/index.js +66 -3593
  89. package/lib/tool-browser/page-probe.js +227 -28
  90. package/lib/tool-browser/panel-page.js +2 -1
  91. package/lib/tool-browser/probe-client.js +157 -0
  92. package/lib/tool-browser/screenshot-annotations.js +108 -0
  93. package/lib/tool-browser/state.js +337 -0
  94. package/lib/tool-browser/takeover.js +1 -1
  95. package/lib/tool-browser/tools-debug.js +862 -0
  96. package/lib/tool-browser/tools-interaction.js +993 -0
  97. package/lib/tool-browser/tools-navigation.js +807 -0
  98. package/lib/tool-browser/tools-observation.js +461 -0
  99. package/lib/tool-browser/tools-reference.js +293 -0
  100. package/lib/web-guest.js +1 -0
  101. package/package.json +16 -36
  102. package/scripts/build-client.mjs +305 -0
  103. package/scripts/build.mjs +15 -12
  104. package/scripts/fix-exports.mjs +6 -16
  105. package/scripts/install-electron.mjs +55 -5
  106. package/scripts/pack.mjs +99 -0
  107. package/scripts/publish-manifest.mjs +56 -0
  108. package/scripts/verify-exports.mjs +26 -15
  109. package/skills/dsh-builtin-browser/SKILL.md +27 -2
  110. package/skills/dsh-builtin-browser/references/batch.md +15 -0
  111. package/src/browser/anti-bot.ts +251 -0
  112. package/src/browser/deep-dom.ts +40 -0
  113. package/src/browser/runtime.ts +18 -0
  114. package/src/browser/takeover-target.ts +16 -7
  115. package/src/browser/types.ts +56 -3
  116. package/src/browser-electron/authenticated-route.ts +29 -4
  117. package/src/browser-electron/automatic-maintenance.ts +23 -13
  118. package/src/browser-electron/bridge-connection.ts +11 -10
  119. package/src/browser-electron/bridge-install.ts +2 -1
  120. package/src/browser-electron/bridge-status.ts +61 -22
  121. package/src/browser-electron/desktop-bridge-host.ts +9 -7
  122. package/src/browser-electron/desktop-identity.ts +38 -5
  123. package/src/browser-electron/desktop-shell.ts +100 -0
  124. package/src/browser-electron/electron-provision.ts +104 -18
  125. package/src/browser-electron/entry.ts +1378 -1299
  126. package/src/browser-electron/extension-browser.ts +11 -4
  127. package/src/browser-electron/foreground-watch.ts +142 -0
  128. package/src/browser-electron/guest-cookie-jar.ts +3 -2
  129. package/src/browser-electron/guest-route.ts +180 -32
  130. package/src/browser-electron/guest-runtime.ts +61 -10
  131. package/src/browser-electron/guest-storage.ts +5 -2
  132. package/src/browser-electron/history-store.ts +3 -6
  133. package/src/browser-electron/host-main.ts +8 -4
  134. package/src/browser-electron/host-patch-maintenance.ts +18 -9
  135. package/src/browser-electron/maintenance-route.ts +2 -1
  136. package/src/browser-electron/missing-system-browser.ts +11 -10
  137. package/src/browser-electron/preferred-browser.ts +13 -3
  138. package/src/browser-electron/preview-route.ts +9 -12
  139. package/src/browser-electron/process-ownership.ts +9 -3
  140. package/src/browser-electron/profile-command.ts +2 -1
  141. package/src/browser-electron/profile-extension.ts +5 -0
  142. package/src/browser-electron/profile-lease.ts +131 -35
  143. package/src/browser-electron/provider-core.ts +1107 -0
  144. package/src/browser-electron/provider-interaction.ts +1034 -0
  145. package/src/browser-electron/provider-media.ts +589 -0
  146. package/src/browser-electron/provider-navigation.ts +323 -0
  147. package/src/browser-electron/provider-observation.ts +664 -0
  148. package/src/browser-electron/provider-tabs.ts +372 -0
  149. package/src/browser-electron/provider.ts +158 -4063
  150. package/src/browser-electron/reference-route.ts +598 -608
  151. package/src/browser-electron/remote-host.ts +118 -42
  152. package/src/browser-electron/runtime-status.ts +80 -13
  153. package/src/browser-electron/settings-store.ts +10 -6
  154. package/src/browser-electron/sidebar-only-host.ts +4 -2
  155. package/src/browser-electron/system-browser.ts +537 -184
  156. package/src/browser-electron/tauri-host.ts +194 -0
  157. package/src/browser-electron/virtual-cursor.ts +24 -14
  158. package/src/browser-reference/service.ts +38 -7
  159. package/src/browser-reference/web-sources.ts +4 -1
  160. package/src/client/apply-guard.ts +22 -0
  161. package/src/client/browser/BrowserController.ts +3 -3
  162. package/src/client/browser/IframeImpl.ts +182 -176
  163. package/src/client/browser/frame-history.ts +125 -0
  164. package/src/client/browser/frame-state.ts +27 -0
  165. package/src/client/browser/web-reference-source.ts +5 -1
  166. package/src/client/definition.tsx +36 -30
  167. package/src/client/electron/ElectronWebViewImpl.ts +20 -13
  168. package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
  169. package/src/client/electron/NativeChildPresentation.ts +11 -3
  170. package/src/client/electron/NativeViewPage.ts +19 -5
  171. package/src/client/index.ts +333 -293
  172. package/src/client/locales.ts +9 -6
  173. package/src/client/reference/client/plugin.ts +21 -2
  174. package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
  175. package/src/client/reference/client/production/assembly.ts +4 -28
  176. package/src/client/reference/client/production/availability.ts +0 -2
  177. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  178. package/src/client/reference/client/production/draft-adapter.ts +4 -0
  179. package/src/client/reference/client/production/http-transport.ts +0 -5
  180. package/src/client/reference/client/production/production-submission.ts +50 -290
  181. package/src/client/reference/client/production/protocol.ts +7 -4
  182. package/src/client/reference/client/production/runtime.ts +41 -86
  183. package/src/client/reference/client/production/source-marker.ts +49 -13
  184. package/src/client/reference/client/production/user-text-rule.ts +10 -1
  185. package/src/client/reference/client/reveal.ts +3 -1
  186. package/src/client/reference/client/session-schedule.ts +36 -0
  187. package/src/client/settings/index.ts +8 -0
  188. package/src/client/settings/mount-guard.ts +31 -0
  189. package/src/client/settings/panel.ts +163 -52
  190. package/src/client/startpage/controller.ts +3 -6
  191. package/src/client/view/BrowserBody.tsx +2 -1
  192. package/src/client/view/IframePresentation.ts +37 -16
  193. package/src/client/view/StartPage.tsx +2 -1
  194. package/src/compat/host-features.ts +92 -0
  195. package/src/reference-source.ts +1 -1
  196. package/src/reference-text.ts +23 -1
  197. package/src/takeover-protocol.ts +11 -2
  198. package/src/tool-browser/block-recovery.ts +85 -0
  199. package/src/tool-browser/code-tool.ts +173 -19
  200. package/src/tool-browser/code-worker.ts +101 -15
  201. package/src/tool-browser/errors.ts +40 -0
  202. package/src/tool-browser/index.ts +66 -3534
  203. package/src/tool-browser/page-probe.ts +229 -28
  204. package/src/tool-browser/panel-page.ts +3 -1
  205. package/src/tool-browser/probe-client.ts +183 -0
  206. package/src/tool-browser/screenshot-annotations.ts +131 -0
  207. package/src/tool-browser/state.ts +375 -0
  208. package/src/tool-browser/takeover.ts +3 -2
  209. package/src/tool-browser/tools-debug.ts +806 -0
  210. package/src/tool-browser/tools-interaction.ts +956 -0
  211. package/src/tool-browser/tools-navigation.ts +786 -0
  212. package/src/tool-browser/tools-observation.ts +474 -0
  213. package/src/tool-browser/tools-reference.ts +294 -0
  214. package/src/web-guest.ts +35 -34
  215. package/dist/client.cjs +0 -43167
  216. package/dist/client.d.cts +0 -516
  217. package/dist/client.d.mts +0 -516
  218. package/dist/index.cjs +0 -92
  219. package/dist/index.d.mts +0 -2960
  220. package/dist/index.mjs +0 -24
  221. package/lib/browser-reference/submission-receipts.js +0 -139
  222. package/src/browser-reference/submission-receipts.ts +0 -122
@@ -1,310 +1,70 @@
1
1
  /**
2
- * Ordered submission projection into the HOST's real prompt content blocks.
2
+ * What one captured reference puts into the composer.
3
3
  *
4
- * The host's `service.ts:302` currently builds
5
- * `content = [...uploaded, ...(text === '' ? [] : [{ type: 'text', text }])]`
6
- * where `uploaded` are already-serialized `PromptContentPart`s from the host's
7
- * image/file attachment admission. We REUSE `createSubmissionProjector` (the
8
- * additive contract) to interleave the captured groups in capture order, then
9
- * map its `text`/`image`/`table` parts into the host's content vocabulary:
10
- * - `text` / `table` -> `{ type: 'text', text }` (verbatim / structural text);
11
- * - `image` -> `admitImage(assetKey)` -> a REAL `{ type: 'image', data }` or
12
- * `{ type: 'file', receiptId }` from the host attachment service. NEVER a
13
- * URL and NEVER alt text; an unbound image keeps its slot as a placeholder.
14
- *
15
- * Host attachments (`uploaded`) stay first and the plain composer text stays
16
- * last, matching `service.ts:302` ("附件在前文字在后"); group parts are inserted
17
- * between them in order.
18
- *
19
- * This module does NOT import or modify `service.ts`. `wireSubmissionContent`
20
- * is the injectable seam the host calls at line 302 (see deploy/README.md).
21
- *
22
- * @module dsh-browser-reference/production/production-submission
4
+ * The stock conversation send path is `[...serializeAttachments(), { type: 'text', text }]`: the model
5
+ * sees the composer text and the composer attachments, nothing else. So a reference reaches the model
6
+ * only through those two places — its text, tables and image placeholders become the quote inserted
7
+ * into the editor, and its images become composer attachments.
23
8
  */
24
9
  import { renderReferenceMarkdownTable } from '../../../../reference-text.ts'
25
- import { referenceOwnerKey } from '../../../../reference-owner.ts'
26
10
  import type { OrderedReferenceGroup } from '../types.ts'
27
- import { createSubmissionProjector, type TextPosition } from '../ordered-submission.ts'
28
- import { composerText, sourceMarker, submissionQuote } from './source-marker.ts'
29
- import type { AssetStore } from './asset-store.ts'
30
-
31
- /** Mirror of `session-controller/src/types.ts:78` (no cross-package import). */
32
- export type HostPromptContentPart =
33
- | { readonly type: 'text'; readonly text: string }
34
- | { readonly type: 'image'; readonly mediaType: string; readonly data: string; readonly name?: string }
35
- | { readonly type: 'file'; readonly receiptId: string }
36
-
37
- /**
38
- * Resolve one captured image asset into a host-admitted content block.
39
- * Returns undefined when the asset is not durably bound yet.
40
- */
41
- export type AdmitImage = (assetKey: string, partId: string) => HostPromptContentPart | undefined
11
+ import { createSubmissionProjector } from '../ordered-submission.ts'
12
+ import { composerQuote, sourceMarker } from './source-marker.ts'
13
+ import type { AssetBinding, AssetStore } from './asset-store.ts'
42
14
 
43
- /**
44
- * Default admission backed by the durable asset store: inline real bytes, or a
45
- * file receipt when the host uploaded the asset. This is the "宿主已有的
46
- * 图片/文件附件准入与持久服务" output, not a page URL.
47
- */
48
- export function createAdmitImage(assets: AssetStore): AdmitImage {
49
- return (assetKey, partId) => {
50
- const binding = assets.get(assetKey)
51
- if (binding === undefined) return undefined
52
- if (binding.receiptId !== undefined) {
53
- return { type: 'file', receiptId: binding.receiptId }
54
- }
55
- return {
56
- type: 'image',
57
- mediaType: binding.mime,
58
- data: binding.data,
59
- name: partId,
60
- }
61
- }
62
- }
63
-
64
- export interface WireSubmissionInput {
65
- /** Host-serialized attachments, kept verbatim at the front. */
66
- readonly uploaded: readonly HostPromptContentPart[]
67
- /** Plain composer text; kept last (matching service.ts:302). */
68
- readonly text: string
69
- /** Ordered captured groups for this session. */
70
- readonly groups: readonly OrderedReferenceGroup[]
71
- readonly admitImage: AdmitImage
72
- readonly textPosition?: TextPosition
73
- /**
74
- * The user's note per reference. It is submitted as its OWN labelled block so
75
- * the model never confuses the human's words with the quoted page text
76
- * (three-state §6).
77
- */
78
- readonly comments?: ReadonlyMap<string, string>
79
- /**
80
- * Emit one clickable `dsh-browser-ref:` source marker per group. Defaults to
81
- * TRUE so the real send path always produces a locatable source. Setting it
82
- * to false restores the exact pre-marker projection (byte-identical to the
83
- * old output), which is the comparison/rollback lever for A/B tests and for
84
- * diagnosing a bad link without changing what the model received.
85
- */
86
- readonly sourceLinks?: boolean
87
- /**
88
- * Optional page title per reference, used ONLY as the marker's visible text
89
- * (never inside the URI). When absent a stable `引用来源 N` label is used.
90
- * `toOrderedGroup` drops `source.title`, so production currently takes the
91
- * fallback; the callback is the seam a host can wire to surface real titles.
92
- */
93
- readonly sourceTitleFor?: (referenceId: string) => string | undefined
94
- }
95
-
96
- /** The prefix that keeps a note distinguishable from the quoted original. */
97
- export const COMMENT_LABEL = '引用评论'
98
15
  /** Stable visible label for one attached reference's source marker. */
99
16
  export { SOURCE_LINK_LABEL } from './source-marker.ts'
100
17
 
101
- /**
102
- * Build the `content` array for `Session.prompt`. With `groups === []` the
103
- * result is byte-identical to the host's current `[...uploaded, ...text]`.
104
- */
105
- export function wireSubmissionContent(input: WireSubmissionInput): readonly HostPromptContentPart[] {
106
- const perGroup = createSubmissionProjector({ mode: 'ordered' })
107
- const text = composerText(input.text, new Set(input.groups.map(group => group.referenceId)))
108
- const quoteText = (text: string): string => input.sourceLinks === false ? text : submissionQuote(text)
109
- const projectedBlocks = (groups: readonly OrderedReferenceGroup[]): HostPromptContentPart[] =>
110
- perGroup.project({ text: '', uploaded: [], groups }).map(part => {
111
- const mapped = mapProjected(part, input.admitImage)
112
- return mapped.type === 'text' ? { type: 'text', text: quoteText(`${mapped.text}\n`) } : mapped
113
- })
114
- const placeUserText = (blocks: HostPromptContentPart[]): void => {
115
- if (text === '') return
116
- const block: HostPromptContentPart = { type: 'text', text }
117
- if (input.textPosition === 'leading') blocks.unshift(block)
118
- else blocks.push(block)
119
- }
120
- // Source markers are ONE extra independent text block appended AFTER every
121
- // projected group (and after every note), BEFORE the user's own question.
122
- // They never touch a projected block, so quoted text stays verbatim and keeps
123
- // its trailing newline (the fifth-round fix). With no groups nothing is added,
124
- // so `groups === []` stays byte-identical to service.ts:302.
125
- const appendSourceMarkers = (blocks: HostPromptContentPart[]): void => {
126
- if (input.sourceLinks === false || input.groups.length === 0) return
127
- const markers: string[] = []
128
- input.groups.forEach((group, index) => {
129
- try {
130
- markers.push(sourceMarker(group.referenceId, index, input.sourceTitleFor?.(group.referenceId)))
131
- } catch {
132
- // A referenceId that cannot be canonicalized must not break the whole
133
- // send: that single group simply has no marker (B20 partial visibility).
134
- }
135
- })
136
- if (markers.length === 0) return
137
- blocks.push({ type: 'text', text: `${markers.join('\n')}\n${submissionQuote('Browser reference presentation: the attached references are already displayed as interactive capsules. Do not repeat their markers, reference URIs, source URLs, or source/citation links in the reply. Answer using the quoted content; the capsules provide source navigation.')}` })
138
- }
139
- const noted = input.comments === undefined
140
- ? undefined
141
- : input.groups.filter(group => (input.comments?.get(group.referenceId) ?? '') !== '')
142
- if (noted !== undefined && noted.length > 0 && input.comments !== undefined) {
143
- // Project group by group so each note lands immediately before the content
144
- // it annotates, while the parts inside a group keep their captured order.
145
- const withNotes: HostPromptContentPart[] = []
146
- for (const group of input.groups) {
147
- const note = input.comments.get(group.referenceId)
148
- if (note !== undefined && note !== '') {
149
- // A plain label, not markdown: the user's own message text is rendered as text, so asterisks showed
150
- // up literally ("**引用评论**:123"). Brackets looked like page content; a bare label reads as a
151
- // label in every renderer.
152
- withNotes.push({ type: 'text', text: quoteText(`${COMMENT_LABEL}:${note}\n`) })
153
- }
154
- withNotes.push(...projectedBlocks([group]))
155
- }
156
- appendSourceMarkers(withNotes)
157
- placeUserText(withNotes)
158
- return [...input.uploaded, ...withNotes]
159
- }
160
- const blocks: HostPromptContentPart[] = projectedBlocks(input.groups)
161
- appendSourceMarkers(blocks)
162
- placeUserText(blocks)
163
- return [...input.uploaded, ...blocks]
164
- }
18
+ export const REFERENCE_PRESENTATION = 'Browser reference presentation: this quote is already displayed as an interactive capsule. Do not repeat its marker, reference URI, source URL, or source/citation links in the reply. Answer using the quoted content; the capsule provides source navigation.'
165
19
 
166
- /** Map one projected part into the host's content vocabulary. */
167
- function mapProjected(
168
- part: ReturnType<ReturnType<typeof createSubmissionProjector>['project']>[number],
169
- admitImage: AdmitImage,
170
- ): HostPromptContentPart {
171
- switch (part.type) {
172
- case 'text':
173
- return { type: 'text', text: part.text }
174
- case 'table':
175
- return { type: 'text', text: part.table === undefined ? part.text : renderReferenceMarkdownTable(part.table) }
176
- case 'image': {
177
- const admitted = admitImage(part.assetKey, part.partId ?? part.assetKey)
178
- return admitted ?? { type: 'text', text: `[image unavailable: ${part.partId ?? part.assetKey}]` }
179
- }
180
- default: {
181
- const exhaustive: never = part
182
- throw new Error(`unhandled projected part: ${JSON.stringify(exhaustive)}`)
183
- }
184
- }
20
+ /** One captured image that travels as a composer attachment. */
21
+ export interface ComposerImage {
22
+ readonly partId: string
23
+ readonly binding: AssetBinding
185
24
  }
186
25
 
187
- /**
188
- * Injection seam the host registers; binds a session id to its stored groups.
189
- * `requestId` is OPTIONAL everywhere, so implementations/tests that omit it
190
- * keep working through a FIFO fallback.
191
- */
192
- export interface SubmissionSeam {
193
- /** Reconcile durable consumption before projecting a restored draft. */
194
- prepare?(sessionId: string): Promise<void>
195
- bind?(sessionId: string, requestId: string, hostRequestId: string): Promise<void>
196
- /** Replacement for the `content = [...uploaded, ...text]` line at service.ts:302. */
197
- buildContent(input: {
198
- readonly sessionId: string
199
- readonly uploaded: readonly HostPromptContentPart[]
200
- readonly text: string
201
- /** Stable per-send id; lets concurrent sends keep separate frozen sets. */
202
- readonly requestId?: string
203
- }): readonly HostPromptContentPart[]
204
- /**
205
- * Consume the exact set frozen by this send's `buildContent`.
206
- *
207
- * The host calls this only after `Session.prompt` ACCEPTED the content. A
208
- * projection alone must never clear the draft: a refused send would drop the
209
- * references the user still sees, and a footnote would no longer point at the
210
- * message it came with. References added while the send was in flight are not
211
- * part of the frozen set and stay in the draft.
212
- */
213
- commit(sessionId: string, requestId?: string): void | Promise<void>
214
- /**
215
- * Drop the frozen set without consuming anything (refused or thrown send).
216
- *
217
- * The draft keeps every reference, so the user can fix the problem and send
218
- * again with the same quotes.
219
- */
220
- rollback(sessionId: string, requestId?: string): void
26
+ export interface ComposerReference {
27
+ /** The quote text inserted into the editor; the host sends it verbatim (line-quoted). */
28
+ readonly text: string
29
+ /** Images bound in the durable asset store, in capture order. */
30
+ readonly images: readonly ComposerImage[]
221
31
  }
222
32
 
223
- export interface CreateSubmissionSeamOptions {
224
- readonly bind?: (sessionId: string, hostRequestId: string, intentIds: readonly string[]) => Promise<void>
225
- /** Resolve the ordered groups for one session (from the session draft store). */
226
- readonly groupsFor: (sessionId: string) => readonly OrderedReferenceGroup[]
227
- /** Resolve the durable asset store for one session. */
228
- readonly assetsFor: (sessionId: string) => AssetStore
229
- /** The draft's notes per reference, submitted as labelled blocks. */
230
- readonly commentsFor?: (sessionId: string) => ReadonlyMap<string, string>
231
- /**
232
- * Called with the exact reference ids a now-accepted send carried, so the
233
- * draft stops holding them while the sent message keeps their provenance.
234
- *
235
- * Without this the next message re-attaches the same quote: the card survived the
236
- * send, and a restart rebuilt it from its acknowledged delivery.
237
- */
238
- readonly submitted?: (sessionId: string, referenceIds: readonly string[]) => void | Promise<void>
239
- readonly textPosition?: TextPosition
240
- /** Passed through to `wireSubmissionContent`; omitted => source links ON. */
241
- readonly sourceLinks?: boolean
242
- /** Optional visible page title per reference for the source markers. */
243
- readonly sourceTitleFor?: (referenceId: string) => string | undefined
33
+ export interface ComposerReferenceInput {
34
+ /** Zero-based position among this draft's references (the marker's visible number). */
35
+ readonly index: number
36
+ readonly title?: string
37
+ readonly assets: AssetStore
244
38
  }
245
39
 
246
- /** Build the seam the assembly registers into the host context. */
247
- export function createSubmissionSeam(options: CreateSubmissionSeamOptions): SubmissionSeam {
248
- /** One frozen set per requestId — never a single overwritable per-session key. */
249
- const tokenized = new Map<string, readonly string[]>()
250
- /** Untagged sends (older hosts / tests) fall back to a per-session FIFO queue. */
251
- const untagged = new Map<string, string[][]>()
252
-
253
- const consume = (sessionId: string, requestId?: string): readonly string[] | undefined => {
254
- if (requestId !== undefined) {
255
- const ids = tokenized.get(requestId)
256
- tokenized.delete(requestId)
257
- if (ids !== undefined) return ids
258
- }
259
- const queue = untagged.get(sessionId)
260
- const ids = queue?.shift()
261
- if (queue !== undefined && queue.length === 0) untagged.delete(sessionId)
262
- return ids
263
- }
264
-
265
- return {
266
- async bind(sessionId, requestId, hostRequestId) {
267
- sessionId = referenceOwnerKey(sessionId)
268
- const ids = tokenized.get(requestId)
269
- if (ids !== undefined && ids.length > 0) await options.bind?.(sessionId, hostRequestId, ids)
270
- },
271
- buildContent({ sessionId: rawSessionId, uploaded, text, requestId }) {
272
- // The send path passes the shell's "session-<uuid>"; the draft store, the comments and the asset
273
- // bindings are all keyed on the bare id. Without this the chips were visible in the composer while
274
- // buildContent saw ZERO groups, so the message went out with the typed text alone and the model
275
- // answered "there is nothing attached".
276
- const sessionId = referenceOwnerKey(rawSessionId)
277
- const groups = options.groupsFor(sessionId)
278
- const content = wireSubmissionContent({
279
- uploaded,
280
- text,
281
- groups,
282
- admitImage: createAdmitImage(options.assetsFor(sessionId)),
283
- ...options.commentsFor === undefined ? {} : { comments: options.commentsFor(sessionId) },
284
- ...(options.textPosition === undefined ? {} : { textPosition: options.textPosition }),
285
- ...(options.sourceLinks === undefined ? {} : { sourceLinks: options.sourceLinks }),
286
- ...(options.sourceTitleFor === undefined ? {} : { sourceTitleFor: options.sourceTitleFor }),
287
- })
288
- const ids = groups.map(group => group.referenceId)
289
- // Pure read: remember what this projection used, decide nothing yet.
290
- if (requestId !== undefined) tokenized.set(requestId, ids)
291
- else {
292
- const queue = untagged.get(sessionId) ?? []
293
- queue.push(ids)
294
- untagged.set(sessionId, queue)
40
+ /** Project one reference group into the composer quote and its image attachments. */
41
+ export function composerReference(group: OrderedReferenceGroup, input: ComposerReferenceInput): ComposerReference {
42
+ const lines: string[] = []
43
+ const images: ComposerImage[] = []
44
+ for (const part of createSubmissionProjector({ mode: 'ordered' }).project({ text: '', uploaded: [], groups: [group] })) {
45
+ switch (part.type) {
46
+ case 'text':
47
+ lines.push(part.text)
48
+ break
49
+ case 'table':
50
+ lines.push(part.table === undefined ? part.text : renderReferenceMarkdownTable(part.table))
51
+ break
52
+ case 'image': {
53
+ const partId = part.partId ?? part.assetKey
54
+ const binding = input.assets.get(part.assetKey)
55
+ if (binding === undefined) lines.push(`[image unavailable: ${partId}]`)
56
+ else {
57
+ images.push({ partId, binding })
58
+ lines.push(`[image ${images.length}: ${partId}, attached to this message]`)
59
+ }
60
+ break
295
61
  }
296
- return content
297
- },
298
- commit(sessionId, requestId) {
299
- sessionId = referenceOwnerKey(sessionId)
300
- const referenceIds = consume(sessionId, requestId)
301
- if (referenceIds !== undefined && referenceIds.length > 0) {
302
- return options.submitted?.(sessionId, referenceIds)
62
+ default: {
63
+ const exhaustive: never = part
64
+ throw new Error(`unhandled projected part: ${JSON.stringify(exhaustive)}`)
303
65
  }
304
- },
305
- rollback(sessionId, requestId) {
306
- sessionId = referenceOwnerKey(sessionId)
307
- consume(sessionId, requestId)
308
- },
66
+ }
309
67
  }
68
+ lines.push(REFERENCE_PRESENTATION)
69
+ return { text: composerQuote(lines.join('\n'), sourceMarker(group.referenceId, input.index, input.title)), images }
310
70
  }
@@ -166,8 +166,6 @@ export interface DeliveryRecord {
166
166
  }
167
167
 
168
168
  export interface DeliveriesResponse {
169
- readonly tracksSubmissions?: boolean
170
- readonly unverified?: readonly string[]
171
169
  readonly ok: true
172
170
  readonly sequence: number
173
171
  readonly deliveries: readonly DeliveryRecord[]
@@ -220,12 +218,17 @@ export type ExportFormat = 'jsonl' | 'markdown' | 'zip' | 'markdown-zip'
220
218
 
221
219
  /** Transport error whose status shapes the caller's decision (409 = refuse ACK). */
222
220
  export class ReferenceHttpError extends Error {
221
+ readonly status: number
222
+ readonly body?: unknown
223
223
  constructor(
224
224
  message: string,
225
- readonly status: number,
226
- readonly body?: unknown,
225
+ status: number,
226
+ body?: unknown,
227
227
  ) {
228
+
228
229
  super(message)
230
+ this.status = status
231
+ this.body = body
229
232
  this.name = 'ReferenceHttpError'
230
233
  }
231
234
  }
@@ -39,12 +39,7 @@ import {
39
39
  } from './reference-card.ts'
40
40
  import { encodeBrowserRefUri, parseBrowserRefUri } from '../scheme.ts'
41
41
  import type { RevealStatus } from '../types.ts'
42
- import {
43
- createSubmissionSeam,
44
- type HostPromptContentPart,
45
- type SubmissionSeam,
46
- } from './production-submission.ts'
47
- import { sourceMarker } from './source-marker.ts'
42
+ import { composerReference } from './production-submission.ts'
48
43
  import {
49
44
  createProductionRevealer,
50
45
  type ProductionRevealer,
@@ -196,9 +191,6 @@ export interface ProductionRuntime {
196
191
  availability(): AvailabilityState
197
192
  /** All sessions' reflections, for reveal routing. */
198
193
  ownerFor(referenceId: string): RevealOwner | undefined
199
- /** Ordered submission seam the host calls at service.ts:302. */
200
- readonly submission: SubmissionSeam
201
- projectContent(input: { uploaded: readonly HostPromptContentPart[]; text: string }): readonly HostPromptContentPart[]
202
194
  /** Remove a card for good: tombstoned locally and dropped on the plugin side. */
203
195
  removeCard(referenceId: string): Promise<void>
204
196
  /** Jump the sidebar browser back to a reference's原文 and highlight it. */
@@ -494,20 +486,29 @@ export function createProductionRuntime(options: ProductionRuntimeOptions): Prod
494
486
  const host = hostInputFor(sessionId)
495
487
  const title = delivery.snapshot.source.title
496
488
  const index = (draftStoreFor(sessionId).state().reflections ?? []).length
497
- const marker = sourceMarker(delivery.referenceId, index - 1, title)
489
+ const reference = composerReference(toOrderedGroup(delivery.snapshot), {
490
+ index: index - 1, assets: assetStoreFor(sessionId), ...title === undefined ? {} : { title },
491
+ })
498
492
  // 插入需要编辑器里有光标:确认按钮是在侧栏 iframe 里点的,先聚焦编辑器。
499
493
  try { host.focusEditor?.() } catch { /* 没有编辑器就交给下面的失败路径 */ }
500
494
  const uri = encodeBrowserRefUri({ referenceId: delivery.referenceId })
495
+ let inserted = false
501
496
  try {
502
- if (host.insertQuote?.(marker)) return true
503
- if (host.insertReference?.({
504
- source: 'browser-reference', ref: uri, label: title || '网页引用',
505
- appearance: 'session', clipboardText: marker,
506
- }, host.captureInsertion())) return true
507
- return false
497
+ inserted = host.insertQuote?.(reference.text) === true
498
+ || host.insertReference?.({
499
+ source: 'browser-reference', ref: uri, label: title || '网页引用',
500
+ appearance: 'session', clipboardText: reference.text,
501
+ }, host.captureInsertion()) === true
508
502
  } catch {
509
503
  return false
510
504
  }
505
+ if (inserted && reference.images.length > 0) {
506
+ try {
507
+ const ids = host.attachImages?.(reference.images) ?? []
508
+ if (ids.length > 0) attachedImages.set(`${sessionId}${delivery.referenceId}`, ids)
509
+ } catch { /* 图片附件是尽力而为:引文已带占位说明 */ }
510
+ }
511
+ return inserted
511
512
  }
512
513
 
513
514
  const processDelivery = async (delivery: DeliveryRecord, sessionId: string): Promise<ApplyOutcome> => {
@@ -757,61 +758,6 @@ export function createProductionRuntime(options: ProductionRuntimeOptions): Prod
757
758
  return flushConsumptions()
758
759
  }
759
760
 
760
- const tracksSubmissions = new Set<string>()
761
- const submission = createSubmissionSeam({
762
- bind: async (sessionId, hostRequestId, intentIds) => {
763
- if (tracksSubmissions.has(sessionId)) await http.bindSubmission?.(sessionId, hostRequestId, intentIds)
764
- },
765
- groupsFor: sessionId => draftStoreFor(sessionId).state().groups,
766
- submitted: consumeSubmitted,
767
- assetsFor: sessionId => assetStoreFor(sessionId),
768
- // Real page titles make the sent message's source link readable. ownerFor
769
- // resolves draft, pendingArchive and sent reflections, so a link produced
770
- // by this seam keeps its title even after the card has cleared.
771
- sourceTitleFor: referenceId => ownerFor(referenceId)?.label,
772
- commentsFor: sessionId => {
773
- const notes = new Map<string, string>()
774
- for (const reflection of draftStoreFor(sessionId).state().reflections) {
775
- if (reflection.comment !== undefined && reflection.comment !== '') {
776
- notes.set(reflection.referenceId, reflection.comment)
777
- }
778
- }
779
- return notes
780
- },
781
- ...(options.textPosition === undefined ? {} : { textPosition: options.textPosition }),
782
- })
783
-
784
- // Idempotent retry hook for the host. `createSubmissionSeam.commit` consumes
785
- // its per-send token, so a plain re-commit after a failed cleanup would be a
786
- // no-op; this hook instead flushes any pending archive directly. It NEVER
787
- // re-sends a message and NEVER re-ACKs. The assembly registers THIS SAME
788
- // object as `browserReferenceSubmission`, so service.ts can reach it.
789
- Object.assign(submission, {
790
- prepare: async (sessionId: string): Promise<void> => {
791
- sessionId = referenceOwnerKey(sessionId)
792
- if (http.consume === undefined) return
793
- const state = draftStoreFor(sessionId).state()
794
- const visible = new Set(state.groups.map(group => group.referenceId))
795
- if (visible.size === 0) return
796
- // Reconcile just the cards the user can submit. New incoming captures
797
- // and cursor advancement belong to the regular session poll.
798
- const response = await http.deliveries(sessionId, state.since)
799
- if (response.tracksSubmissions === true) tracksSubmissions.add(sessionId)
800
- else tracksSubmissions.delete(sessionId)
801
- if (response.unverified?.some(id => visible.has(id))) throw new Error('会话正在恢复,请稍后发送网页引用')
802
- for (const delivery of response.deliveries) {
803
- if (delivery.sessionId === sessionId && delivery.state === 'consumed' && visible.has(delivery.referenceId)) {
804
- await processDelivery(delivery, sessionId)
805
- }
806
- }
807
- publish()
808
- },
809
- retrySubmitted: (_sessionId: string, _requestId?: string): void => {
810
- flushPendingArchives()
811
- void flushConsumptions()
812
- },
813
- })
814
-
815
761
  const referenceDetail = (referenceId: string): (StoredReflection & { readonly sessionId: string; readonly card: CardViewModel }) | undefined => {
816
762
  draftStoreFor(current)
817
763
  for (const [sessionId, store] of stores) {
@@ -939,6 +885,9 @@ export function createProductionRuntime(options: ProductionRuntimeOptions): Prod
939
885
  * the delivery queue and removed on the plugin side in one step, so the next
940
886
  * send simply does not see it (there is no window in which it can be undone).
941
887
  */
888
+ const quotesSeen = new Set<string>()
889
+ const attachedImages = new Map<string, readonly string[]>()
890
+
942
891
  const removeReferences = (sessionId: string, ids: readonly string[]): void => {
943
892
  if (ids.length === 0) return
944
893
  const store = draftStoreFor(sessionId)
@@ -965,19 +914,29 @@ export function createProductionRuntime(options: ProductionRuntimeOptions): Prod
965
914
  if (disposed) return
966
915
  const previous = lastDraft
967
916
  lastDraft = draft
968
- // 上游接受消息后会清空草稿:这一刻把本会话的引用全部退役,输入框里的胶囊随之消失。
969
- // 之前没有任何人调用提交缝(上游补丁已删),所以发完消息输入框还留着上一次的胶囊。
970
- if (draft.trim() !== '' || previous.trim() === '') return
971
917
  const store = draftStoreFor(sessionId)
972
918
  const ids = store.state().groups.map(group => group.referenceId)
973
- if (ids.length === 0) return
974
- try {
975
- store.retire(ids)
976
- store.flushPendingArchive()
977
- for (const id of ids) { try { queue.markDeleted(id) } catch { /* 幂等 */ } }
978
- } catch { /* 本地清理失败不该影响已发送的消息 */ }
979
- markDirty()
980
- publish()
919
+ // 上游接受消息后会清空草稿:这一刻把本会话的引用全部退役,输入框里的胶囊随之消失。
920
+ if (draft.trim() === '') {
921
+ if (previous.trim() !== '' && ids.length > 0) void consumeSubmitted(sessionId, ids)
922
+ return
923
+ }
924
+ // The host quote is what gets sent, so it is the single source of truth: once a quote has been
925
+ // seen in the draft, the user deleting it removes its card too.
926
+ const removed: string[] = []
927
+ for (const referenceId of ids) {
928
+ const key = `${sessionId}${referenceId}`
929
+ if (draft.includes(encodeBrowserRefUri({ referenceId }))) quotesSeen.add(key)
930
+ else if (quotesSeen.delete(key)) {
931
+ removed.push(referenceId)
932
+ const images = attachedImages.get(key)
933
+ attachedImages.delete(key)
934
+ if (images !== undefined) {
935
+ try { hostInputFor(sessionId).removeAttachments?.(images) } catch { /* the user can still remove them in the composer */ }
936
+ }
937
+ }
938
+ }
939
+ if (removed.length > 0) removeReferences(sessionId, removed)
981
940
  },
982
941
  setSession(sessionId) {
983
942
  sessionId = referenceOwnerKey(sessionId)
@@ -1058,10 +1017,6 @@ export function createProductionRuntime(options: ProductionRuntimeOptions): Prod
1058
1017
  return availabilityOf(poller.lastError)
1059
1018
  },
1060
1019
  ownerFor,
1061
- submission,
1062
- projectContent({ uploaded, text }) {
1063
- return submission.buildContent({ sessionId: current, uploaded, text })
1064
- },
1065
1020
  setComment(referenceId, comment) {
1066
1021
  if (disposed) return false
1067
1022
  for (const store of stores.values()) {