diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a26e291d..ecbd1c15 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -66,6 +66,11 @@ jobs:
timeout-minutes: 5
run: node scripts/workbench/e2e-sessions.mjs
+ - name: Verify delivery cards, browser downloads and scoped file reveal
+ if: ${{ !cancelled() && steps.host_tests.outcome == 'success' }}
+ timeout-minutes: 5
+ run: node scripts/workbench/e2e-deliveries.mjs
+
- name: Select the same installed Chrome for UI and worker
run: bash scripts/workbench/ci-select-chromium.sh
diff --git a/README.en.md b/README.en.md
index ec4220d8..17f60e8d 100644
--- a/README.en.md
+++ b/README.en.md
@@ -341,7 +341,7 @@ When memory is full, the next write by the model first consolidates the existing
## Headless server workbench (fork development)
-The [amd64 Docker Compose workbench](apps/headless/README.md) supports browser enrollment, the original desktop model settings, and general text conversations with shared desktop UI, streaming, cancellation and reconnect. It also includes profile and role editing, avatar management, and notes scoped to the owner, a role, or a registered project. Manual workspaces and explicit chat attachments are separate: browsing a project does not send its files to a model. The workbench accepts supported UTF-8 text, static images and PDFs for compatible adapters. An [optional human-operated browser](apps/browser-worker/README.md) uses a separate sandboxed worker and an explicit list of sites. The base app requires neither that worker nor a running desktop. This is separate from the mobile relay; see the [parity inventory](docs/development/web-workbench/README.md) for the remaining desktop workflows.
+The [amd64 Docker Compose workbench](apps/headless/README.md) supports browser enrollment, the original desktop model settings, and general text conversations with shared desktop UI, streaming, cancellation and reconnect. It also includes profile and role editing, avatar management, and notes scoped to the owner, a role, or a registered project. Manual workspaces and explicit chat attachments are separate: browsing a project does not send its files to a model. The workbench accepts supported UTF-8 text, static images and PDFs for compatible adapters. Confirmed replies can be exported as Markdown or plain text. Desktop delivery cards are reused for scoped downloads and project file reveal. An [optional human-operated browser](apps/browser-worker/README.md) uses a separate sandboxed worker and an explicit list of sites. The base app requires neither that worker nor a running desktop. This is separate from the mobile relay; see the [parity inventory](docs/development/web-workbench/README.md) for the remaining desktop workflows.
## Build from Source
diff --git a/README.md b/README.md
index 58acf632..0630705f 100644
--- a/README.md
+++ b/README.md
@@ -332,7 +332,7 @@ IM 机器人支持 `/new [角色名]`、`/list`、`/stop`、`/status`、`/help`
## 无 GUI 服务器工作台(本分支开发中)
-[amd64 Docker Compose 与 Web 工作台说明](apps/headless/README.md):当前可在浏览器认领服务器、配置模型,并使用桌面同源的会话列表、编辑器及消息区进行通用文本对话;支持停止与刷新续接。网页还可以编辑个人资料、普通角色及其头像,并分别管理全局、角色和已授权项目的记忆。可手动浏览获准项目的文件,也可显式把所选文本、静态图片或兼容协议的 PDF 作为会话附件发送;浏览项目不会自动上传。还可配置[独立人工浏览器面板](apps/browser-worker/README.md),由当前登录者接管已登记站点;实际工作器须通过 Chromium 沙箱就绪检查。它和手机版中转是两个不同部署目标;完整业务进度见[对等清单](docs/development/web-workbench/README.md)。
+[amd64 Docker Compose 与 Web 工作台说明](apps/headless/README.md):当前可在浏览器认领服务器、配置模型,并使用桌面同源的会话列表、编辑器及消息区进行通用文本对话;支持停止与刷新续接。网页还可以编辑个人资料、普通角色及其头像,并分别管理全局、角色和已授权项目的记忆。可手动浏览获准项目的文件,也可显式把所选文本、静态图片或兼容协议的 PDF 作为会话附件发送;浏览项目不会自动上传。已确认的回复可导出为 Markdown 或纯文本;桌面交付卡复用于 Web,支持按授权项目下载文件和定位。还可配置[独立人工浏览器面板](apps/browser-worker/README.md),由当前登录者接管已登记站点;实际工作器须通过 Chromium 沙箱就绪检查。它和手机版中转是两个不同部署目标;完整业务进度见[对等清单](docs/development/web-workbench/README.md)。
## 从源码构建
diff --git a/apps/desktop/src/renderer/src/features/chat/DeliverablesCard.tsx b/apps/desktop/src/renderer/src/features/chat/DeliverablesCard.tsx
index 283ad7ea..285db9b5 100644
--- a/apps/desktop/src/renderer/src/features/chat/DeliverablesCard.tsx
+++ b/apps/desktop/src/renderer/src/features/chat/DeliverablesCard.tsx
@@ -1,15 +1,5 @@
import { useEffect, useState } from 'react'
-import {
- Check,
- ChevronDown,
- ChevronRight,
- ChevronUp,
- Copy,
- ExternalLink,
- File,
- FolderOpen,
- Package
-} from 'lucide-react'
+import { DeliverablesView, formatDeliverableSize, type DeliverableViewRow } from './DeliverablesView'
import { useI18n } from '../../i18n/i18n'
import { type ChatBlock, useChatState } from '../../store/chat'
import { useToast } from '../../components/ToastProvider'
@@ -24,16 +14,6 @@ import type { DeliverableInfo } from '../../../../shared/deliverables'
// 缩略图按「对话:调用:序号」缓存:滚动 / 重渲染时不反复向系统要图。
const thumbCache = new Map()
-/** 文件多于 FOLD_PREVIEW + 1 个时折叠,只显示前 FOLD_PREVIEW 个(免得出现「展开其余 1 个」)。 */
-const FOLD_PREVIEW = 5
-
-function formatSize(n: number): string {
- if (n < 1024) return `${n} B`
- if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`
- if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`
- return `${(n / 1024 / 1024 / 1024).toFixed(1)} GB`
-}
-
/**
* 主进程信息到达前,先按调用参数画出文件名,避免卡片高度跳动。参数是模型原样发出的(可能是相对路径、
* 可能重复),只取文件名占位;真实路径以 inspect 返回的为准。
@@ -60,9 +40,6 @@ export function DeliverablesCard({
const [loaded, setLoaded] = useState(false)
const [thumbs, setThumbs] = useState>({})
const [copied, setCopied] = useState(null)
- const [expanded, setExpanded] = useState(false)
- // 整张卡收起(点标题):默认展开——交付物就是这一轮的结果;收起状态不保存,重开对话恢复展开。
- const [cardOpen, setCardOpen] = useState(true)
useEffect(() => {
let alive = true
@@ -145,121 +122,42 @@ export function DeliverablesCard({
? 'chat.deliver.revealMac'
: 'chat.deliver.revealOther'
)
- const count = t(files.length === 1 ? 'chat.deliver.countOne' : 'chat.deliver.count').replace(
- '{n}',
- String(files.length)
- )
- const foldable = files.length > FOLD_PREVIEW + 1
- // 从头截取,行序号即文件在交付清单里的序号(IPC 按它取路径)。
- const shown = foldable && !expanded ? files.slice(0, FOLD_PREVIEW) : files
- // 收起时标题带上首个文件名与总数,不展开也知道交付了什么。
- const summary =
- files.length === 0
- ? ''
- : files.length === 1
- ? files[0].name
- : t('chat.deliver.collapsedMany')
- .replace('{name}', files[0].name)
- .replace('{n}', String(files.length))
- .replace('{rest}', String(files.length - 1))
+ // 保留原始序号:打开、定位和复制仍由 Electron 的上下文与 IPC 完成。
+ const rows = files.map((f, i): DeliverableViewRow => {
+ const missing = loaded && f.size === null
+ const available = loaded && !missing
+ const canOpen = available && f.openable
+ const actions: DeliverableViewRow['actions'][number][] = []
+ if (canOpen) actions.push({ id: 'open', label: t('chat.deliver.open'), onClick: () => open(i) })
+ actions.push(
+ { id: 'locate', label: revealLabel, onClick: () => reveal(i), disabled: !available },
+ { id: 'copy', label: t('chat.deliver.copyPath'), onClick: () => copyPath(i, f.path), copied: copied === i }
+ )
+ return {
+ key: f.path,
+ index: i,
+ name: f.name,
+ title: f.path,
+ thumb: thumbs[i],
+ missing,
+ detail: missing ? t('chat.deliver.missing') : loaded ? `${formatDeliverableSize(f.size ?? 0)} · ${dirLabel(f)}` : dirLabel(f),
+ // 点整行:能打开就打开,否则在文件夹中显示(可执行 / 脚本类文件不直接打开)。
+ primary: available ? () => canOpen ? open(i) : reveal(i) : undefined,
+ actions
+ }
+ })
return (
-
-
-
- {shown.map((f, i) => {
- const missing = loaded && f.size === null
- const canOpen = loaded && !missing && f.openable
- const thumb = thumbs[i]
- // 点整行:能打开就打开,否则在文件夹中显示(可执行 / 脚本类文件不直接打开)。
- const primary = (): void => (canOpen ? open(i) : reveal(i))
- return (
-
-
-
- {canOpen && (
-
- )}
-
-
-
-
- )
- })}
-
- {cardOpen && foldable && (
-
- )}
-
+ t(n === 1 ? 'chat.deliver.countOne' : 'chat.deliver.count').replace('{n}', String(n)),
+ collapsed: (name, n) => t('chat.deliver.collapsedMany')
+ .replace('{name}', name).replace('{n}', String(n)).replace('{rest}', String(n - 1)),
+ expand: (remaining) => t('chat.deliver.expand').replace('{n}', String(remaining)),
+ collapse: t('chat.deliver.collapse')
+ }}
+ rows={rows}
+ />
)
}
diff --git a/apps/desktop/src/renderer/src/features/chat/DeliverablesView.tsx b/apps/desktop/src/renderer/src/features/chat/DeliverablesView.tsx
new file mode 100644
index 00000000..cc48ebb6
--- /dev/null
+++ b/apps/desktop/src/renderer/src/features/chat/DeliverablesView.tsx
@@ -0,0 +1,131 @@
+import { useState, type ReactNode } from 'react'
+import {
+ Check,
+ ChevronDown,
+ ChevronRight,
+ ChevronUp,
+ Copy,
+ Download,
+ ExternalLink,
+ Eye,
+ File,
+ FolderOpen,
+ Package
+} from 'lucide-react'
+
+// Leave six-file cards unfolded rather than creating a control for one remaining row.
+const FOLD_PREVIEW = 5
+const ACTION_ICONS = {
+ open: ExternalLink,
+ preview: Eye,
+ download: Download,
+ locate: FolderOpen,
+ copy: Copy
+}
+
+export interface DeliverableViewAction {
+ id: keyof typeof ACTION_ICONS
+ label: string
+ onClick: () => void
+ disabled?: boolean
+ copied?: boolean
+}
+
+export interface DeliverableViewRow {
+ key: string
+ index?: number
+ name: string
+ detail: string
+ title?: string
+ thumb?: string | null
+ missing?: boolean
+ primary?: () => void
+ actions: readonly DeliverableViewAction[]
+}
+
+interface DeliverablesViewProps {
+ title: string
+ labels: {
+ count: (n: number) => string
+ collapsed: (name: string, n: number) => string
+ expand: (remaining: number) => string
+ collapse: string
+ }
+ rows: readonly DeliverableViewRow[]
+ groupId?: string
+ origin?: 'reply' | 'desktop'
+ onCollapse?: () => void
+ children?: ReactNode
+}
+
+export function formatDeliverableSize(n: number): string {
+ if (n < 1024) return `${n} B`
+ if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`
+ if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`
+ return `${(n / 1024 / 1024 / 1024).toFixed(1)} GB`
+}
+
+function DeliverableFileRow({ row }: { row: DeliverableViewRow }): React.JSX.Element {
+ return (
+
+
+
+ {row.actions.map(({ id, label, onClick, disabled, copied }) => {
+ const Icon = copied ? Check : ACTION_ICONS[id]
+ return (
+
+ )
+ })}
+
+
+ )
+}
+
+/** Shared file card; the host supplies display metadata and owns every action. */
+export function DeliverablesView({ title, labels, rows, groupId, origin, onCollapse, children }: DeliverablesViewProps): React.JSX.Element {
+ const [expanded, setExpanded] = useState(false)
+ const [cardOpen, setCardOpen] = useState(true)
+ const foldable = rows.length > FOLD_PREVIEW + 1
+ const shown = foldable && !expanded ? rows.slice(0, FOLD_PREVIEW) : rows
+ const summary = rows.length > 1 ? labels.collapsed(rows[0].name, rows.length) : rows[0]?.name
+
+ return (
+
+
+
+ {shown.map((row) => )}
+ {children}
+
+ {cardOpen && foldable && (
+
+ )}
+
+ )
+}
diff --git a/apps/desktop/src/workbench/deliveries-controller.ts b/apps/desktop/src/workbench/deliveries-controller.ts
new file mode 100644
index 00000000..f53e6fff
--- /dev/null
+++ b/apps/desktop/src/workbench/deliveries-controller.ts
@@ -0,0 +1,245 @@
+import type { ChatState } from './chat-transport'
+import { HttpFailure } from './transport'
+import type { DeliveriesTransport, DeliveryCandidate, DeliveryFormat, DeliveryGroup, DeliveryLocation, DeliveryRef } from './deliveries-transport'
+
+export type DeliveryIssue = 'permission' | 'missing' | 'changed' | 'failure' | 'clipboard' | 'previewFailed' | 'workspaceMissing' |
+ 'tooLarge' | 'unsupported' | 'busy' | 'notExportable'
+type Feedback = { issue: DeliveryIssue } | { success: 'created' | 'existing' | 'download' | 'copied' }
+type ItemAction = 'download' | 'preview' | 'locate' | 'copy'
+type Action = { type: 'export'; turnId: string; format: DeliveryFormat } | { type: ItemAction; gid: string; index: number }
+export type DeliveryPreview = DeliveryRef & { name: string; url: string }
+export interface DeliveriesState {
+ sid?: string
+ authority?: string
+ groups: DeliveryGroup[]
+ candidates: DeliveryCandidate[]
+ nextCursor: string | null
+ loading?: 'first' | 'more'
+ issue?: DeliveryIssue
+ feedback?: Feedback
+ pending?: Action
+ preview?: DeliveryPreview
+}
+interface Options {
+ beforeWrite: () => Promise
+ expired: () => void
+ objectUrl: (blob: Blob) => string
+ revokeUrl: (url: string) => void
+ deferRelease: (release: () => void) => () => void
+ saveDownload: (url: string, name: string) => void
+ copyName: (name: string) => Promise
+ openWorkspace?: (where: DeliveryLocation, signal: AbortSignal) => Promise
+}
+interface ListJob { scope: string; authority: string; abort: AbortController }
+interface ActionJob { scope: string; abort: AbortController; ref?: DeliveryRef; authority?: string }
+
+const empty = (sid?: string): DeliveriesState => ({ sid, groups: [], candidates: [], nextCursor: null })
+export const emptyDeliveries = empty()
+
+/** The collection associates a server turn ID with a message; a transcript row alone grants nothing. */
+export function eligibleDeliveryReplies(state: Pick | undefined,
+ pending: boolean, authority: string | undefined, deliveries: DeliveriesState): ReadonlyMap {
+ const eligible = new Map()
+ if (!authority || authority !== deliveries.authority || deliveries.loading === 'first' || deliveries.issue === 'permission' ||
+ state?.compatibility !== 'text' || state.active || pending) return eligible
+ for (const candidate of deliveries.candidates) {
+ const { messageIndex, turnId } = candidate
+ const message = state.messages?.[messageIndex]
+ const last = state.lastTurn
+ if (message?.role === 'assistant' && message.content.trim() &&
+ (last?.turnId !== turnId || (last.status === 'completed' && last.reason === null))) eligible.set(messageIndex, candidate)
+ }
+ return eligible
+}
+
+function issue(error: unknown): DeliveryIssue {
+ if (!(error instanceof HttpFailure)) return 'failure'
+ if (error.status === 401 || error.status === 403) return 'permission'
+ if (error.code === 'reply_not_exportable') return 'notExportable'
+ if (error.code === 'turn_in_progress' || error.status === 429) return 'busy'
+ if (error.code === 'delivery_no_location') return 'workspaceMissing'
+ if (error.status === 404 || error.status === 410) return 'missing'
+ if (error.status === 413) return 'tooLarge'
+ if (error.status === 415) return 'unsupported'
+ if ([409, 412, 428].includes(error.status)) return 'changed'
+ return 'failure'
+}
+function mergeGroups(prior: DeliveryGroup[], next: DeliveryGroup[]): DeliveryGroup[] {
+ const map = new Map(prior.map((group) => [group.id, group]))
+ for (const group of next) map.set(group.id, group)
+ return [...map.values()]
+}
+
+/** One active session; every async publication and browser side effect requires the current job identity. */
+export function createDeliveriesController(api: DeliveriesTransport, options: Options) {
+ const listeners = new Set<() => void>()
+ const downloads = new Map void>()
+ let view = emptyDeliveries
+ let listJob: ListJob | undefined
+ let actionJob: ActionJob | undefined
+
+ function publish(next: DeliveriesState): void {
+ view = next
+ listeners.forEach((listener) => listener())
+ }
+ function patch(update: Partial): void { publish({ ...view, ...update }) }
+ const item = (gid: string, index: number) => view.groups.find((group) => group.id === gid)?.items.find((entry) => entry.index === index)
+ function releaseDownload(url: string): void {
+ const cancel = downloads.get(url)
+ downloads.delete(url)
+ cancel?.()
+ options.revokeUrl(url)
+ }
+ function closePreview(failed = false, expectedUrl?: string): void {
+ if (!view.preview || (expectedUrl !== undefined && view.preview.url !== expectedUrl)) return
+ options.revokeUrl(view.preview.url)
+ patch({ preview: undefined, ...(failed ? { feedback: { issue: 'previewFailed' } as const } : {}) })
+ }
+ function cancelList(): void { listJob?.abort.abort(); listJob = undefined }
+ function cancelAction(): void { actionJob?.abort.abort(); actionJob = undefined }
+ function reset(sid?: string): void {
+ cancelList()
+ cancelAction()
+ if (view.preview) options.revokeUrl(view.preview.url)
+ for (const url of downloads.keys()) releaseDownload(url)
+ publish(empty(sid))
+ }
+ function select(sid?: string): void { if (view.sid !== sid) reset(sid) }
+ function lostAuthorization(error: unknown): boolean {
+ if (!(error instanceof HttpFailure) || (error.status !== 401 && error.status !== 403)) return false
+ reset(view.sid)
+ patch({ issue: 'permission' })
+ if (error.status === 401 || error.code === 'csrf_failed') options.expired()
+ return true
+ }
+
+ async function read(authority: string, more = false, afterCursorReset = false): Promise {
+ const scope = view.sid
+ const cursor = more ? view.nextCursor : undefined
+ if (!scope || (more && (!cursor || listJob || view.authority !== authority))) return
+ cancelList()
+ const staleExport = actionJob?.authority !== undefined && actionJob.authority !== authority
+ if (staleExport) cancelAction()
+ const job = { scope, authority, abort: new AbortController() }
+ listJob = job
+ patch({ loading: more ? 'more' : 'first', issue: afterCursorReset ? 'changed' : undefined,
+ ...(staleExport ? { pending: undefined, feedback: { issue: 'notExportable' } as const } : {}) })
+ const current = (): boolean => listJob === job && view.sid === scope && !job.abort.signal.aborted
+ try {
+ const page = await api.list(scope, cursor ?? undefined, job.abort.signal)
+ if (!current()) return
+ if (cursor && page.nextCursor === cursor) throw new Error('Repeated delivery cursor')
+ const groups = more ? mergeGroups(view.groups, page.groups) : page.groups
+ const same = (ref: DeliveryRef): boolean => groups.find((group) => group.id === ref.gid)?.items
+ .some((entry) => entry.index === ref.index && entry.revision === ref.revision) === true
+ const preview = view.preview
+ if (preview && !same(preview)) options.revokeUrl(preview.url)
+ const staleAction = actionJob?.ref && !same(actionJob.ref)
+ if (staleAction) cancelAction()
+ patch({ authority, groups, candidates: page.candidates, nextCursor: page.nextCursor, loading: undefined,
+ preview: preview && same(preview) ? preview : undefined,
+ ...(staleAction ? { pending: undefined, feedback: { issue: 'changed' } as const } : {}) })
+ } catch (error) {
+ if (!current() || lostAuthorization(error)) return
+ if (cursor && error instanceof HttpFailure && error.status === 409) {
+ listJob = undefined
+ await read(authority, false, true)
+ return
+ }
+ const status = issue(error)
+ if (status === 'missing' && !more) reset(scope)
+ patch({ loading: undefined, issue: status, ...(!more ? { authority: undefined, candidates: [], nextCursor: null } : {}) })
+ } finally {
+ if (listJob === job) listJob = undefined
+ }
+ }
+
+ function begin(pending: Action, ref?: DeliveryRef, authority?: string): ActionJob | undefined {
+ if (!view.sid || actionJob || view.issue === 'permission') return
+ const job: ActionJob = { scope: view.sid, abort: new AbortController(), ref, authority }
+ actionJob = job
+ patch({ pending, feedback: undefined })
+ return job
+ }
+ function active(job: ActionJob): boolean {
+ return actionJob === job && view.sid === job.scope && !job.abort.signal.aborted &&
+ (!job.ref || item(job.ref.gid, job.ref.index)?.revision === job.ref.revision)
+ }
+ function finish(job: ActionJob): void {
+ if (actionJob !== job) return
+ actionJob = undefined
+ patch({ pending: undefined })
+ }
+ function report(job: ActionJob, error: unknown, fallback?: DeliveryIssue): void {
+ if (!active(job) || lostAuthorization(error)) return
+ patch({ feedback: { issue: error instanceof HttpFailure ? issue(error) : fallback ?? 'failure' } })
+ }
+
+ async function exportReply(candidate: DeliveryCandidate, format: DeliveryFormat, authority: string): Promise {
+ if (!view.sid || actionJob || view.issue === 'permission') return
+ if (view.authority !== authority || view.loading === 'first' || !view.candidates.some((entry) =>
+ entry.turnId === candidate.turnId && entry.messageIndex === candidate.messageIndex)) {
+ patch({ feedback: { issue: 'notExportable' } })
+ return
+ }
+ const job = begin({ type: 'export', turnId: candidate.turnId, format }, undefined, authority)
+ if (!job) return
+ try {
+ await options.beforeWrite()
+ if (!active(job) || view.authority !== authority || (listJob && listJob.authority !== authority)) return
+ const { created, group } = await api.exportReply(job.scope, candidate.turnId, format, job.abort.signal)
+ if (!active(job)) return
+ if (group.messageIndex !== candidate.messageIndex) throw new Error('Mismatched delivery message')
+ cancelList()
+ patch({ groups: mergeGroups(view.groups, [group]), loading: undefined, feedback: { success: created ? 'created' : 'existing' } })
+ } catch (error) { report(job, error) } finally { finish(job) }
+ }
+
+ async function runItem(type: ItemAction, gid: string, index: number): Promise {
+ if (!view.sid || actionJob || view.issue === 'permission') return
+ const entry = item(gid, index)
+ if (!entry) { patch({ feedback: { issue: 'missing' } }); return }
+ const ref = entry.revision ? { gid, index, revision: entry.revision } : undefined
+ if (type === 'download' && (!ref || !entry.canDownload || entry.size === null) ||
+ type === 'preview' && (!ref || !entry.canPreview || entry.size === null) ||
+ type === 'locate' && (!ref || !entry.canLocate || !options.openWorkspace)) return
+ // Only an explicit click starts a new preview. This also releases any previously shown image.
+ if (type === 'preview') closePreview()
+ const job = begin({ type, gid, index }, ref)
+ if (!job) return
+ const signal = job.abort.signal
+ try {
+ if (type === 'copy') {
+ await options.copyName(entry.name)
+ if (active(job)) patch({ feedback: { success: 'copied' } })
+ } else if (type === 'locate') {
+ const location = await api.locate(job.scope, ref!, signal)
+ if (!active(job)) return
+ const opened = await options.openWorkspace!(location, signal)
+ if (active(job) && !opened) patch({ feedback: { issue: 'workspaceMissing' } })
+ } else {
+ const binary = await api[type](job.scope, ref!, entry.size!, signal)
+ if (!active(job)) return
+ const url = options.objectUrl(binary)
+ if (type === 'preview') {
+ patch({ preview: { ...ref!, name: entry.name, url } })
+ } else {
+ try {
+ options.saveDownload(url, entry.name)
+ downloads.set(url, options.deferRelease(() => releaseDownload(url)))
+ patch({ feedback: { success: 'download' } })
+ } catch (error) { options.revokeUrl(url); throw error }
+ }
+ }
+ } catch (error) { report(job, error, type === 'copy' ? 'clipboard' : type === 'preview' ? 'previewFailed' : undefined) }
+ finally { finish(job) }
+ }
+
+ return {
+ snapshot: () => view,
+ subscribe(listener: () => void): () => void { listeners.add(listener); return () => { listeners.delete(listener) } },
+ select, read, exportReply, runItem, closePreview,
+ dismiss() { patch({ feedback: undefined }) }
+ }
+}
+export type DeliveriesController = ReturnType
diff --git a/apps/desktop/src/workbench/deliveries-transport.ts b/apps/desktop/src/workbench/deliveries-transport.ts
new file mode 100644
index 00000000..316bd7b3
--- /dev/null
+++ b/apps/desktop/src/workbench/deliveries-transport.ts
@@ -0,0 +1,183 @@
+import type { Transport } from './transport'
+
+export type DeliveryFormat = 'md' | 'txt'
+export interface DeliveryItem {
+ index: number
+ name: string
+ size: number | null
+ kind: 'text' | 'image' | 'document'
+ status: 'ready' | 'missing' | 'too-large' | 'unsupported'
+ revision: string | null
+ canDownload: boolean
+ canPreview: boolean
+ canLocate: boolean
+}
+export interface DeliveryGroup {
+ id: string
+ origin: 'reply' | 'desktop'
+ turnId?: string
+ messageIndex?: number
+ items: DeliveryItem[]
+}
+export interface DeliveryCandidate { turnId: string; messageIndex: number }
+export interface DeliveryPage { groups: DeliveryGroup[]; candidates: DeliveryCandidate[]; nextCursor: string | null }
+export interface DeliveryLocation { workspaceId: string; path: string }
+export interface DeliveryRef { gid: string; index: number; revision: string }
+
+type Json = Record
+const sidPattern = /^[A-Za-z0-9_-]{1,128}$/u
+const groupPattern = /^d_[0-9a-f]{32}$/u
+const revisionPattern = /^[0-9a-f]{64}$/u
+const cursorPattern = /^[A-Za-z0-9_-]{1,160}$/u
+const workspacePattern = /^w_[0-9a-f]{32}$/u
+const MAX_BINARY_BYTES = 8 * 1024 * 1024
+const attachment = /^attachment(?:\s*;|\s*$)/iu
+const inline = /^inline(?:\s*;|\s*$)/iu
+const rasterTypes = new Set(['image/png', 'image/jpeg', 'image/webp'])
+const controls = /[\u0000-\u001f\u007f-\u009f]/u
+
+function invalid(): never { throw new Error('Invalid delivery request or response') }
+function object(value: unknown): Json {
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Json : invalid()
+}
+function match(value: unknown, pattern: RegExp): value is string {
+ return typeof value === 'string' && pattern.exec(value)?.[0] === value
+}
+function indexOf(value: unknown): value is number {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
+}
+function safeName(name: unknown): name is string {
+ return typeof name === 'string' && name.length > 0 && new TextEncoder().encode(name).length <= 255 &&
+ name.trim() === name && !name.startsWith('.') && !name.endsWith('.') &&
+ !/[\\/:<>"|?*\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u.test(name) &&
+ !/^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(?:\s*\.|$)/iu.test(name)
+}
+function isProjectPath(path: unknown): path is string {
+ return typeof path === 'string' && !controls.test(path) && !path.includes('\\') &&
+ path.split('/').every((segment) => segment && !segment.startsWith('.') && !/^[A-Za-z]:/u.test(segment))
+}
+function candidateOf(value: unknown): DeliveryCandidate {
+ const { turnId, messageIndex } = object(value)
+ if (!match(turnId, sidPattern) || !indexOf(messageIndex)) return invalid()
+ return { turnId, messageIndex }
+}
+function deliveryItem(value: unknown): DeliveryItem {
+ const { index, name, size, kind, status, revision, canDownload, canPreview, canLocate } = object(value)
+ if (!indexOf(index) || index > 19 || !safeName(name) || (size !== null && !indexOf(size)) ||
+ (kind !== 'text' && kind !== 'image' && kind !== 'document') ||
+ (status !== 'ready' && status !== 'missing' && status !== 'too-large' && status !== 'unsupported') ||
+ (revision !== null && !match(revision, revisionPattern)) ||
+ typeof canDownload !== 'boolean' || typeof canPreview !== 'boolean' || typeof canLocate !== 'boolean' ||
+ (status === 'ready' ? revision === null || size === null || size > MAX_BINARY_BYTES : revision !== null || canDownload || canPreview || canLocate) ||
+ (canPreview && kind !== 'image')) return invalid()
+ return { index, name, size, kind, status, revision, canDownload, canPreview, canLocate }
+}
+function deliveryGroup(value: unknown): DeliveryGroup {
+ const { id, origin, turnId, messageIndex, items } = object(value)
+ if (!match(id, groupPattern) || (origin !== 'reply' && origin !== 'desktop') || !Array.isArray(items) ||
+ (turnId !== undefined && !match(turnId, sidPattern)) || (messageIndex !== undefined && !indexOf(messageIndex))) return invalid()
+ const files = items.map(deliveryItem)
+ if (new Set(files.map((item) => item.index)).size !== files.length) return invalid()
+ return { id, origin, ...(turnId === undefined ? {} : { turnId }), ...(messageIndex === undefined ? {} : { messageIndex }), items: files }
+}
+function deliveryPage(value: unknown): DeliveryPage {
+ const { groups, candidates, nextCursor } = object(value)
+ if (!Array.isArray(groups) || (candidates !== undefined && !Array.isArray(candidates)) ||
+ (nextCursor !== undefined && nextCursor !== null && !match(nextCursor, cursorPattern))) return invalid()
+ const deliveries = groups.map(deliveryGroup)
+ const replies = (candidates ?? []).map(candidateOf)
+ if (new Set(deliveries.map((group) => group.id)).size !== deliveries.length ||
+ new Set(replies.map((candidate) => candidate.turnId)).size !== replies.length ||
+ new Set(replies.map((candidate) => candidate.messageIndex)).size !== replies.length) return invalid()
+ return { groups: deliveries, candidates: replies, nextCursor: nextCursor ?? null }
+}
+function base(sid: string): string {
+ if (!match(sid, sidPattern)) return invalid()
+ return `/chats/${sid}/deliveries`
+}
+function itemPath(sid: string, ref: DeliveryRef, action: 'download' | 'preview' | 'locate'): string {
+ if (!match(ref.gid, groupPattern) || !indexOf(ref.index) || ref.index > 19 || !match(ref.revision, revisionPattern)) return invalid()
+ return `${base(sid)}/${ref.gid}/items/${ref.index}/${action}`
+}
+
+async function verifyRaster(blob: Blob): Promise {
+ const header = new DataView(await blob.slice(0, 24).arrayBuffer())
+ const size = header.byteLength
+ const u32 = (n: number) => header.getUint32(n)
+ const valid = blob.type === 'image/png'
+ ? size >= 24 && u32(0) === 0x89504e47 && u32(4) === 0x0d0a1a0a && u32(8) === 13 && u32(12) === 0x49484452 && u32(16) > 0 && u32(20) > 0
+ : blob.type === 'image/jpeg'
+ ? size >= 4 && header.getUint16(0) === 0xffd8 && header.getUint8(2) === 0xff && header.getUint8(3) !== 0
+ : size >= 16 && u32(0) === 0x52494646 && u32(8) === 0x57454250 && header.getUint32(4, true) + 8 === blob.size &&
+ [0x56503820, 0x5650384c, 0x56503858].includes(u32(12))
+ if (!valid) return invalid()
+}
+
+/** Streams only the authorized number of bytes, then labels downloads inert even if their extension is executable. */
+async function binaryOf(response: Response, type: 'download' | 'preview', revision: string, expected: number): Promise {
+ const mime = response.headers.get('content-type')?.trim().toLowerCase() ?? ''
+ const length = response.headers.get('content-length')
+ const etag = response.headers.get('etag')
+ const disposition = response.headers.get('content-disposition') ?? ''
+ if (!response.body || response.status !== 200 || etag !== `"${revision}"` ||
+ length === null || !/^\d+$/u.test(length) || Number(length) !== expected ||
+ (type === 'download' ? !attachment.test(disposition) : !inline.test(disposition) || !rasterTypes.has(mime))) {
+ void response.body?.cancel().catch(() => {})
+ return invalid()
+ }
+ const reader = response.body.getReader()
+ const chunks: ArrayBuffer[] = []
+ let seen = 0
+ try {
+ for (;;) {
+ const { value, done } = await reader.read()
+ if (done) break
+ seen += value.byteLength
+ if (seen > expected) { void reader.cancel().catch(() => {}); return invalid() }
+ chunks.push(new Uint8Array(value).buffer)
+ }
+ } finally { reader.releaseLock() }
+ if (seen !== expected) return invalid()
+ const blob = new Blob(chunks, { type: type === 'download' ? 'application/octet-stream' : mime })
+ if (type === 'preview') await verifyRaster(blob)
+ return blob
+}
+
+export function createDeliveriesTransport(transport: Transport, csrf: string) {
+ const accept = 'application/json'
+ async function bytes(sid: string, ref: DeliveryRef, expected: number, signal: AbortSignal, type: 'download' | 'preview'): Promise {
+ if (!indexOf(expected) || expected > MAX_BINARY_BYTES) return invalid()
+ const response = await transport.deliveryRequest(itemPath(sid, ref, type), signal, {
+ accept: type === 'download' ? 'application/octet-stream' : 'image/png, image/jpeg, image/webp', ifMatch: `"${ref.revision}"`
+ })
+ return binaryOf(response, type, ref.revision, expected)
+ }
+ return {
+ async list(sid: string, cursor: string | undefined, signal: AbortSignal): Promise {
+ if (cursor !== undefined && !match(cursor, cursorPattern)) return invalid()
+ const path = base(sid) + (cursor === undefined ? '' : `?cursor=${cursor}`)
+ return deliveryPage(await (await transport.deliveryRequest(path, signal, { accept })).json())
+ },
+ async exportReply(sid: string, turnId: string, format: DeliveryFormat, signal: AbortSignal) {
+ if (!match(turnId, sidPattern) || (format !== 'md' && format !== 'txt')) return invalid()
+ const response = await transport.deliveryRequest(`${base(sid)}/reply`, signal, { accept, post: { csrf, body: { turnId, format } } })
+ const { created, group } = object(await response.json())
+ const parsed = deliveryGroup(group)
+ const [file] = parsed.items
+ if (typeof created !== 'boolean' || response.status !== (created ? 201 : 200) || parsed.origin !== 'reply' ||
+ parsed.turnId !== turnId || parsed.messageIndex === undefined || parsed.items.length !== 1 || file.index !== 0 ||
+ file.kind !== 'text' || !file.canDownload || file.canPreview || file.canLocate || !file.name.endsWith(`.${format}`)) return invalid()
+ return { created, group: parsed }
+ },
+ download: (sid: string, ref: DeliveryRef, expected: number, signal: AbortSignal) => bytes(sid, ref, expected, signal, 'download'),
+ preview: (sid: string, ref: DeliveryRef, expected: number, signal: AbortSignal) => bytes(sid, ref, expected, signal, 'preview'),
+ async locate(sid: string, ref: DeliveryRef, signal: AbortSignal): Promise {
+ const response = await transport.deliveryRequest(itemPath(sid, ref, 'locate'), signal, { accept, post: { csrf, body: { revision: ref.revision } } })
+ const { workspaceId, path } = object(await response.json())
+ if (!match(workspaceId, workspacePattern) || !isProjectPath(path)) return invalid()
+ return { workspaceId, path }
+ }
+ }
+}
+
+export type DeliveriesTransport = ReturnType
diff --git a/apps/desktop/src/workbench/deliveries-ui.tsx b/apps/desktop/src/workbench/deliveries-ui.tsx
new file mode 100644
index 00000000..552e0e7e
--- /dev/null
+++ b/apps/desktop/src/workbench/deliveries-ui.tsx
@@ -0,0 +1,166 @@
+import { useLayoutEffect, useMemo, useSyncExternalStore } from 'react'
+import { DeliverablesView, formatDeliverableSize, type DeliverableViewRow } from '../renderer/src/features/chat/DeliverablesView'
+import { createDeliveriesController, emptyDeliveries, type DeliveriesController, type DeliveriesState } from './deliveries-controller'
+import type { DeliveriesTransport, DeliveryCandidate, DeliveryGroup, DeliveryLocation } from './deliveries-transport'
+import './deliveries.css'
+
+const copy = {
+ 'zh-CN': {
+ title: '对话交付记录', desktop: '桌面交付历史', reply: '用户导出的回复',
+ loading: '正在读取交付记录…', pending: '正在处理交付操作…', more: '更多交付记录', retry: '刷新交付记录',
+ md: '导出 Markdown', txt: '导出纯文本', format: '导出回复', empty: '这条记录没有可展示的文件。',
+ downloadLabel: '下载文件', preview: '预览图片', closePreview: '关闭预览', workspace: '在工作区文件面板中定位',
+ source: '定位到交付卡与原回复', card: '定位到交付卡', copy: '复制文件名', close: '关闭提示',
+ ready: '可用', missing: '交付记录或文件已不存在。', nonDownloadable: '此文件未开放下载。', missingFile: '文件已不存在',
+ tooLarge: '交付文件或记录超过大小上限。', tooLargeFile: '超过大小上限',
+ unsupported: '此文件或操作当前未开放。', unsupportedFile: '暂未支持该类型',
+ permission: '当前登录无权访问这些交付记录。', changed: '交付记录已变化。请刷新后按新记录重试。',
+ cursorChanged: '原有分页已失效,已从第一页重新加载。',
+ failure: '交付操作失败,未确认结果。', clipboard: '复制失败,文件名未写入剪贴板。',
+ previewFailed: '图片预览失败。', workspaceMissing: '工作区中未找到文件,交付记录仍保留。',
+ busy: '对话或交付服务正忙,请稍后重试。', notExportable: '此回复的导出资格已失效。',
+ created: '回复已导出。', existing: '这份回复已导出,显示现有文件。', download: '已发起浏览器下载。', copied: '已复制文件名。'
+ },
+ en: {
+ title: 'Conversation deliveries', desktop: 'Desktop delivery history', reply: 'Reply exported by you',
+ loading: 'Loading deliveries…', pending: 'Working on the delivery…', more: 'More deliveries', retry: 'Refresh deliveries',
+ md: 'Export Markdown', txt: 'Export plain text', format: 'Export reply', empty: 'This delivery has no files to display.',
+ downloadLabel: 'Download file', preview: 'Preview image', closePreview: 'Close preview', workspace: 'Locate in workspace files',
+ source: 'Find the delivery and original reply', card: 'Find the delivery card', copy: 'Copy file name', close: 'Dismiss notice',
+ ready: 'Available', missing: 'The delivery or file no longer exists.', nonDownloadable: 'Download is unavailable for this file.', missingFile: 'File missing',
+ tooLarge: 'This delivery file or record exceeds the size limit.', tooLargeFile: 'Exceeds the size limit',
+ unsupported: 'This file or action is unavailable.', unsupportedFile: 'Unsupported file type',
+ permission: 'This sign-in has no permission to access these deliveries.', changed: 'The delivery has changed. Refresh the list before retrying.',
+ cursorChanged: 'These results changed. The first page was loaded again.',
+ failure: 'The delivery operation failed and the result is unconfirmed.', clipboard: 'Copy failed. The file name was not added to your clipboard.',
+ previewFailed: 'The image preview failed.', workspaceMissing: 'The file was not found in workspace files. The delivery record is still available.',
+ busy: 'The conversation or delivery service is busy. Try again shortly.', notExportable: 'This reply is no longer eligible for export.',
+ created: 'Reply exported.', existing: 'Showing the existing export for this reply.', download: 'Browser download started.', copied: 'File name copied.'
+ }
+}
+
+type Copy = (typeof copy)['en']
+const localCopy = (locale: string): Copy => copy[locale === 'zh-CN' ? 'zh-CN' : 'en']
+const noSubscribe = () => () => {}
+const emptySnapshot = () => emptyDeliveries
+
+export function useDeliveries(api: DeliveriesTransport | undefined, sid: string, open: boolean, authority: string | undefined, options: {
+ beforeWrite: () => Promise
+ expired: () => void
+ openWorkspace?: (location: DeliveryLocation, signal: AbortSignal) => Promise
+}): { controller?: DeliveriesController; view: DeliveriesState } {
+ const { beforeWrite, expired, openWorkspace } = options
+ const controller = useMemo(() => api && createDeliveriesController(api, {
+ beforeWrite, expired, openWorkspace,
+ objectUrl: (blob) => URL.createObjectURL(blob),
+ revokeUrl: (url) => URL.revokeObjectURL(url),
+ deferRelease: (fn) => { const timer = window.setTimeout(fn, 2_000); return () => window.clearTimeout(timer) },
+ saveDownload: (url, name) => {
+ const link = document.createElement('a')
+ link.href = url
+ link.download = name
+ document.body.append(link)
+ try { link.click() } finally { link.remove() }
+ },
+ copyName: (name) => navigator.clipboard.writeText(name)
+ }), [api, beforeWrite, expired, openWorkspace])
+ const view = useSyncExternalStore(controller?.subscribe ?? noSubscribe, controller?.snapshot ?? emptySnapshot)
+ useLayoutEffect(() => {
+ controller?.select(open ? sid : undefined)
+ return () => controller?.select(undefined)
+ }, [controller, sid, open])
+ useLayoutEffect(() => { if (open && authority !== undefined) void controller?.read(authority) }, [controller, sid, open, authority])
+ return open && view.sid === sid ? { view, controller } : { view: emptyDeliveries }
+}
+
+export function ReplyDeliveryActions({ candidate, authority, state, controller, locale }: {
+ candidate: DeliveryCandidate; authority: string; state: DeliveriesState; controller: DeliveriesController; locale: string
+}): React.JSX.Element {
+ const t = localCopy(locale)
+ return
+
+
+
+}
+
+export function BrowserDeliveryCard({ group, state, controller, locale, workspace, source, reveal }: {
+ group: DeliveryGroup; state: DeliveriesState; controller: DeliveriesController; locale: string
+ workspace: boolean; source: boolean; reveal: () => void
+}): React.JSX.Element {
+ const t = localCopy(locale)
+ const zh = locale === 'zh-CN'
+ const run = (action: 'download' | 'preview' | 'locate' | 'copy', index: number) => () => void controller.runItem(action, group.id, index)
+ const preview = state.preview?.gid === group.id ? state.preview : undefined
+ const rows = group.items.map((item): DeliverableViewRow => {
+ const detail = item.status === 'ready' ? item.canDownload ? t.ready : t.nonDownloadable :
+ item.status === 'missing' ? t.missingFile : item.status === 'too-large' ? t.tooLargeFile : t.unsupportedFile
+ const download = item.canDownload ? run('download', item.index) : undefined
+ const inspect = item.canPreview ? run('preview', item.index) : undefined
+ const locate = group.origin === 'desktop' && workspace && item.canLocate
+ const canAct = !state.pending
+ return {
+ index: item.index, key: String(item.index), name: item.name, title: item.name,
+ detail: item.size === null ? detail : `${formatDeliverableSize(item.size)} · ${detail}`,
+ missing: item.status === 'missing', primary: canAct ? inspect ?? download : undefined,
+ actions: [
+ ...(download ? [{ id: 'download' as const, label: t.downloadLabel, onClick: download, disabled: !canAct }] : []),
+ ...(inspect ? [{ id: 'preview' as const, label: t.preview, onClick: inspect, disabled: !canAct }] : []),
+ { id: 'locate', label: locate ? t.workspace : source ? t.source : t.card,
+ onClick: locate ? run('locate', item.index) : reveal, disabled: !!locate && !canAct },
+ { id: 'copy', label: t.copy, onClick: run('copy', item.index), disabled: !canAct }
+ ]
+ }
+ })
+ return zh ? `${n} 个文件` : `${n} ${n === 1 ? 'file' : 'files'}`,
+ collapsed: (name, n) => zh ? `${name} 等 ${n} 个文件` : `${name} + ${n - 1} more`,
+ expand: (n) => zh ? `展开其余 ${n} 个文件` : `Show ${n} more files`, collapse: zh ? '收起其余文件' : 'Show fewer files'
+ }} onCollapse={preview ? () => controller.closePreview() : undefined}>
+ {!rows.length && {t.empty}
}
+ {preview &&
+ {preview.name}
+
controller.closePreview(true, preview.url)} />
+ }
+
+}
+
+export function DeliveryHistory({ groups, state, authority, controller, locale, workspace, hasSource, reveal }: {
+ groups: DeliveryGroup[]; state: DeliveriesState; authority?: string; controller: DeliveriesController; locale: string; workspace: boolean
+ hasSource: (group: DeliveryGroup) => boolean; reveal: (group: DeliveryGroup) => void
+}): React.JSX.Element | null {
+ const t = localCopy(locale)
+ if (!groups.length && !state.loading && !state.issue && !state.nextCursor) return null
+ const didReset = state.issue === 'changed' && !!state.authority
+ return
+ {t.title}
+ {state.loading && {t.loading}
}
+ {state.issue &&
+ {didReset && !state.loading ? t.cursorChanged : t[state.issue]}{' '}
+ {authority && state.issue !== 'permission' && }
+
}
+ {groups.map((group) => reveal(group)} />)}
+ {!!state.nextCursor && authority && }
+
+}
+
+export function DeliveryFeedback({ state, authority, controller, locale }: {
+ state: DeliveriesState; authority?: string; controller: DeliveriesController; locale: string
+}): React.JSX.Element | null {
+ const t = localCopy(locale)
+ if (state.pending) return {t.pending}
+ const feedback = state.feedback
+ if (!feedback) return null
+ return
+ {'issue' in feedback ? t[feedback.issue] : t[feedback.success]}
+ {'issue' in feedback && authority && (feedback.issue === 'changed' || feedback.issue === 'missing' || feedback.issue === 'notExportable') &&
+ }
+
+
+}
diff --git a/apps/desktop/src/workbench/deliveries.css b/apps/desktop/src/workbench/deliveries.css
new file mode 100644
index 00000000..0eda5d1c
--- /dev/null
+++ b/apps/desktop/src/workbench/deliveries.css
@@ -0,0 +1,65 @@
+.wb-deliveries__message {
+ min-width: 0;
+}
+.wb-deliveries__reply {
+ display: grid;
+ gap: var(--space-2);
+ margin: var(--space-2) 0 0 calc(32px + var(--space-3));
+}
+.wb-deliveries__formats,
+.wb-deliveries__feedback,
+.wb-deliveries__preview figcaption {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+}
+.wb-deliveries__history {
+ display: grid;
+ gap: var(--space-2);
+}
+.wb-deliveries__history h2,
+.wb-deliveries__history p {
+ margin: 0;
+ color: var(--fg-muted);
+ font-size: 13px;
+}
+.wb-deliveries__history > button {
+ justify-self: start;
+}
+.wb-deliveries__empty,
+.wb-deliveries__preview {
+ margin: 0;
+ padding: var(--space-3);
+}
+.wb-deliveries__preview {
+ border-top: 1px solid var(--border);
+}
+.wb-deliveries__preview figcaption {
+ justify-content: space-between;
+ margin-bottom: var(--space-2);
+ overflow-wrap: anywhere;
+ color: var(--fg-muted);
+ font-size: 12px;
+}
+.wb-deliveries__preview img {
+ display: block;
+ max-width: 100%;
+ max-height: min(60vh, 32rem);
+ object-fit: contain;
+ margin: 0 auto;
+}
+.wb-deliveries__feedback {
+ margin: 0 auto;
+ width: min(100%, var(--cf-main));
+ padding: var(--space-2) var(--space-5);
+ font-size: 12px;
+ color: var(--fg-muted);
+}
+.wb-deliveries__feedback[role='alert'],
+.wb-deliveries__history [role='alert'] {
+ color: var(--danger, var(--fg));
+}
+@media (max-width: 520px) {
+ .wb-deliveries__reply { margin-left: 0; }
+}
diff --git a/apps/desktop/src/workbench/text-workbench.tsx b/apps/desktop/src/workbench/text-workbench.tsx
index 9125cdf8..cab0e9b0 100644
--- a/apps/desktop/src/workbench/text-workbench.tsx
+++ b/apps/desktop/src/workbench/text-workbench.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'
import { Archive, ArrowLeft, Globe, Plus, Search } from 'lucide-react'
import { useI18n } from '../renderer/src/i18n/i18n'
import { findActive, useModels } from '../renderer/src/store/models'
@@ -17,6 +17,9 @@ import { ManualBrowserDialog } from './browser-panel'
import { createBrowserTransport, type BrowserTransport } from './browser-transport'
import { chatCopy, turnLabel, type ChatCopy } from './chat-copy'
import { createChatTransport, inputBytes, MAX_TEXT_INPUT, type ChatState } from './chat-transport'
+import { eligibleDeliveryReplies } from './deliveries-controller'
+import { createDeliveriesTransport, type DeliveriesTransport, type DeliveryGroup, type DeliveryLocation } from './deliveries-transport'
+import { BrowserDeliveryCard, DeliveryFeedback, DeliveryHistory, ReplyDeliveryActions, useDeliveries } from './deliveries-ui'
import { createLibrary, type Roster } from './library-transport'
import { LibraryWorkspace, type LibraryPanel } from './library-workspace'
import { createPreferenceTransport, matchesPreferences, projectSession } from './session-preferences'
@@ -77,6 +80,16 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp
const workspaceLabel = locale === 'zh-CN' ? '工作区文件' : 'Workspace files'
const openFiles = files ? () => { setFilesOpen(true); void files.loadProjects() } : undefined
const sid = wk.selected
+ const deliveryEnabled = bootstrap.capabilities?.deliveries === true
+ const deliveryApi = useMemo(() => deliveryEnabled ? createDeliveriesTransport(transport, bootstrap.csrf) : undefined,
+ [deliveryEnabled, transport, bootstrap.csrf])
+ const [locatedFilesSid, setLocatedFilesSid] = useState()
+ useLayoutEffect(() => { setLocatedFilesSid(undefined) }, [sid, locked])
+ const openInWorkspace = useCallback(async ({ workspaceId, path }: DeliveryLocation, signal: AbortSignal): Promise => {
+ if (!sid || !files || signal.aborted || !await files.reveal(workspaceId, path, signal) || signal.aborted) return false
+ setLocatedFilesSid(sid)
+ return true
+ }, [files, sid])
const selectedEntry = wk.sessions.find((s) => s.id === sid)
const preferenceEntry = sid ? preferences?.get(sid) : undefined
const projectedEntry = selectedEntry ? projectSession(selectedEntry, preferenceEntry?.pending) : undefined
@@ -216,7 +229,9 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp
if (!preferenceControlsDisabled && model !== preferenceEntry?.confirmed?.preferences.model) void preferences.write(sid, { model })
}
} : undefined}
- openSettings={openSettings} openFiles={openFiles} workspaceLabel={workspaceLabel} />
+ openSettings={openSettings} openFiles={openFiles} workspaceLabel={workspaceLabel}
+ deliveryApi={deliveryApi} locale={locale} beforeWrite={beforeWrite} onExpired={onExpired}
+ openInWorkspace={files ? openInWorkspace : undefined} />
:
{wk.listLoading ? {c.loading} : <>
{wk.listIssue ? c[wk.listIssue] : c.empty}
@@ -230,7 +245,8 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp
{settingsOpen && renderSettings(() => setSettingsOpen(false))}
{browserOpen && browserVisible && setBrowserOpen(undefined)} />}
- {files && setFilesOpen(false)} controller={files} />}
+ {files && { setFilesOpen(false); setLocatedFilesSid(undefined) }} controller={files} />}
{renameSid && renameSid === sid && preferences && preferenceEntry && setRenameSid(undefined)} reload={reloadPreferences} />}
@@ -244,9 +260,11 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp
type ManagedModel = { pinned: string | null | undefined; disabled: boolean; choose: (model: string | null) => void }
-function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openSettings, openFiles, workspaceLabel }: {
+function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openSettings, openFiles, workspaceLabel,
+ deliveryApi, locale, beforeWrite, onExpired, openInWorkspace }: {
sid: string; wk: Workspace; c: ChatCopy; locked: boolean; preferred: string | null; onPick: (id: string) => void; openSettings: () => void
- openFiles?: () => void; workspaceLabel: string; managedModel?: ManagedModel
+ openFiles?: () => void; workspaceLabel: string; managedModel?: ManagedModel; deliveryApi?: DeliveriesTransport; locale: string
+ beforeWrite: () => Promise; onExpired: () => void; openInWorkspace?: (where: DeliveryLocation, signal: AbortSignal) => Promise
}): React.JSX.Element {
const state = wk.projection?.snapshot?.state
const link = wk.projection?.status ?? 'loading'
@@ -262,6 +280,43 @@ function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openS
const following = useRef(true)
const [atBottom, setAtBottom] = useState(true)
const anchor = useRef()
+ // Deltas only change active.text. Read deliveries on confirmed snapshot/turn changes, never on deltas.
+ const authority = link === 'ready' && state ? [wk.projection?.snapshot?.cursor.generation, state.compatibility,
+ state.messages?.length ?? 'history', active?.turnId ?? '', last?.turnId ?? '', last?.status ?? '', last?.reason ?? ''].join(':') : undefined
+ const { controller: deliveries, view: deliveryView } = useDeliveries(deliveryApi, sid, !locked && link !== 'missing', authority,
+ { beforeWrite, expired: onExpired, openWorkspace: openInWorkspace })
+ const start = Math.max(0, messages.length - windowSize)
+ const eligible = eligibleDeliveryReplies(state, !!wk.pending, authority, deliveryView)
+ const messageIndexFor = (group: DeliveryGroup): number | undefined => {
+ const i = group.messageIndex
+ return group.origin === 'reply' && group.turnId && i !== undefined && state?.compatibility === 'text' &&
+ messages[i]?.role === 'assistant' && messages[i].content.trim() ? i : undefined
+ }
+ const attached = new Map()
+ const history = deliveryView.groups.filter((group) => {
+ const i = messageIndexFor(group)
+ if (i === undefined || i < start) return true
+ const groups = attached.get(i) ?? []
+ groups.push(group)
+ attached.set(i, groups)
+ return false
+ })
+ const requestedReveal = useRef()
+ const focusSource = (selector: string): void => {
+ const element = scroll.current?.querySelector(selector)
+ if (!element) return
+ following.current = false
+ element.focus({ preventScroll: true })
+ element.scrollIntoView({ block: 'nearest' })
+ }
+ const reveal = (group: DeliveryGroup): void => {
+ const i = messageIndexFor(group)
+ if (i === undefined) return focusSource(`[data-delivery-group-id="${group.id}"]`)
+ if (i >= start) return focusSource(`[data-delivery-message-index="${i}"]`)
+ requestedReveal.current = i
+ following.current = false
+ setWindowSize((n) => Math.max(n, messages.length - i))
+ }
const jump = (): void => {
const el = scroll.current
if (!el) return
@@ -274,6 +329,10 @@ function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openS
scroll.current.scrollTop = scroll.current.scrollHeight - anchor.current
anchor.current = undefined
} else if (following.current) jump()
+ if (requestedReveal.current !== undefined) {
+ focusSource(`[data-delivery-message-index="${requestedReveal.current}"]`)
+ requestedReveal.current = undefined
+ }
}, [messages, active, windowSize, attachmentDraft])
const older = (): void => {
const el = scroll.current
@@ -281,7 +340,6 @@ function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openS
following.current = false
setWindowSize((n) => n + PAGE)
}
- const start = Math.max(0, messages.length - windowSize)
const visibleMessages = useMemo(() => messages.slice(start).map((message) => ({ message,
cards: uploads ? message.attachments?.map((entry) => attachmentCard(sid, entry)) : undefined
})), [messages, start, uploads, sid])
@@ -299,8 +357,22 @@ function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openS
{writeBanner && {writeBanner}
}
{link === 'missing' && {c.missing}
}
{!messages.length && !writeBanner && link === 'ready' && {c.empty}
}
- {visibleMessages.map(({ message, cards }, index) => )}
+ {visibleMessages.map(({ message, cards }, index) => {
+ const at = start + index
+ const candidate = eligible.get(at)
+ const groups = attached.get(at) ?? []
+ const bubble =
+ return deliveries && (candidate || groups.length) ?
+ {bubble}
+
+ {candidate && authority && }
+ {groups.map((group) => reveal(group)} />)}
+
+
: bubble
+ })}
{active?.text && }
{link !== 'ready' && link !== 'missing' && {c[link === 'reconnecting' ? 'reconnecting' : 'loading']}
}
{active && {active.text ? c.running : c.reading}
}
@@ -308,8 +380,11 @@ function TextThread({ sid, wk, c, locked, preferred, onPick, managedModel, openS
data-testid="workbench-turn-status" data-status={last.status}>{turnLabel(c, last)}
}
{wk.pending === 'send' && !active && {c.sent}
}
{wk.turnIssue && {c[wk.turnIssue]}
}
+ {deliveries && messageIndexFor(group) !== undefined} reveal={reveal} />}
+ {deliveries && }
{uploads && uploads.dismiss(sid)} />}
{(state?.writable || active) && {
+ const headers: Record = { accept: options.accept }
+ const post = options.post
+ if (options.ifMatch) headers['if-match'] = options.ifMatch
+ if (post) {
+ if (!post.csrf) throw new Error('Delivery session closed')
+ headers[csrfHeader] = post.csrf
+ headers['content-type'] = 'application/json'
+ }
+ const response = await send(prefix + path, {
+ method: post ? 'POST' : 'GET', headers, signal,
+ body: post ? JSON.stringify(post.body) : undefined, credentials: 'same-origin',
+ mode: 'same-origin', redirect: 'error', cache: 'no-store', referrerPolicy: 'same-origin'
+ })
+ if (!response.ok) {
+ const failure: unknown = await response.json().catch(() => undefined)
+ const code = record(failure) ? failure.error ?? failure.code : undefined
+ throw new HttpFailure(response.status, typeof code === 'string' ? code : undefined)
+ }
+ return response
+ }
+
return {
- request, uploadAttachment, browserRequest,
+ request, uploadAttachment, browserRequest, deliveryRequest,
async inspect(): Promise {
try {
return { mode: 'authenticated', bootstrap: await bootstrap() }
diff --git a/apps/desktop/src/workbench/workspace-files.ts b/apps/desktop/src/workbench/workspace-files.ts
index c80a1a3f..c5e36cb1 100644
--- a/apps/desktop/src/workbench/workspace-files.ts
+++ b/apps/desktop/src/workbench/workspace-files.ts
@@ -120,8 +120,8 @@ export function createWorkspaceFiles(api: WorkspaceTransport) {
directories = new Map(directories).set(path, state)
emit()
}
- async function list(path: string): Promise {
- if (!projectId || projectIssue() || directories.get(path)?.pending || directories.get(path)?.data) return
+ async function list(path: string, refresh = false): Promise {
+ if (!projectId || projectIssue() || directories.get(path)?.pending || (!refresh && directories.get(path)?.data)) return
const id = projectId
const generation = dirGeneration
directory(path, { pending: true })
@@ -194,6 +194,38 @@ export function createWorkspaceFiles(api: WorkspaceTransport) {
return !view.file?.disk && !view.file?.issue ? reload() : undefined
}
+ // Reuse the same project, directory and reader checks as the manual file panel.
+ async function reveal(id: string, path: string, signal: AbortSignal): Promise {
+ if (signal.aborted) return false
+ await loadProjects()
+ if (signal.aborted || !projects.data?.some((project) => project.id === id)) return false
+ await (select(id) ?? list(''))
+ const current = (): boolean => !signal.aborted && projectId === id && !projectIssue()
+ if (!current()) return false
+ const segments = path.split('/')
+ let parent = ''
+ for (const [index, name] of segments.entries()) {
+ const target = parent ? `${parent}/${name}` : name
+ const last = index === segments.length - 1
+ let entry = directories.get(parent)?.data?.entries.find((node) => node.path === target)
+ if (!entry) {
+ // Manual browsing may have cached the directory before this file was produced.
+ await list(parent, true)
+ if (!current()) return false
+ entry = directories.get(parent)?.data?.entries.find((node) => node.path === target)
+ }
+ if (entry?.type !== (last ? 'file' : 'dir')) return false
+ if (last) {
+ await openFile(target)
+ return current() && view.file?.path === target && !!view.file.disk && !view.file.issue
+ }
+ await (expanded.has(target) ? list(target) : toggle(target))
+ if (!current()) return false
+ parent = target
+ }
+ return false
+ }
+
function edit(text: string): void {
const file = view.file
if (!view.writable || file?.disk?.kind !== 'text' || file.pending === 'read') return
@@ -236,7 +268,7 @@ export function createWorkspaceFiles(api: WorkspaceTransport) {
return {
snapshot: () => view,
subscribe(notify: () => void): () => void { listeners.add(notify); return () => { listeners.delete(notify) } },
- loadProjects, select, list, toggle, openFile, reload, edit, review, canSave, save
+ loadProjects, select, list, toggle, openFile, reveal, reload, edit, review, canSave, save
}
}
diff --git a/apps/headless/README.md b/apps/headless/README.md
index 7ee5d7c8..e9881ee8 100644
--- a/apps/headless/README.md
+++ b/apps/headless/README.md
@@ -27,6 +27,14 @@
每条消息最多 4 个附件、合计 20 MiB;同一会话已提交的附件累计上限为 48 MiB。草稿默认保留 24 小时,每个会话最多 32 份或 40 MiB,实例总量最多 512 份或 256 MiB。成功确认会话内容后释放对应草稿额度;中途关闭页面可能留下未发送的草稿,期限过后在清扫时回收。已发送图片可在刷新或容器重建后按当前会话查看;重试同一个已确认的发送请求不会重新向模型计费。工具卡、交付件、任意桌面文件和文件夹路径的自动处理不属于这条流程。
+## 下载交付物,或把回复保存为文件
+
+在已结束并确认写入磁盘的助手回复旁,点击 **导出 Markdown** 或 **导出纯文本**。交付卡使用桌面原有的文件行和折叠布局。点击卡片上的下载按钮,原始 UTF-8 字节才会写到当前浏览器的下载位置。重复导出同一轮、同一格式会返回原来的交付记录,不会再次调用模型。导出的是可见的最终回复,不包含推理、工具参数或模型配置;这并不表示在服务器上运行了文件生成工具。
+
+旧桌面对话的交付记录仍为只读。服务只认可桌面 `present_files` 的成功调用、配对的结果和已经保存的交付清单;不会从随意一段聊天文字中猜测路径。只有落在管理员已挂载项目内的合格文件才会显示。原生路径须在本实例的授权目录中仍然有效;原机器路径、链接和隐藏项目不会被映射成浏览器文件。可以下载受支持的数据文本和静态图片(单份 2 MiB)、PDF 和可识别的无宏 `.docx`、`.xlsx`、`.pptx`(单份 8 MiB)。Office 识别核对包结构、主要 XML 与内部关系;含未受支持的部件(如嵌入二进制、打印机配置)、外部关系、旧版二进制格式或加密内容时,卡片会标明该类型暂未支持。Office 和 PDF 均作为附件交给浏览器下载,不在同源页面执行或预览。只有校验后的 PNG/JPEG/WebP 可在网页内预览。对可定位的桌面交付项,点击「在工作区文件中定位」会选中同一项目和相对路径,不会启动服务器的系统文件管理器。
+
+下载、预览和定位都检查当前登录、对话、交付组、原始序号和文件版本。已移动、已更换、过大或未支持的文件都有独立状态;变更后需要先刷新交付卡。这些地址不是公开分享链接。备份要包含数据卷:已导出回复的确认记录和原会话共同决定可下载的字节;项目中的桌面交付文件则需随自己的项目另行保管。
+
## 手动打开服务器项目的文件
配置专用项目父目录后,工作台的文件夹按钮会显示已授权的项目。打开目录只读一层;打开文件只读取该项目的相对路径。浏览器选择的项目与聊天会话相互独立,文件内容不自动发送给模型。文本预览上限 2 MiB;二进制和过大文件只显示类型/体积提示。隐藏文件、符号链接、硬链接、设备和项目内额外挂载不在此授权范围。
diff --git a/apps/headless/src/business/handlers.mjs b/apps/headless/src/business/handlers.mjs
index 253a33a4..6a5be22c 100644
--- a/apps/headless/src/business/handlers.mjs
+++ b/apps/headless/src/business/handlers.mjs
@@ -1,6 +1,7 @@
import { connectProvider } from './model-connection.mjs'
import { openUploadStore } from '../attachments/upload-store.mjs'
import { attachmentRoutes } from '../attachments/routes.mjs'
+import { deliveryRoutes } from '../deliveries/routes.mjs'
import { createEventJournal } from '../events/index.mjs'
import { createChatWebSocket } from '../events/websocket.mjs'
import { createTextTurns } from '../chat/text-turns.mjs'
@@ -51,7 +52,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi
try {
library = await openLibrary({ dataDir, workspaceRoot, workspaceWritable, privateRoots })
uploads = await openUploadStore({ dataDir })
- turns = createTextTurns({ dataDir, settings, journal, ...opts, resolveRole: library.resolveRole, uploads })
+ turns = createTextTurns({ dataDir, settings, journal, ...opts, resolveRole: library.resolveRole, uploads, deliveries: true })
// The Unix client is loaded only when the operator mounted a private worker socket.
if (browserRunDir) {
const { createManualBrowser } = await import('../browser/manual-browser.mjs')
@@ -61,6 +62,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi
const handleBrowser = browserRoutes(browser)
const chats = chatRoutes(turns, { withRoleForChat: library.withRoleForChat })
const attachments = attachmentRoutes({ uploads, turns })
+ const deliveries = deliveryRoutes({ turns, files: library.deliveryFiles })
function beginShutdown() {
lifetime.abort(); attachments.close()
if (browser && !closingBrowser) { closingBrowser = Promise.resolve(browser.close()); void closingBrowser.catch(() => {}) }
@@ -68,13 +70,15 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi
return {
beginShutdown,
capabilities: Object.freeze({ textChat: true, library: true, workspaceFiles: library.workspaceFilesEnabled, attachments: true,
- browserPanel: !!browser, sessionPreferences: typeof turns.patchPreferences === 'function' && typeof journal.watchSessions === 'function' }),
+ browserPanel: !!browser, deliveries: typeof turns.deliverySnapshot === 'function',
+ sessionPreferences: typeof turns.patchPreferences === 'function' && typeof journal.watchSessions === 'function' }),
createRealtime: ({ auth, policy }) => createChatWebSocket({ turns, journal, auth, policy }),
getConfig: () => settings.getPublicConfig(),
async handle(req, res, { auth, policy }) {
const path = (req.url ?? '').split('?', 1)[0]
if (path.includes('/browser') && await handleBrowser(req, res, { auth, policy })) return true
if (path === '/api/v1/chats' || path.startsWith('/api/v1/chats/')) {
+ if (path.includes('/deliveries') && await deliveries(req, res, { auth, policy })) return true
if (path.includes('/attachments') && await attachments.handle(req, res, { auth, policy })) return true
return chats(req, res, { auth, policy })
}
diff --git a/apps/headless/src/business/library-routes.mjs b/apps/headless/src/business/library-routes.mjs
index a64ab98a..91c36c10 100644
--- a/apps/headless/src/business/library-routes.mjs
+++ b/apps/headless/src/business/library-routes.mjs
@@ -7,6 +7,7 @@ import { checkRoleBindings } from './role-bindings.mjs'
import { openWorkspaceCatalog } from './workspace-catalog.mjs'
import { openWorkspaceFiles } from '../files/workspace-files.mjs'
import { workspaceFileRoutes } from '../files/workspace-routes.mjs'
+import { openDeliveryFiles } from '../files/delivery-files.mjs'
const rolePath = /^\/api\/v1\/personas\/([A-Za-z0-9][A-Za-z0-9_.-]{0,63})(?:\/(enabled|avatar-image))?$/
const memoryPath = /^\/api\/v1\/memory\/(global|role|project)(?:\/([A-Za-z0-9][A-Za-z0-9_.-]{0,127}))?$/
@@ -94,6 +95,7 @@ export async function openLibrary({ dataDir, workspaceRoot, workspaceWritable =
}
return {
workspaceFilesEnabled: Boolean(fileCommands),
+ deliveryFiles: workspaceRoot ? openDeliveryFiles({ catalog }) : undefined,
resolveRole: id => serial(() => enabledRole(id)),
withRoleForChat: (id, action) => serial(async () => action(await enabledRole(id))),
async handle(req, res, { auth, policy }) {
diff --git a/apps/headless/src/business/workspace-catalog.mjs b/apps/headless/src/business/workspace-catalog.mjs
index 0bd1f437..ddc49213 100644
--- a/apps/headless/src/business/workspace-catalog.mjs
+++ b/apps/headless/src/business/workspace-catalog.mjs
@@ -1,7 +1,11 @@
import { createHash } from 'node:crypto'
import { openSync, opendirSync, realpathSync } from 'node:fs'
import { isAbsolute, join, relative, resolve, sep } from 'node:path'
-import { DIRECTORY, close, fdPath, mountId, openAbsoluteDirectory, sameInode, stat, visibleName } from '../files/workspace-files-fd.mjs'
+import { DIRECTORY, close, fdPath, mountId, openAbsoluteDirectory, sameInode, stat, validWorkspaceName, visibleName, workspacePathParts } from '../files/workspace-files-fd.mjs'
+
+const deliverySystemRoots = ['/boot', '/usr', '/bin', '/sbin', '/lib', '/lib64', '/var/log', '/var/cache', '/var/spool', '/var/backups']
+const privateDeliveryName = /^(?:credentials?|secrets?|private[-_ ]?keys?|api[-_ ]?keys?|(?:access[-_ ]?|refresh[-_ ]?)tokens?|id[-_](?:rsa|dsa|ecdsa|ed25519)|known_hosts|authorized_keys|passwd|shadow)(?:[._ -]|$)|\.(?:pem|key|p12|pfx|kdbx)(?:\.|$)/iu
+const hiddenDeliveryName = name => privateDeliveryName.test(name) || /[\p{Cf}\p{Zl}\p{Zp}]/u.test(name)
const unavailable = () => Object.assign(Error('Workspace is unavailable'), { code: 'ERR_WORKSPACE_UNAVAILABLE', status: 404, statusCode: 404 })
const validId = id => typeof id === 'string' && /^w_[a-f0-9]{32}$/.test(id)
@@ -25,11 +29,18 @@ function overlapsReserved(base, path) {
/** Only first-level real directories of an explicitly mounted root are choices. resolveRoot
* serves memory's canonical project-key calculation; file consumers own a pinProject lease. */
export function openWorkspaceCatalog({ root, privateRoots = [] }) {
- if (root == null || root === '') return Object.freeze({ list: () => [], resolveRoot: () => undefined, pinProject() { throw unavailable() }, close() {} })
+ if (root == null || root === '') return Object.freeze({
+ list: () => [], resolveRoot: () => undefined, resolveDeliveryPath: () => null,
+ pinProject() { throw unavailable() }, close() {},
+ })
if (typeof root !== 'string' || !isAbsolute(root) || root.includes('\0')) throw unavailable()
const base = resolve(root)
const reserved = [...privateRoots, '/proc', '/dev', '/sys', '/etc', '/run', '/root']
if (base === '/' || reserved.some(path => overlapsReserved(base, path))) throw unavailable()
+ // Apply the extra system-directory exclusion to native deliveries only. Workspace browsing
+ // and project identifiers keep their existing contract.
+ const deliveryEnabled = !deliverySystemRoots.some(path => overlapsReserved(base, path))
+ const deliveryPrefix = base + sep
let fd, rootInfo, rootMount
try {
fd = openAbsoluteDirectory(base)
@@ -89,6 +100,26 @@ export function openWorkspaceCatalog({ root, privateRoots = [] }) {
if (!validId(id)) return undefined
return items().find(item => item.id === id)?.path
},
+ // Server-read native history only. No absolute path is opened here: derive the
+ // catalog ID from an actual direct child. The caller must still pin that ID and
+ // verify every intermediate directory and leaf before claiming the item.
+ resolveDeliveryPath(absolute) {
+ if (!deliveryEnabled || typeof absolute !== 'string' || absolute.length > 4095 ||
+ !absolute.startsWith(deliveryPrefix) || Buffer.byteLength(absolute) > 4095) return null
+ const split = absolute.indexOf(sep, deliveryPrefix.length)
+ if (split < 0) return null
+ const name = absolute.slice(deliveryPrefix.length, split)
+ const path = absolute.slice(split + 1)
+ const parts = workspacePathParts(path)
+ if (!validWorkspaceName(name) || hiddenDeliveryName(name) || !parts || parts.some(hiddenDeliveryName)) return null
+ let item
+ try {
+ assertRoot()
+ item = openChild(name)
+ assertRoot()
+ return { id: projectId(item.path, item.info), path }
+ } catch { return null } finally { close(item?.sub) }
+ },
pinProject(id) {
if (!validId(id)) throw unavailable()
const record = items().find(item => item.id === id)
diff --git a/apps/headless/src/chat/README.md b/apps/headless/src/chat/README.md
index d504a431..63dbee92 100644
--- a/apps/headless/src/chat/README.md
+++ b/apps/headless/src/chat/README.md
@@ -15,6 +15,9 @@
| `POST /api/v1/chats/:sid/attachments` | 当前所有者把文件字节作为 `application/octet-stream` 上传;`x-deva-file-name` 是 UTF-8 文件名的无填充 base64url,`x-deva-file-type` 是所选内容类型。返回不透明附件 ID 和显示元数据,不触发模型请求。|
| `DELETE /api/v1/chats/:sid/attachments/:id` | 幂等撤回未发送的草稿;已经确认的会话历史独立保存。|
| `GET /api/v1/chats/:sid/attachments/:id/preview` | 仅为本会话授权的静态图片返回经校验的原始字节;登录过期或异会话不提供内容。|
+| `GET /api/v1/chats/:sid/deliveries` | 返回允许导出的已完成回复、确认的交付组和分页游标。只传元数据,组内序号是原条目的序号;不会广播文件内容或宿主绝对路径。|
+| `POST /api/v1/chats/:sid/deliveries/reply` | `{turnId,format}`,格式为 `md` 或 `txt`。在当前会话的已确认回复中定位,不接收浏览器提供的文件名、路径或正文。同轮同格式重复调用返回同一组。|
+| `GET /api/v1/chats/:sid/deliveries/:gid/items/:index/download` | 按交付记录和 `If-Match` 版本下载,响应使用 `Content-Disposition: attachment`。`preview` 同样验版本且仅返回经校验的静态图片;`POST …/locate` 提供当前受权项目的相对定位。|
| `WS /api/v1/chats/:sid/stream` | 只读、同源、按登录会话校验。首次订阅取快照;刷新可用最后实际应用的游标衔接,旧游标转为新快照。退出、会话过期、消费超时或服务关闭时释放连接。|
写入需要工作台登录 Cookie、匹配的 Origin 与 CSRF。通过反代访问时,对 WS 路径一并保留 Host、Origin、HTTP/1.1 Upgrade 和 Connection。不要把聊天数据、访问凭据或控制命令放入 WS URL;可选的 `cursor` 只是进度,不授予访问权。
diff --git a/apps/headless/src/chat/delivery-records-native.mjs b/apps/headless/src/chat/delivery-records-native.mjs
new file mode 100644
index 00000000..c623c695
--- /dev/null
+++ b/apps/headless/src/chat/delivery-records-native.mjs
@@ -0,0 +1,173 @@
+import { createHash } from 'node:crypto'
+import { posix, win32 } from 'node:path'
+import { deliveryLimitError, deliveryStorageError, parseNativeJSON } from './delivery-records-storage.mjs'
+
+const maxMessages = 4096
+const maxParts = 16384
+const maxDesktopGroups = 256
+const maxPaths = 20 // Original desktop present_files limit.
+const maxReply = 64 * 1024 // UTF-16 units, same as the text turn writer.
+const maxQuestion = 12 * 1024
+const TURN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u
+export const validDeliveryTurn = value => typeof value === 'string' && value.length === 36 && TURN_ID.test(value)
+const desktopId = value => typeof value === 'string' && value.length > 0 && value.length <= 256 &&
+ !/[\u0000-\u0020\u007f-\u009f]/u.test(value) && value.isWellFormed()
+export const fields = (obj, keys) => object(obj) && Object.keys(obj).length === keys.length && keys.every(key => Object.hasOwn(obj, key))
+export const object = obj => obj !== null && typeof obj === 'object' && !Array.isArray(obj)
+export const digest = value => createHash('sha256').update(value).digest('hex')
+export const groupId = (sid, origin, ...identity) => `d_${digest(JSON.stringify(['deva-delivery-v1', sid, origin, ...identity])).slice(0, 32)}`
+
+const textPart = value => fields(value, ['type', 'text']) && value.type === 'text' && typeof value.text === 'string'
+const oneText = message => Array.isArray(message.content) && message.content.length === 1 && textPart(message.content[0])
+ ? message.content[0].text : null
+
+function notice(after, { status, reason }, text) {
+ if (status === 'failed') return { after, kind: 'error', message: '模型回复未能完成。' }
+ const code = status === 'aborted' || status === 'interrupted' ? 'aborted'
+ : reason === 'refusal' ? (text?.trim() ? null : 'refused')
+ : ['empty', 'truncated', 'repeated'].includes(reason) ? reason : null
+ return code ? { after, kind: 'notice', code } : null
+}
+
+/** One native user message and at most one native assistant message per receipt,
+ * in admission order. Require this correspondence across the entire ledger, not
+ * merely a nearby assistant message after a matching turn ID. */
+export function webReplies(session, ledger, attachmentIndex) {
+ if (!fields(ledger, ['version', 'messageCount', 'requests'])) return null
+ const replies = new Map()
+ let cursor = 0
+ let notices = 0
+ for (const [ordinal, row] of ledger.requests.entries()) {
+ const keys = ['clientRequestId', 'fingerprint', 'turnId', 'startedAt', 'status', 'reason']
+ if (Object.hasOwn(row, 'model')) {
+ if (typeof row.model !== 'string' || row.model.length > 512) return null
+ keys.push('model')
+ }
+ if (!fields(row, keys) || !validDeliveryTurn(row.turnId)) return null
+ const user = session.messages[cursor]
+ if (!fields(user, ['role', 'content']) || user.role !== 'user') return null
+ if (!attachmentIndex?.byMessage.has(cursor)) {
+ const text = oneText(user)
+ if (!text || text.length > maxQuestion || !text.trim() || Buffer.byteLength(text) > maxQuestion) return null
+ }
+ cursor++
+ const messageIndex = cursor
+ let text = null
+ const assistant = session.messages[cursor]
+ if (assistant?.role === 'assistant') {
+ if (!fields(assistant, ['role', 'content'])) return null
+ text = oneText(assistant)
+ if (text === null || !text.length || text.length > maxReply || ['running', 'interrupted'].includes(row.status)) return null
+ cursor++
+ }
+ if (row.status === 'completed' && row.reason === null) {
+ if (!text?.trim()) return null
+ // Lone surrogates have no exact UTF-8 encoding. Keep the native reply visible, but not exportable.
+ if (text.isWellFormed()) replies.set(row.turnId, { turnId: row.turnId, messageIndex, ordinal, text })
+ } else if (row.reason === 'empty' && text?.trim()) return null
+ const expected = notice(cursor, row, text)
+ if (expected) {
+ const recorded = session.notices?.[notices++]
+ const names = Object.keys(expected)
+ if (!fields(recorded, names) || !names.every(key => recorded[key] === expected[key])) return null
+ }
+ }
+ return cursor === session.messages.length && notices === (session.notices?.length ?? 0) ? replies : null
+}
+
+function validateMessages(messages) {
+ return Array.isArray(messages) && messages.length <= maxMessages && messages.every(m =>
+ object(m) && ['assistant', 'user'].includes(m.role) && (typeof m.content === 'string' || Array.isArray(m.content)))
+}
+
+export function nativeMessages(files, sid, session) {
+ if (session.messages?.length > maxMessages) throw deliveryLimitError()
+ if (!validateMessages(session.messages)) throw deliveryStorageError()
+ const compacted = session.compacted
+ if (compacted === undefined) return session.messages
+ const prefix = `${sid}.compacted-`
+ if (!fields(compacted, ['count', 'file']) || !Number.isSafeInteger(compacted.count) || compacted.count < 1 ||
+ typeof compacted.file !== 'string' || !compacted.file.startsWith(prefix) ||
+ !/^[A-Za-z0-9_-]{1,128}\.jsonl$/u.test(compacted.file.slice(prefix.length)) || !compacted.file.endsWith('.jsonl')) {
+ throw deliveryStorageError()
+ }
+ if (compacted.count + session.messages.length > maxMessages) throw deliveryLimitError()
+ const text = files.readCompacted(compacted.file)
+ if (text === null) throw deliveryStorageError()
+ let start = 0
+ const messages = []
+ // An interrupted desktop append may leave extra lines; the main file commits only `count`.
+ for (let lines = 0; messages.length < compacted.count && start < text.length; lines++) {
+ if (lines >= maxMessages) throw deliveryLimitError()
+ const newline = text.indexOf('\n', start)
+ const end = newline < 0 ? text.length : newline
+ if (end !== start) messages.push(parseNativeJSON(text.slice(start, end)))
+ start = end + 1
+ }
+ if (messages.length !== compacted.count || !validateMessages(messages)) throw deliveryStorageError()
+ return [...messages, ...session.messages]
+}
+
+function validatedPaths(paths) {
+ if (!Array.isArray(paths) || paths.length === 0 || paths.length > maxPaths) return null
+ const unique = new Set()
+ for (const p of paths) {
+ if (typeof p !== 'string' || !p.length || p.length > 4096 || Buffer.byteLength(p) > 4096 ||
+ /[\u0000-\u001f\u007f-\u009f]/u.test(p) || !p.isWellFormed()) return null
+ const absolutePosix = p.startsWith('/') && p.length > 1 && !p.endsWith('/') && posix.normalize(p) === p
+ const absoluteWindows = /^(?:[A-Za-z]:\\|\\\\[^.\\?][^\\]*\\[^\\]+\\)/u.test(p) && !p.endsWith('\\') && win32.normalize(p) === p
+ if (!absolutePosix && !absoluteWindows) return null
+ const identity = absoluteWindows ? p.toLowerCase() : p
+ if (unique.has(identity)) return null
+ unique.add(identity)
+ }
+ return paths.map((path, index) => ({ index, path }))
+}
+
+export function desktopDeliveryRecords(sid, messages, delivered) {
+ if (!object(delivered)) return []
+ if (Object.keys(delivered).length > maxParts) throw deliveryLimitError()
+ const uses = new Map()
+ const results = new Map()
+ const deliveries = []
+ let count = 0
+ const unique = (map, id, value) => map.set(id, map.has(id) ? null : value)
+ for (const [at, message] of messages.entries()) {
+ const content = message.content
+ if (!Array.isArray(content)) continue
+ if ((count += content.length) > maxParts) throw deliveryLimitError()
+ for (const part of content) {
+ if (!object(part) || typeof part.type !== 'string') throw deliveryStorageError()
+ if (part.type === 'tool_use' && desktopId(part.id)) {
+ unique(uses, part.id, at)
+ if (message.role === 'assistant' && part.name === 'present_files') deliveries.push({ id: part.id, at })
+ } else if (part.type === 'tool_result' && desktopId(part.toolUseId)) {
+ unique(results, part.toolUseId, { at, part })
+ }
+ }
+ }
+ const records = []
+ const completeBatches = new Map()
+ function completeBatch(at) {
+ if (completeBatches.has(at)) return completeBatches.get(at)
+ const next = messages[at + 1]
+ const calls = messages[at].content.filter(p => p.type === 'tool_use')
+ const complete = next?.role === 'user' && Array.isArray(next.content) && next.content.length === calls.length &&
+ next.content.every(p => p.type === 'tool_result') && calls.every(call =>
+ uses.get(call.id) === at && results.get(call.id)?.at === at + 1)
+ completeBatches.set(at, complete)
+ return complete
+ }
+ // Newest first; keep the exact native order of the files within each group.
+ for (const { id, at } of deliveries.reverse()) {
+ const result = results.get(id)
+ if (uses.get(id) !== at || result?.at !== at + 1 || !completeBatch(at) ||
+ (result.part.isError !== undefined && result.part.isError !== false) ||
+ typeof result.part.content !== 'string' || !result.part.content.trim() || !Object.hasOwn(delivered, id)) continue
+ const entries = validatedPaths(delivered[id])
+ if (!entries) continue
+ if (records.length >= maxDesktopGroups) throw deliveryLimitError()
+ records.push({ id: groupId(sid, 'desktop', id), origin: 'desktop', messageIndex: at, entries })
+ }
+ return records
+}
diff --git a/apps/headless/src/chat/delivery-records-storage.mjs b/apps/headless/src/chat/delivery-records-storage.mjs
new file mode 100644
index 00000000..7b24c70f
--- /dev/null
+++ b/apps/headless/src/chat/delivery-records-storage.mjs
@@ -0,0 +1,216 @@
+import { randomBytes } from 'node:crypto'
+import {
+ closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, openSync, readSync, realpathSync,
+ renameSync, unlinkSync, writeFileSync
+} from 'node:fs'
+import { join, resolve } from 'node:path'
+import { DIRECTORY, PATH, fdPath, mountId, sameInode } from '../files/workspace-files-fd.mjs'
+import { HttpError } from '../http/policy.mjs'
+
+const stats = { bigint: true }
+const dirFlags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW | constants.O_NONBLOCK
+const readFlags = constants.O_RDONLY | constants.O_NONBLOCK
+const writeFlags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_NONBLOCK
+const uid = BigInt(process.geteuid())
+const nativeLimit = 32 * 1024 * 1024 // Full native history, including any declared compacted prefix.
+const metadataLimit = 128 * 1024 // 256 ledger rows × two formats; no document bytes.
+const signature = ['mode', 'uid', 'gid', 'nlink', 'size', 'mtimeNs', 'ctimeNs']
+const same = (a, b) => sameInode(a, b) && signature.every(key => a[key] === b[key])
+const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
+export const deliveryStorageError = () => new HttpError(503, 'chat_storage_unconfirmed')
+export const deliveryLimitError = () => new HttpError(413, 'delivery_history_limit')
+const corrupted = () => { throw deliveryStorageError() }
+
+function stat(path) {
+ try { return lstatSync(path, stats) } catch (err) { if (err?.code !== 'ENOENT') throw err; return null }
+}
+
+const safeDir = (st, privateMode) => st?.isDirectory() && st.uid === uid && (st.mode & (privateMode ? 0o077n : 0o022n)) === 0n
+const safeFile = (st, privateMode) => st?.isFile() && st.uid === uid && st.nlink === 1n &&
+ (privateMode ? (st.mode & 0o7777n) === 0o600n : (st.mode & 0o022n) === 0n)
+
+/** The workbench holds its data directory's writer lock throughout this synchronous operation.
+ * Use directory FDs so neither native reads nor writes ever follow a replacement directory. */
+export function withDeliveryFiles(dataDir, sid, use) {
+ const root = resolve(dataDir)
+ const dirs = []
+ function directory(path, privateMode) {
+ const named = stat(path)
+ if (!named) return null
+ if (!safeDir(named, privateMode)) corrupted()
+ const parent = dirs.at(-1)
+ const fd = openSync(path, dirFlags)
+ const entry = { path, fd, named, privateMode, mount: null }
+ dirs.push(entry)
+ const opened = fstatSync(fd, stats)
+ entry.mount = mountId(fd)
+ if (!safeDir(opened, privateMode) || !sameInode(named, opened) || (parent && parent.mount !== entry.mount)) corrupted()
+ return fdPath(fd)
+ }
+ function stableDirs() {
+ if (realpathSync(root) !== root) corrupted()
+ for (const { path, named, privateMode, mount } of dirs) {
+ const pin = openSync(path, DIRECTORY)
+ try {
+ const live = fstatSync(pin, stats)
+ if (!safeDir(live, privateMode) || !sameInode(live, named) || mountId(pin) !== mount) corrupted()
+ } finally { closeSync(pin) }
+ }
+ }
+ try {
+ const home = directory(root, true)
+ const data = home && directory(join(home, 'data'), false)
+ const chats = data && directory(join(data, 'chats'), false)
+ if (!chats) return use(null)
+ stableDirs()
+ const mount = dirs.at(-1).mount
+ const nativeName = `${sid}.json`
+ const metadataName = `${sid}.deliveries-v1`
+ let nativeBytes = 0
+ const native = new Map()
+ let metadata
+
+ function read(name, limit, privateMode) {
+ const path = join(chats, name)
+ const named = stat(path)
+ if (!named) return null
+ if (!safeFile(named, privateMode) || named.size < 1n) corrupted()
+ if (named.size > BigInt(limit)) throw privateMode ? deliveryStorageError() : deliveryLimitError()
+ // O_PATH pins the inode before a data open, even if the name races to a device/FIFO.
+ const pin = openSync(path, PATH)
+ try {
+ const pinned = fstatSync(pin, stats)
+ if (!safeFile(pinned, privateMode) || !same(named, pinned) || mountId(pin) !== mount) corrupted()
+ const fd = openSync(fdPath(pin), readFlags)
+ try {
+ const opened = fstatSync(fd, stats)
+ if (!same(pinned, opened) || mountId(fd) !== mount) corrupted()
+ const bytes = Buffer.allocUnsafe(Number(opened.size))
+ for (let offset = 0; offset < bytes.length;) {
+ const count = readSync(fd, bytes, offset, bytes.length - offset, offset)
+ if (!count) corrupted()
+ offset += count
+ }
+ unchanged(name, opened)
+ if (!same(opened, fstatSync(fd, stats))) corrupted()
+ return { identity: opened, text: decoder.decode(bytes), bytes: bytes.length }
+ } finally { closeSync(fd) }
+ } finally { closeSync(pin) }
+ }
+
+ function readNative(name) {
+ const source = read(name, nativeLimit - nativeBytes, false)
+ native.set(name, source?.identity ?? null)
+ nativeBytes += source?.bytes ?? 0
+ return source
+ }
+
+ function unchanged(name, expected) {
+ const path = join(chats, name)
+ if (expected === null) {
+ if (stat(path) !== null) corrupted()
+ return
+ }
+ const pin = openSync(path, PATH)
+ try {
+ if (!same(expected, fstatSync(pin, stats)) || mountId(pin) !== mount) corrupted()
+ } finally { closeSync(pin) }
+ }
+
+ function validate() {
+ stableDirs()
+ for (const [name, identity] of native) unchanged(name, identity)
+ if (metadata !== undefined) unchanged(metadataName, metadata)
+ }
+
+ function readMetadata() {
+ const file = read(metadataName, metadataLimit, true)
+ metadata = file?.identity ?? null
+ return file?.text ?? null
+ }
+
+ function saveMetadata(text) {
+ if (metadata === undefined || Buffer.byteLength(text) > metadataLimit) corrupted()
+ const tmp = join(chats, `${metadataName}.${randomBytes(12).toString('hex')}.tmp`)
+ const fd = openSync(tmp, writeFlags, 0o600)
+ let pending = true
+ try {
+ fchmodSync(fd, 0o600)
+ writeFileSync(fd, text, 'utf8')
+ fsyncSync(fd)
+ validate()
+ const created = fstatSync(fd, stats)
+ const named = stat(tmp)
+ if (!safeFile(created, true) || !named || !same(created, named)) corrupted()
+ renameSync(tmp, join(chats, metadataName))
+ pending = false
+ fsyncSync(dirs.at(-1).fd)
+ const saved = read(metadataName, metadataLimit, true)
+ // rename can change ctime. Still require the inode we published, exact bytes and stable readback.
+ if (!saved || !sameInode(saved.identity, created) || saved.text !== text) corrupted()
+ metadata = saved.identity
+ validate()
+ } finally {
+ try {
+ if (pending) {
+ const named = stat(tmp)
+ if (named && sameInode(named, fstatSync(fd, stats))) unlinkSync(tmp)
+ }
+ } finally { closeSync(fd) }
+ }
+ }
+
+ const result = use({
+ readMain() {
+ const file = readNative(nativeName)
+ return file && { value: parseNativeJSON(file.text), privateMode: (file.identity.mode & 0o7777n) === 0o600n ||
+ (file.identity.mode & 0o7777n) === 0o400n }
+ },
+ readCompacted: name => readNative(name)?.text ?? null,
+ readMetadata, saveMetadata
+ })
+ validate()
+ return result
+ } finally {
+ for (const { fd } of dirs.reverse()) closeSync(fd)
+ }
+}
+
+// Native JSON is strict about shape at the projection layer. Also reject duplicate object
+// keys (JSON.parse would silently choose the last one), and bound nesting / structural work
+// before comparisons with the native in-memory view. Ignore syntax inside quoted strings.
+export function parseNativeJSON(text) {
+ const token = /["[\]{},:\\]/g
+ const quote = /["\\]/g
+ const scopes = []
+ let count = 0
+ for (let match; (match = token.exec(text));) {
+ if (++count > 1_000_000) throw deliveryLimitError()
+ const char = match[0]
+ const scope = scopes.at(-1)
+ if (char === '"') {
+ quote.lastIndex = token.lastIndex
+ for (;;) {
+ const end = quote.exec(text)
+ if (!end) corrupted()
+ if (end[0] === '"') break
+ quote.lastIndex++
+ }
+ token.lastIndex = quote.lastIndex
+ if (scope?.key) {
+ const key = JSON.parse(text.slice(match.index, token.lastIndex))
+ if (scope.keys.has(key)) corrupted()
+ scope.keys.add(key)
+ scope.key = false
+ }
+ } else if (char === '{' || char === '[') {
+ if (scopes.length >= 32) throw deliveryLimitError()
+ scopes.push(char === '{' ? { keys: new Set(), key: true } : null)
+ } else if (char === '}' || char === ']') {
+ scopes.pop()
+ } else if (char === ',' && scope) {
+ scope.key = true
+ }
+ }
+ return JSON.parse(text)
+}
diff --git a/apps/headless/src/chat/delivery-records.mjs b/apps/headless/src/chat/delivery-records.mjs
new file mode 100644
index 00000000..9394234b
--- /dev/null
+++ b/apps/headless/src/chat/delivery-records.mjs
@@ -0,0 +1,172 @@
+import { isDeepStrictEqual } from 'node:util'
+import { HttpError } from '../http/policy.mjs'
+import { desktopDeliveryRecords, digest, fields, groupId, nativeMessages, object, validDeliveryTurn, webReplies } from './delivery-records-native.mjs'
+import { deliveryStorageError, parseNativeJSON, withDeliveryFiles } from './delivery-records-storage.mjs'
+
+const formats = new Map([['md', 'text/markdown; charset=utf-8'], ['txt', 'text/plain; charset=utf-8']])
+const missing = () => new HttpError(404, 'session_not_found')
+const ineligible = () => new HttpError(404, 'reply_not_exportable')
+const invalidExport = () => new HttpError(400, 'invalid_delivery_export')
+const validGroupId = value => typeof value === 'string' && value.length === 34 && /^d_[0-9a-f]{32}$/u.test(value)
+const revision = value => typeof value === 'string' && value.length === 64 && /^[0-9a-f]{64}$/u.test(value)
+const time = value => Number.isFinite(value) && value >= 0
+const emptyIndex = () => ({ version: 1, rows: [] })
+
+function exportInput(raw, validSid) {
+ if (!raw || ![Object.prototype, null].includes(Object.getPrototypeOf(raw)) || Reflect.ownKeys(raw).length !== 2) throw invalidExport()
+ const turn = Object.getOwnPropertyDescriptor(raw, 'turnId')
+ const format = Object.getOwnPropertyDescriptor(raw, 'format')
+ if (!turn?.enumerable || !format?.enumerable || !validSid(turn.value) || !formats.has(format.value)) throw invalidExport()
+ return { turnId: turn.value, format: format.value }
+}
+
+function metadata(text, sid) {
+ if (text === null) return emptyIndex()
+ const index = parseNativeJSON(text)
+ // Atomic writer emits one canonical JSON representation. Reject duplicate keys,
+ // extra fields, oversized arrays, and IDs from a different session.
+ if (!fields(index, ['version', 'rows']) || index.version !== 1 || !Array.isArray(index.rows) || index.rows.length > 512 ||
+ text !== JSON.stringify(index)) throw deliveryStorageError()
+ const ids = new Set()
+ for (const row of index.rows) {
+ if (!fields(row, ['id', 'turnId', 'format', 'messageIndex', 'revision']) || !validDeliveryTurn(row.turnId) || !formats.has(row.format) ||
+ !Number.isSafeInteger(row.messageIndex) || row.messageIndex < 1 || row.messageIndex > 511 || !revision(row.revision) ||
+ row.id !== groupId(sid, 'reply', row.turnId, row.format) || ids.has(row.id)) throw deliveryStorageError()
+ ids.add(row.id)
+ }
+ return index
+}
+
+function replyRecord(row, reply) {
+ return {
+ id: row.id, origin: 'reply', turnId: row.turnId, messageIndex: reply.messageIndex, entries: [{
+ index: 0, name: `reply-${String(reply.ordinal + 1).padStart(3, '0')}.${row.format}`, size: Buffer.byteLength(reply.text),
+ revision: row.revision, mime: formats.get(row.format)
+ }]
+ }
+}
+
+function checkRows(index, replies) {
+ const records = []
+ const stale = new Set()
+ const verified = new Map()
+ for (const [at, row] of index.rows.entries()) {
+ const reply = replies.get(row.turnId)
+ if (!reply || reply.messageIndex !== row.messageIndex || (reply.revision ??= digest(reply.text)) !== row.revision) {
+ stale.add(row.turnId)
+ continue
+ }
+ records.push({ row, reply, at })
+ }
+ records.sort((a, b) => b.row.messageIndex - a.row.messageIndex || b.at - a.at)
+ for (const { row, reply } of records) {
+ if (!stale.has(row.turnId)) verified.set(row.id, replyRecord(row, reply))
+ }
+ return { verified, stale }
+}
+
+/** Dedicated synchronous delivery domain; ordinary chat snapshots and events are unchanged.
+ * The native writer lock is already held by the caller (the workbench owner). */
+export function createDeliveryRecords({ dataDir, validSid, ledgerKey, active, closing, blocked, cached, classify, attachedIndex, hasMedia }) {
+ const ambiguous = new Set()
+
+ function view(sid, use) {
+ if (!validSid(sid)) throw new HttpError(400, 'invalid_session_id')
+ if (closing()) throw new HttpError(503, 'chat_closed')
+ if (blocked(sid) || ambiguous.has(sid)) throw deliveryStorageError()
+ try {
+ return withDeliveryFiles(dataDir, sid, files => {
+ const source = files?.readMain()
+ const expected = cached(sid)
+ if (!source) throw expected ? deliveryStorageError() : missing()
+ const session = source.value
+ if (!object(session) || session.id !== sid || typeof session.title !== 'string' ||
+ !time(session.createdAt) || !time(session.updatedAt)) throw deliveryStorageError()
+ // Desktop cache hydration may include a compacted prefix. Its read-only projection
+ // deliberately ignores that cache; Web writers must match the confirmed native file.
+ if (expected && !isDeepStrictEqual(session, Object.fromEntries(Object.entries(expected).filter(([, value]) => value !== undefined)))) {
+ throw deliveryStorageError()
+ }
+ const messages = nativeMessages(files, sid, session)
+ if (!Object.hasOwn(session, ledgerKey)) {
+ const ownsDeliveries = Object.hasOwn(session, 'delivered')
+ const records = ownsDeliveries ? desktopDeliveryRecords(sid, messages, session.delivered) : []
+ const kind = ownsDeliveries || session.compacted !== undefined || classify(session) !== 'legacy_text'
+ ? 'unsupported_history' : 'read_only_session'
+ return use({ records, kind })
+ }
+ const unsupported = () => use({ records: [], kind: 'unsupported_history' })
+ if (!source.privateMode) throw deliveryStorageError()
+ if (session.compacted !== undefined || classify(session) !== 'text' || !hasMedia(expected ?? session, session)) return unsupported()
+ const replies = webReplies(session, session[ledgerKey], attachedIndex(session))
+ if (!replies) return unsupported()
+ const index = metadata(files.readMetadata(), sid)
+ return use({ files, replies, index, ...checkRows(index, replies) })
+ })
+ } catch (error) {
+ if (error instanceof HttpError) throw error
+ throw deliveryStorageError()
+ }
+ }
+
+ function deliverySnapshot(sid) {
+ return view(sid, ({ records, replies, verified, stale }) => ({
+ records: records ?? [...verified.values()],
+ candidates: replies && !active(sid) ? [...replies.values()].reverse().filter(reply => !stale.has(reply.turnId))
+ .map(({ turnId, messageIndex }) => ({ turnId, messageIndex })) : []
+ }))
+ }
+
+ function listDeliveryRecords(sid) { return deliverySnapshot(sid).records }
+
+ function exportReplyDelivery(sid, raw, verifyOwner) {
+ if (!validSid(sid)) throw new HttpError(400, 'invalid_session_id')
+ const { turnId, format } = exportInput(raw, validSid)
+ // This callback can reenter application code. Check writer state only after it returns.
+ if (verifyOwner !== undefined) {
+ const verified = verifyOwner(sid)
+ if (verified === false || typeof verified?.then === 'function') throw new HttpError(401, 'unauthorized')
+ }
+ if (active(sid)) throw new HttpError(409, 'turn_in_progress')
+ let writing = false
+ try {
+ return view(sid, ({ files, replies, index, verified, stale, kind }) => {
+ if (!replies) throw new HttpError(409, kind)
+ if (stale.size) throw deliveryStorageError()
+ const reply = replies.get(turnId)
+ if (!reply) throw ineligible()
+ const id = groupId(sid, 'reply', turnId, format)
+ const prior = verified.get(id)
+ if (prior) {
+ if (prior.turnId !== turnId || !prior.entries[0].name.endsWith(`.${format}`)) throw deliveryStorageError()
+ return { created: false, record: prior }
+ }
+ if (index.rows.length >= 512) throw deliveryStorageError()
+ const row = { id, turnId, format, messageIndex: reply.messageIndex, revision: reply.revision ?? digest(reply.text) }
+ writing = true
+ files.saveMetadata(JSON.stringify({ ...index, rows: [...index.rows, row] }))
+ return { created: true, record: replyRecord(row, reply) }
+ })
+ } catch (error) {
+ if (writing) ambiguous.add(sid)
+ throw error
+ }
+ }
+
+ function readReplyDelivery(sid, id, index) {
+ if (!validSid(sid) || !validGroupId(id) || index !== 0) return null
+ try {
+ return view(sid, ({ replies, verified }) => {
+ const record = verified?.get(id)
+ if (!record) return null
+ const { name, revision, mime } = record.entries[0]
+ return { name, bytes: Buffer.from(replies.get(record.turnId).text, 'utf8'), revision, mime }
+ })
+ } catch (error) {
+ if (error instanceof HttpError && [404, 413, 503].includes(error.status)) return null
+ throw error
+ }
+ }
+
+ return { deliverySnapshot, listDeliveryRecords, exportReplyDelivery, readReplyDelivery }
+}
diff --git a/apps/headless/src/chat/text-turns.mjs b/apps/headless/src/chat/text-turns.mjs
index b20c8ef4..a760c8b3 100644
--- a/apps/headless/src/chat/text-turns.mjs
+++ b/apps/headless/src/chat/text-turns.mjs
@@ -4,6 +4,7 @@ import { consumeModelStep, createChatStore, isValidSessionId, modelMessages } fr
import { connectProvider } from '../business/model-connection.mjs'
import { chatScope } from '../events/index.mjs'
import { HttpError } from '../http/policy.mjs'
+import { createDeliveryRecords } from './delivery-records.mjs'
import { confirmPreferenceStorage, preflightPreferenceStorage } from './session-preferences-storage.mjs'
import {
PREFERENCES_META, checkPreferenceRevision, firstTitle, listPreferenceFields, managedModel, preferenceChanges,
@@ -185,7 +186,7 @@ function appendNotice(notices, after, status, reason, text) {
/** One instance per data directory and journal. The owner closes the journal after awaiting close().
* resolveRole only reads trusted library state and returns the current enabled role projection. */
-export function createTextTurns({ dataDir, settings, journal, version, allowedOrigins, resolveRole, uploads }) {
+export function createTextTurns({ dataDir, settings, journal, version, allowedOrigins, resolveRole, uploads, deliveries }) {
if (typeof settings?.getProvider !== 'function' || !['snapshot', 'snapshotAndSubscribe', 'publishChat', 'publishSessionsChanged']
.every(fn => typeof journal?.[fn] === 'function')) throw new TypeError('Text turns require settings and an event journal')
if (resolveRole !== undefined && typeof resolveRole !== 'function') throw new TypeError('resolveRole must be a function')
@@ -202,12 +203,14 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
const active = new Map()
const unconfirmed = new Map() // Quarantine ambiguous writes until restart; never replay a charged request.
const hidden = new Set() // A failed create may leave a session only in the core's cache.
+ const deliverySessions = deliveries === true ? new Map() : undefined
let closing
function lookupSession(sid) {
warned = false
const s = hidden.has(sid) ? undefined : store.getSession(sid)
if (s && warned) incomplete.add(s)
+ if (s && Object.hasOwn(s, META)) deliverySessions?.set(sid, s)
return s
}
@@ -283,6 +286,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
s = store.ensureSession(id, role ? { personaId: role.id, model: role.model || undefined } : undefined)
s[META] = { version: 1, messageCount: 0, requests: [] }
store.saveStrict(id)
+ deliverySessions?.set(id, s)
} catch {
hidden.add(id)
throw storageError()
@@ -657,8 +661,18 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr
const s = lookupSession(sid)
return !!s && compatibility(s) === 'text'
}
+ const records = deliverySessions && createDeliveryRecords({
+ dataDir, validSid, ledgerKey: META,
+ active: sid => active.has(sid), closing: () => Boolean(closing),
+ blocked: sid => hidden.has(sid) || unconfirmed.has(sid) || incomplete.has(deliverySessions.get(sid)),
+ cached: sid => deliverySessions.get(sid), classify: compatibility, attachedIndex,
+ hasMedia(cached, source) {
+ const index = attachedIndex(source)
+ return !index || (!mediaUnconfirmed.has(cached) && attachments.available(index))
+ }
+ })
return Object.freeze({
create, list, attach, snapshot, send, stop, close, getPreferences, patchPreferences,
- attachmentScope, describeCommittedAttachment, readCommittedAttachment, hasBrowserSession
+ attachmentScope, describeCommittedAttachment, readCommittedAttachment, hasBrowserSession, ...records
})
}
diff --git a/apps/headless/src/deliveries/routes.mjs b/apps/headless/src/deliveries/routes.mjs
new file mode 100644
index 00000000..1c4ae836
--- /dev/null
+++ b/apps/headless/src/deliveries/routes.mjs
@@ -0,0 +1,102 @@
+import { HttpError, json, readJson, responseHeaders } from '../http/policy.mjs'
+import { createDeliveries } from './service.mjs'
+
+const address = /^\/api\/v1\/chats\/([A-Za-z0-9_-]{1,128})\/deliveries(?:\/(reply)|\/(d_[a-f0-9]{32})\/items\/(0|[1-9][0-9]?)\/(download|preview|locate))?$/
+const maxDataReplies = 4
+const maxSlowTransferMs = 30_000
+const fileFaults = Object.freeze({
+ ERR_DELIVERY_FILE_INVALID: [400, 'invalid_delivery'], ERR_DELIVERY_FILE_CONFLICT: [409, 'delivery_changed'],
+ ERR_DELIVERY_FILE_UNSUPPORTED: [415, 'delivery_unsupported'], AUTH_FAILED: [401, 'auth']
+})
+function fault(err) {
+ if (err instanceof HttpError) return [err.status, err.code]
+ if (Object.hasOwn(fileFaults, err?.code)) return fileFaults[err.code]
+ if (err?.code === 'ERR_WORKSPACE_UNAVAILABLE') return [404, 'delivery_not_found']
+ // Never serialize a local error message, absolute path, model reply or file contents.
+ return [503, 'delivery_unavailable']
+}
+function getRevision(req) {
+ const values = req.headersDistinct['if-match']
+ if (!values?.length) throw new HttpError(428, 'delivery_revision_required')
+ if (values.length !== 1 || !/^"[a-f0-9]{64}"$/u.test(values[0]) || values[0].length !== 66) throw new HttpError(400, 'invalid_delivery_revision')
+ return values[0].slice(1, -1)
+}
+function inlineName(name) {
+ const ascii = name.replace(/[^A-Za-z0-9._ -]/gu, '_')
+ const encoded = encodeURIComponent(name).replace(/['()*]/g, ch => '%' + ch.codePointAt(0).toString(16).toUpperCase())
+ return `filename="${ascii}"; filename*=UTF-8''${encoded}`
+}
+function sendFile(req, res, op, revision, result) {
+ res.writeHead(200, { ...responseHeaders, 'content-security-policy': "sandbox; default-src 'none'; frame-ancestors 'none'; base-uri 'none'",
+ 'cross-origin-resource-policy': 'same-origin', 'content-type': result.mime, 'content-length': result.bytes.length,
+ 'content-disposition': `${op === 'download' ? 'attachment' : 'inline'}; ${inlineName(result.name)}`, etag: `"${revision}"` })
+ res.end(req.method === 'HEAD' ? undefined : result.bytes)
+}
+function cursorFor(op, raw) {
+ if (!raw) return null
+ const match = /^\?cursor=([A-Za-z0-9_-]{1,160})$/u.exec(raw)
+ if (op !== 'list' || !match || match[0] !== raw) throw new HttpError(400, 'unexpected_query')
+ return match[1]
+}
+
+/** No mounted directory is directly served. Even with a valid revision clients must own the
+ * exact session, record and index. A slow transfer keeps its bounded data slot until it closes. */
+export function deliveryRoutes({ turns, files }) {
+ const service = createDeliveries({ turns, files })
+ let active = 0, dataReplies = 0
+ return async (req, res, { auth, policy }) => {
+ const raw = req.url ?? '', q = raw.indexOf('?'), path = q < 0 ? raw : raw.slice(0, q)
+ const resource = address.exec(path)
+ if (!resource || resource[0] !== path) return false
+ const [, sid, reply, gid, item, action] = resource, op = reply ?? action ?? 'list'
+ const write = op === 'reply' || op === 'locate', binary = op === 'download' || op === 'preview'
+ const methods = write ? ['POST'] : binary ? ['GET','HEAD'] : ['GET']
+ let counted = false, dataSlot = false, timer
+ const releaseData = () => {
+ if (!dataSlot) return
+ dataSlot = false; dataReplies--; clearTimeout(timer)
+ res.off('finish', releaseData); res.off('close', releaseData)
+ }
+ try {
+ policy.check(req, write)
+ const cookie = policy.cookie(req)
+ const authorize = () => write ? auth.authenticate(cookie, req.headers['x-deva-csrf']) : auth.authenticate(cookie)
+ authorize()
+ if (!methods.includes(req.method)) { json(res, 405, { error: 'method' }, { allow: methods.join(', ') }); return true }
+ const cursor = cursorFor(op, q < 0 ? '' : raw.slice(q))
+ if (res.destroyed || res.writableEnded) return true
+ if (active >= 8 || (binary && dataReplies >= maxDataReplies)) throw new HttpError(429, 'delivery_busy')
+ active++; counted = true
+ if (binary) {
+ if (req.headers.range !== undefined) throw new HttpError(416, 'delivery_range_unsupported')
+ dataReplies++; dataSlot = true; res.once('finish', releaseData); res.once('close', releaseData)
+ timer = setTimeout(() => res.destroy(), maxSlowTransferMs); timer.unref()
+ const rev = getRevision(req)
+ const record = await service.resolveItem(sid, gid, Number(item), rev, op)
+ authorize()
+ if (!res.destroyed) sendFile(req, res, op, rev, record)
+ } else {
+ let result
+ if (op === 'list') result = await service.list(sid, cursor)
+ else {
+ const body = await readJson(req, 1024)
+ authorize()
+ if (op === 'reply') {
+ if (Object.keys(body).length !== 2 || !Object.hasOwn(body, 'turnId') || !Object.hasOwn(body, 'format')) throw new HttpError(400, 'invalid_delivery_export')
+ result = await service.publish(sid, body, authorize)
+ } else {
+ if (Object.keys(body).length !== 1 || !Object.hasOwn(body, 'revision')) throw new HttpError(400, 'invalid_delivery_revision')
+ result = await service.resolveItem(sid, gid, Number(item), body.revision, op)
+ }
+ }
+ authorize()
+ if (!res.destroyed) json(res, op === 'reply' && result.created ? 201 : 200, result)
+ }
+ } catch (err) {
+ releaseData()
+ const [status, code] = fault(err)
+ if (!res.destroyed && !res.headersSent) json(res, status, { error: code }, write ? { connection: 'close' } : {})
+ } finally { if (counted) active-- }
+ return true
+ }
+}
diff --git a/apps/headless/src/deliveries/service.mjs b/apps/headless/src/deliveries/service.mjs
new file mode 100644
index 00000000..88e12434
--- /dev/null
+++ b/apps/headless/src/deliveries/service.mjs
@@ -0,0 +1,139 @@
+import { createHash } from 'node:crypto'
+import { HttpError } from '../http/policy.mjs'
+
+const groupPattern = /^d_[a-f0-9]{32}$/u
+const digestPattern = /^[a-f0-9]{64}$/u
+const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u
+const itemStatuses = new Set(['ready', 'missing', 'too-large', 'unsupported'])
+const itemKinds = new Set(['text', 'image', 'document'])
+const images = new Set(['image/png', 'image/jpeg', 'image/webp'])
+const mimeTypes = new Set(['text/plain', 'text/markdown', 'text/csv', 'application/pdf', ...images,
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation'])
+const maxBytes = 8 * 1024 * 1024
+const maxGroups = 40, maxProjectItems = 20
+const hash = input => createHash('sha256').update(JSON.stringify(input)).digest('hex')
+const exact = (value, re) => typeof value === 'string' && re.exec(value)?.[0] === value
+const notFound = () => { throw new HttpError(404, 'delivery_not_found') }
+const changed = () => { throw new HttpError(409, 'delivery_changed') }
+const invalid = () => { throw new HttpError(400, 'invalid_delivery') }
+const damaged = () => { throw new HttpError(503, 'delivery_unavailable') }
+const safeIndex = n => Number.isSafeInteger(n) && n >= 0
+const parsedMime = value => typeof value === 'string' ? value.split(';', 1)[0].toLowerCase() : ''
+
+export function safeDeliveryName(name) {
+ return typeof name === 'string' && name.isWellFormed() && name.length > 0 && Buffer.byteLength(name) <= 255 &&
+ name.trim() === name && !name.startsWith('.') && !name.endsWith('.') &&
+ !/[\\/:<>"|?*\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u.test(name) && !/^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(?:\s*\.|$)/iu.test(name)
+}
+function bindRevision(sid, gid, index, base) {
+ // Reply hashes are native SHA-256 digests, project file revisions are opaque r_ tags.
+ // Neither is returned directly: the HTTP projection binds both to this session, group and item.
+ if (!exact(base, digestPattern) && !exact(base, /^r_[a-f0-9]{64}$/u)) damaged()
+ return hash(['deva:delivery-revision:v1', sid, gid, index, base])
+}
+function snapshotProof(sid, records) { return hash(['deva:delivery-page:v1', sid, records.map(r => r.id)]) }
+function pageOffset(raw, max, proof) {
+ if (raw === null) return 0
+ if (!exact(raw, /^[a-zA-Z0-9_-]{1,160}$/u)) invalid()
+ let value
+ try {
+ const bytes = Buffer.from(raw, 'base64url')
+ if (bytes.toString('base64url') !== raw) invalid()
+ value = JSON.parse(bytes.toString('utf8'))
+ } catch { invalid() }
+ if (!Array.isArray(value) || value.length !== 2 || !safeIndex(value[0]) || value[0] === 0 || !exact(value[1], digestPattern)) invalid()
+ if (value[1] !== proof || value[0] >= max) throw new HttpError(409, 'deliveries_changed')
+ return value[0]
+}
+
+/** Called only with records selected from the owner's confirmed native conversation. Absolute
+ * desktop file names are kept on the host. The client sees a group ID and the ORIGINAL item index. */
+export function createDeliveries({ turns, files }) {
+ function source(sid) {
+ const snap = turns.deliverySnapshot(sid)
+ if (!Array.isArray(snap?.records) || !Array.isArray(snap.candidates) || snap.records.length > 1024 || snap.candidates.length > 256) damaged()
+ return snap
+ }
+ async function descriptor(sid, record, entry) {
+ const { id, origin } = record, { index } = entry
+ if (!exact(id, groupPattern) || !safeIndex(index) || index > 19) damaged()
+ const raw = origin === 'reply' ? {
+ name: entry.name, size: entry.size, revision: entry.revision, kind: 'text', status: 'ready',
+ canDownload: true, canPreview: false, canLocate: false
+ } : origin === 'desktop' && files ? await files.inspect(entry.path) : null
+ if (!raw || !safeDeliveryName(raw.name)) return null
+ if (!itemKinds.has(raw.kind) || !itemStatuses.has(raw.status) || (raw.size !== null && !safeIndex(raw.size))) damaged()
+ const ready = raw.status === 'ready'
+ const revision = ready ? bindRevision(sid, id, index, raw.revision) : null
+ const item = { index, name: raw.name, size: raw.size, status: raw.status, kind: raw.kind, revision,
+ canDownload: ready && raw.canDownload === true, canPreview: ready && raw.kind === 'image' && raw.canPreview === true,
+ canLocate: ready && origin === 'desktop' && raw.canLocate === true }
+ return { item, base: raw.revision }
+ }
+ async function project(sid, record) {
+ if (!Array.isArray(record.entries) || record.entries.length > 20 || !['reply','desktop'].includes(record.origin)) damaged()
+ const items = []
+ for (const entry of record.entries) {
+ const found = await descriptor(sid, record, entry)
+ if (found) items.push(found.item)
+ }
+ if (!items.length) return null
+ return { id: record.id, origin: record.origin, ...(exact(record.turnId, uuid) ? { turnId: record.turnId } : {}),
+ ...(safeIndex(record.messageIndex) ? { messageIndex: record.messageIndex } : {}), items }
+ }
+ async function list(sid, cursor) {
+ const { records, candidates } = source(sid)
+ const proof = snapshotProof(sid, records)
+ let at = pageOffset(cursor, records.length, proof), inspected = 0, visited = 0
+ const groups = []
+ for (; at < records.length && visited < maxGroups; at++) {
+ const rec = records[at]
+ if (!exact(rec.id, groupPattern) || !Array.isArray(rec.entries) || rec.entries.length > 20) damaged()
+ const cost = files && rec.origin === 'desktop' ? rec.entries.length : 0
+ if (visited && inspected + cost > maxProjectItems) break
+ inspected += cost; visited++
+ const group = await project(sid, rec)
+ if (group) groups.push(group)
+ }
+ return { groups, candidates: candidates.map(({ turnId, messageIndex }) => {
+ if (!exact(turnId, uuid) || !safeIndex(messageIndex)) damaged()
+ return { turnId, messageIndex }
+ }), nextCursor: at < records.length ? Buffer.from(JSON.stringify([at, proof])).toString('base64url') : null }
+ }
+ async function publish(sid, body, authorize) {
+ const result = await turns.exportReplyDelivery(sid, body, authorize)
+ if (typeof result?.created !== 'boolean' || result.record?.origin !== 'reply') damaged()
+ const group = await project(sid, result.record)
+ if (!group || group.items.length !== 1) damaged()
+ return { created: result.created, group }
+ }
+ async function resolveItem(sid, gid, index, revision, op) {
+ if (!exact(gid, groupPattern) || !safeIndex(index) || index > 19 || !exact(revision, digestPattern)) invalid()
+ const { records } = source(sid), record = records.find(r => r.id === gid)
+ const entry = record?.entries.find(e => e.index === index)
+ if (!entry) notFound()
+ const desc = await descriptor(sid, record, entry)
+ if (!desc || desc.item.status === 'missing') notFound()
+ if (desc.item.status === 'too-large') throw new HttpError(413, 'delivery_too_large')
+ if (desc.item.status !== 'ready') throw new HttpError(415, 'delivery_unsupported')
+ if (desc.item.revision !== revision) changed()
+ if (op === 'locate') {
+ if (!desc.item.canLocate) throw new HttpError(415, 'delivery_no_location')
+ const spot = await files.locate(entry.path, desc.base)
+ if (!exact(spot?.workspaceId, /^w_[a-f0-9]{32}$/u) || typeof spot.path !== 'string' ||
+ !spot.path.length || /[\\\p{Cc}]/u.test(spot.path) || spot.path.split('/').some(p => !p || p.startsWith('.'))) damaged()
+ return { workspaceId: spot.workspaceId, path: spot.path }
+ }
+ if (!(op === 'preview' ? desc.item.canPreview : op === 'download' && desc.item.canDownload)) throw new HttpError(415, 'delivery_unsupported')
+ const result = record.origin === 'reply' ? await turns.readReplyDelivery(sid, gid, index) : await files.read(entry.path, desc.base, op)
+ if (!result) notFound()
+ const mime = parsedMime(result.mime)
+ if (record.origin === 'reply' && result.revision !== desc.base) changed()
+ if (!mimeTypes.has(mime) || (op === 'preview' && !images.has(mime)) || !Buffer.isBuffer(result.bytes) ||
+ result.bytes.length > maxBytes || result.bytes.length !== desc.item.size || result.name !== desc.item.name) damaged()
+ return { bytes: result.bytes, name: desc.item.name, mime: mime.startsWith('text/') ? mime + '; charset=utf-8' : mime }
+ }
+ return Object.freeze({ list, publish, resolveItem })
+}
diff --git a/apps/headless/src/files/delivery-files.mjs b/apps/headless/src/files/delivery-files.mjs
new file mode 100644
index 00000000..f059cf99
--- /dev/null
+++ b/apps/headless/src/files/delivery-files.mjs
@@ -0,0 +1,136 @@
+import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
+import { extname } from 'node:path'
+import { setImmediate } from 'node:timers/promises'
+import { AVATAR_MAX_BYTES, avatarImageMime } from '../../dist/library-core.mjs'
+import { officeDeliveryMime } from './delivery-office.mjs'
+import { decodeUtf8 } from './workspace-files-fd.mjs'
+import { assertFile, readBytes, withDirectory, withFilePin, withReadablePin } from './workspace-files-pin.mjs'
+
+const text = { kind: 'text', mime: 'text/plain', maxBytes: 2 * 1024 * 1024 }
+const raster = mime => ({ kind: 'image', mime, maxBytes: AVATAR_MAX_BYTES })
+const jpeg = raster('image/jpeg')
+const pdf = { kind: 'document', mime: 'application/pdf', maxBytes: 8 * 1024 * 1024 }
+const office = (ext, subtype) => ({ ext, kind: 'document', mime: 'application/vnd.openxmlformats-officedocument.' + subtype, maxBytes: 8 * 1024 * 1024 })
+const types = new Map([
+ ['.txt', text], ['.md', text], ['.csv', text], ['.json', text],
+ ['.png', raster('image/png')], ['.jpg', jpeg], ['.jpeg', jpeg], ['.webp', raster('image/webp')], ['.pdf', pdf],
+ ['.docx', office('.docx', 'wordprocessingml.document')], ['.xlsx', office('.xlsx', 'spreadsheetml.sheet')],
+ ['.pptx', office('.pptx', 'presentationml.presentation')],
+])
+const nonText = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u
+const activeTextPrefix = /^(?:#!|%PDF-|<\?xml\b|]))/iu
+const keyPrefix = /^-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/u
+const pdfMagic = /^%PDF-(?:1\.[0-7]|2\.0)[\r\n]/u
+const revisionPattern = /^r_[0-9a-f]{64}$/u
+const cacheLimit = 128
+
+class DeliveryFileError extends Error {
+ constructor(kind, status, message) {
+ super(message)
+ this.code = `ERR_DELIVERY_FILE_${kind}`
+ this.status = this.statusCode = status
+ }
+}
+const invalid = () => new DeliveryFileError('INVALID', 400, 'Invalid delivery file request')
+const conflict = () => new DeliveryFileError('CONFLICT', 409, 'Delivery file changed or is unavailable')
+const unsupported = () => new DeliveryFileError('UNSUPPORTED', 415, 'Delivery file is not available in this format')
+const equalTag = (a, b) => timingSafeEqual(Buffer.from(a), Buffer.from(b))
+
+function metadata(name, type, info, status, revision = null) {
+ const ready = status === 'ready'
+ return {
+ name, kind: type?.kind ?? 'document', size: info && info.size <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(info.size) : null,
+ status, revision, canDownload: ready, canPreview: ready && type.kind === 'image', canLocate: ready,
+ }
+}
+function validateBytes(type, bytes) {
+ if (type === pdf) return pdfMagic.test(bytes.subarray(0, 9).toString('latin1')) ? 'ready' : 'unsupported'
+ if (type.ext) return officeDeliveryMime(type.ext, bytes) === type.mime ? 'ready' : 'unsupported'
+ if (type.kind === 'image') return avatarImageMime(bytes) === type.mime ? 'ready' : 'unsupported'
+ let content
+ try { content = decodeUtf8(bytes) } catch { return 'unsupported' }
+ const prefix = content.trimStart().slice(0, 1024)
+ if (keyPrefix.test(prefix)) return 'private'
+ return nonText.test(content) || activeTextPrefix.test(prefix) ? 'unsupported' : 'ready'
+}
+
+/** Only accept paths taken from authenticated native history, never HTTP client input. */
+export function openDeliveryFiles({ catalog }) {
+ if (typeof catalog?.resolveDeliveryPath !== 'function' || typeof catalog?.pinProject !== 'function') {
+ throw TypeError('A workspace catalog is required')
+ }
+ const signingKey = randomBytes(32)
+ // Cache only validation outcomes/signatures, not file bytes or file descriptors. A hit
+ // still re-pins the named entry and checks metadata/access; all reads bypass this cache.
+ const settled = new Map()
+ function tag(domain, key, bytes) {
+ const signer = createHmac('sha256', signingKey).update(domain).update(key)
+ if (bytes) signer.update(bytes)
+ return signer.digest('hex').slice(0, 32)
+ }
+ function content(scope, name, pin, info, type, key, metaTag, full) {
+ let outcome = full ? undefined : settled.get(key)
+ let bytes
+ if (!outcome) {
+ // PDF is attachment-only. Its classifier and signature sample just magic plus
+ // the versioned inode metadata; a real download re-reads and checks all bytes.
+ bytes = withReadablePin(pin, info, fd => readBytes(fd, info, type === pdf && !full ? 9 : undefined), scope.project)
+ const status = validateBytes(type, bytes)
+ const signed = type === pdf ? bytes.subarray(0, 9) : bytes
+ outcome = { status, revision: status === 'ready' ? `r_${metaTag}${tag('content\0', key, signed)}` : null }
+ }
+ assertFile(scope, name, info)
+ settled.delete(key)
+ settled.set(key, outcome)
+ if (settled.size > cacheLimit) settled.delete(settled.keys().next().value)
+ return { ...outcome, bytes }
+ }
+ function inspectPinned(absolute, expected, variant) {
+ const grant = catalog.resolveDeliveryPath(absolute)
+ if (!grant) return null
+ const { id, path } = grant
+ const parts = path.split('/')
+ const name = parts.pop()
+ const type = types.get(extname(name).toLowerCase())
+ return withDirectory(catalog, id, parts, scope => withFilePin(scope, name, ({ pin, info }) => {
+ if (!type || (info.mode & 0o7111n)) return { item: metadata(name, type, info, 'unsupported') }
+ if (info.size > type.maxBytes) return { item: metadata(name, type, info, 'too-large') }
+ const key = JSON.stringify([
+ // The catalog ID binds the project device/inode. A directory's birth time may be
+ // derived from ctime on older Linux; unrelated sibling edits must not retag this file.
+ id, path, scope.project.mount,
+ info.dev, info.ino, info.birthtimeNs, info.ctimeNs, info.mtimeNs, info.size, info.mode, info.uid, info.gid,
+ ].map(String))
+ const metaTag = tag('meta\0', key)
+ if (expected && !equalTag(expected.slice(2, 34), metaTag)) return null
+ const output = content(scope, name, pin, info, type, key, metaTag,
+ variant === 'download' || (variant === 'preview' && type.kind === 'image'))
+ if (output.status === 'private') return null
+ return { item: metadata(name, type, info, output.status, output.revision), id, path, type, bytes: output.bytes }
+ }, () => ({ item: metadata(name, type, null, 'missing') })))
+ }
+ function lookupRevision(absolute, expected, variant) {
+ if (typeof expected !== 'string' || expected.length !== 66 || !revisionPattern.test(expected)) throw invalid()
+ let result
+ try { result = inspectPinned(absolute, expected, variant) } catch { throw conflict() }
+ if (!result?.item.revision || !equalTag(result.item.revision, expected)) throw conflict()
+ return result
+ }
+ return Object.freeze({
+ async inspect(absolute) {
+ // Yield between cold metadata entries in the caller's bounded page scan.
+ await setImmediate()
+ try { return inspectPinned(absolute)?.item ?? null } catch { return null }
+ },
+ async read(absolute, revision, variant) {
+ if (variant !== 'download' && variant !== 'preview') throw invalid()
+ const { item, type, bytes } = lookupRevision(absolute, revision, variant)
+ if (variant === 'preview' && !item.canPreview) throw unsupported()
+ return { bytes, mime: type.mime, name: item.name }
+ },
+ async locate(absolute, revision) {
+ const { id, path } = lookupRevision(absolute, revision)
+ return { workspaceId: id, path }
+ },
+ })
+}
diff --git a/apps/headless/src/files/delivery-office.mjs b/apps/headless/src/files/delivery-office.mjs
new file mode 100644
index 00000000..4083d128
--- /dev/null
+++ b/apps/headless/src/files/delivery-office.mjs
@@ -0,0 +1,592 @@
+import { performance } from 'node:perf_hooks'
+import { inflateRawSync } from 'node:zlib'
+
+const MiB = 1024 * 1024
+const maxArchive = 8 * MiB
+const maxExpanded = 32 * MiB
+const maxEntries = 512
+const maxPart = 8 * MiB
+const maxRaster = 2 * MiB
+const maxMetadata = 4 * MiB
+const maxManifest = 256 * 1024
+const maxRelationships = 128 * 1024
+const maxMain = 2 * MiB
+const maxRatio = 250
+const maxXmlNodes = 60_000
+const maxXmlDepth = 96
+const maxAttributes = 96
+const maxPath = 240
+const maxExtra = 256
+const maxWorkMs = 250
+
+const contentTypes = '[Content_Types].xml'
+const rootRelationships = '_rels/.rels'
+const schemas = 'http://schemas.openxmlformats.org/'
+const strict = 'http://purl.oclc.org/ooxml/'
+const packageTypes = `${schemas}package/2006/content-types`
+const packageRels = `${schemas}package/2006/relationships`
+const officeRels = `${schemas}officeDocument/2006/relationships`
+const strictOfficeRels = `${strict}officeDocument/relationships`
+const appType = 'application/vnd.openxmlformats-officedocument.'
+const zipType = 'application/vnd.openxmlformats-package.'
+const msType = 'application/vnd.ms-'
+const wordType = `${appType}wordprocessingml.`
+const excelType = `${appType}spreadsheetml.`
+const pptType = `${appType}presentationml.`
+const relsType = `${zipType}relationships+xml`
+const xmlNamespace = 'http://www.w3.org/XML/1998/namespace'
+const xmlnsNamespace = 'http://www.w3.org/2000/xmlns/'
+const decodeUtf8 = new TextDecoder('utf-8', { fatal: true })
+const bad = Symbol('Invalid or unsupported Office package')
+const requireThat = valid => { if (!valid) throw bad }
+const checkTime = state => requireThat(performance.now() <= state.deadline)
+
+const formats = new Map([
+ ['.docx', {
+ mime: `${wordType}document`, main: 'word/document.xml', type: `${wordType}document.main+xml`,
+ root: 'document', namespace: 'wordprocessingml', folder: 'word', parts: [
+ [/^styles\.xml$/u, 'styles', `${wordType}styles+xml`],
+ [/^stylesWithEffects\.xml$/u, 'stylesWithEffects', `${msType}word.stylesWithEffects+xml`],
+ [/^numbering\.xml$/u, 'numbering', `${wordType}numbering+xml`],
+ [/^settings\.xml$/u, 'settings', `${wordType}settings+xml`],
+ [/^webSettings\.xml$/u, 'webSettings', `${wordType}webSettings+xml`],
+ [/^fontTable\.xml$/u, 'fontTable', `${wordType}fontTable+xml`],
+ [/^footnotes\.xml$/u, 'footnotes', `${wordType}footnotes+xml`],
+ [/^endnotes\.xml$/u, 'endnotes', `${wordType}endnotes+xml`],
+ [/^comments\.xml$/u, 'comments', `${wordType}comments+xml`],
+ [/^header[1-9][0-9]*\.xml$/u, 'header', `${wordType}header+xml`],
+ [/^footer[1-9][0-9]*\.xml$/u, 'footer', `${wordType}footer+xml`],
+ ],
+ }],
+ ['.xlsx', {
+ mime: `${excelType}sheet`, main: 'xl/workbook.xml', type: `${excelType}sheet.main+xml`,
+ root: 'workbook', namespace: 'spreadsheetml', folder: 'xl', parts: [
+ [/^worksheets\/sheet[1-9][0-9]*\.xml$/u, 'worksheet', `${excelType}worksheet+xml`],
+ [/^styles\.xml$/u, 'styles', `${excelType}styles+xml`],
+ [/^sharedStrings\.xml$/u, 'sharedStrings', `${excelType}sharedStrings+xml`],
+ [/^calcChain\.xml$/u, 'calcChain', `${excelType}calcChain+xml`],
+ [/^tables\/table[1-9][0-9]*\.xml$/u, 'table', `${excelType}table+xml`],
+ [/^drawings\/drawing[1-9][0-9]*\.xml$/u, 'drawing', `${appType}drawing+xml`],
+ ],
+ }],
+ ['.pptx', {
+ mime: `${pptType}presentation`, main: 'ppt/presentation.xml', type: `${pptType}presentation.main+xml`,
+ root: 'presentation', namespace: 'presentationml', folder: 'ppt', parts: [
+ [/^slides\/slide[1-9][0-9]*\.xml$/u, 'slide', `${pptType}slide+xml`],
+ [/^slideLayouts\/slideLayout[1-9][0-9]*\.xml$/u, 'slideLayout', `${pptType}slideLayout+xml`],
+ [/^slideMasters\/slideMaster[1-9][0-9]*\.xml$/u, 'slideMaster', `${pptType}slideMaster+xml`],
+ [/^notesSlides\/notesSlide[1-9][0-9]*\.xml$/u, 'notesSlide', `${pptType}notesSlide+xml`],
+ [/^notesMasters\/notesMaster[1-9][0-9]*\.xml$/u, 'notesMaster', `${pptType}notesMaster+xml`],
+ [/^handoutMasters\/handoutMaster[1-9][0-9]*\.xml$/u, 'handoutMaster', `${pptType}handoutMaster+xml`],
+ [/^presProps\.xml$/u, 'presProps', `${pptType}presProps+xml`],
+ [/^viewProps\.xml$/u, 'viewProps', `${pptType}viewProps+xml`],
+ [/^tableStyles\.xml$/u, 'tableStyles', `${pptType}tableStyles+xml`],
+ ],
+ }],
+])
+const commonParts = new Map([
+ ['docProps/core.xml', ['core', `${zipType}core-properties+xml`]],
+ ['docProps/app.xml', ['extended-properties', `${appType}extended-properties+xml`]],
+ ['docProps/custom.xml', ['custom-properties', `${appType}custom-properties+xml`]],
+])
+const rasterTypes = new Map([['png', 'image/png'], ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg']])
+
+const segmentIsSafe = segment => /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u.test(segment) && !segment.endsWith('.')
+
+function pathIsSafe(path) {
+ return path.length <= maxPath && (path === contentTypes || path === rootRelationships ||
+ path.split('/').every(segmentIsSafe))
+}
+
+function checkExtra(bytes, start, length, local) {
+ requireThat(length <= maxExtra)
+ const end = start + length
+ const fields = new Set()
+ for (let at = start; at < end;) {
+ requireThat(at + 4 <= end)
+ const tag = bytes.readUInt16LE(at)
+ const size = bytes.readUInt16LE(at + 2)
+ at += 4
+ requireThat(at + size <= end && !fields.has(tag))
+ fields.add(tag)
+ // Only two metadata extras that cannot change names, sizes, or file types.
+ if (tag === 0x5455) {
+ requireThat(size >= 1)
+ const flags = bytes[at]
+ requireThat((flags & ~7) === 0)
+ const count = (flags & 1) + ((flags >> 1) & 1) + ((flags >> 2) & 1)
+ requireThat(size === 1 + 4 * (local ? count : flags & 1))
+ } else if (tag === 0x7875) {
+ requireThat(size >= 5 && bytes[at] === 1)
+ const uidSize = bytes[at + 1]
+ requireThat(uidSize >= 1 && uidSize <= 8 && 3 + uidSize < size)
+ const gidSize = bytes[at + 2 + uidSize]
+ requireThat(gidSize >= 1 && gidSize <= 8 && size === 3 + uidSize + gidSize)
+ } else {
+ throw bad
+ }
+ at += size
+ }
+}
+
+function readCentral(bytes, state) {
+ // Require a single ordinary ZIP, with no prefix, suffix, comments, or Zip64.
+ const end = bytes.length - 22
+ requireThat(end >= 0 && bytes.readUInt32LE(end) === 0x06054b50 && bytes.readUInt32LE(end + 4) === 0 &&
+ bytes.readUInt16LE(end + 20) === 0)
+ const count = bytes.readUInt16LE(end + 10)
+ const start = bytes.readUInt32LE(end + 16)
+ requireThat(count >= 3 && count <= maxEntries && count === bytes.readUInt16LE(end + 8) &&
+ start > 0 && start + bytes.readUInt32LE(end + 12) === end)
+
+ const entries = new Map()
+ const names = new Set()
+ let expanded = 0
+ let at = start
+ for (let index = 0; index < count; index++) {
+ checkTime(state)
+ requireThat(at + 46 <= end && bytes.readUInt32LE(at) === 0x02014b50)
+ const version = bytes.readUInt16LE(at + 6)
+ const flags = bytes.readUInt16LE(at + 8)
+ const method = bytes.readUInt16LE(at + 10)
+ const date = bytes.readUInt32LE(at + 12)
+ const crc = bytes.readUInt32LE(at + 16)
+ const compressed = bytes.readUInt32LE(at + 20)
+ const size = bytes.readUInt32LE(at + 24)
+ const nameLength = bytes.readUInt16LE(at + 28)
+ const extra = bytes.readUInt16LE(at + 30)
+ const attrs = bytes.readUInt32LE(at + 38)
+ const offset = bytes.readUInt32LE(at + 42)
+ const next = at + 46 + nameLength + extra
+ requireThat(version >= 10 && version <= 20 && (flags & ~0x080e) === 0 &&
+ (method === 8 || (method === 0 && (flags & 6) === 0 && compressed === size)) &&
+ nameLength > 0 && nameLength <= maxPath + 1 && next <= end &&
+ bytes.readUInt32LE(at + 32) === 0 && bytes.readUInt16LE(at + 36) <= 1 && offset < start &&
+ size <= maxPart && compressed <= maxArchive && size <= maxRatio * compressed)
+ expanded += size
+ requireThat(expanded <= maxExpanded)
+ const rawName = bytes.subarray(at + 46, at + 46 + nameLength)
+ const name = rawName.toString('latin1')
+ const directory = name.endsWith('/')
+ const path = directory ? name.slice(0, -1) : name
+ const key = path.toLowerCase()
+ const fileType = (attrs >>> 28) & 15
+ const dosAttrs = attrs & 0xffff
+ requireThat(pathIsSafe(path) && !names.has(key) && (dosAttrs & ~0x37) === 0 &&
+ (fileType === 0 || fileType === (directory ? 4 : 8)) &&
+ (directory ? (size === 0 && method === 0 && crc === 0) : (dosAttrs & 16) === 0 && size > 0))
+ checkExtra(bytes, at + 46 + nameLength, extra, false)
+ names.add(key)
+ entries.set(name, { rawName, directory, offset, version, flags, method, date, crc, compressed, size })
+ at = next
+ }
+ requireThat(at === end)
+ return { entries, start }
+}
+
+function readLocals(bytes, entries, start, state) {
+ const sorted = [...entries.values()].sort((a, b) => a.offset - b.offset)
+ requireThat(sorted[0].offset === 0)
+ for (let i = 0; i < sorted.length; i++) {
+ checkTime(state)
+ const entry = sorted[i]
+ const { offset, version, flags, method, date, rawName, crc, compressed, size } = entry
+ const end = i + 1 < sorted.length ? sorted[i + 1].offset : start
+ requireThat(offset + 30 <= end && bytes.readUInt32LE(offset) === 0x04034b50 &&
+ bytes.readUInt16LE(offset + 4) === version && bytes.readUInt16LE(offset + 6) === flags &&
+ bytes.readUInt16LE(offset + 8) === method && bytes.readUInt32LE(offset + 10) === date &&
+ bytes.readUInt16LE(offset + 26) === rawName.length)
+ const extra = bytes.readUInt16LE(offset + 28)
+ const header = offset + 30 + rawName.length + extra
+ const dataEnd = header + compressed
+ requireThat(dataEnd <= end && rawName.equals(bytes.subarray(offset + 30, offset + 30 + rawName.length)))
+ checkExtra(bytes, offset + 30 + rawName.length, extra, true)
+ const matches = pos => bytes.readUInt32LE(pos) === crc && bytes.readUInt32LE(pos + 4) === compressed &&
+ bytes.readUInt32LE(pos + 8) === size
+ if (flags & 8) {
+ requireThat(matches(offset + 14) || (bytes.readUInt32LE(offset + 14) === 0 &&
+ bytes.readUInt32LE(offset + 18) === 0 && bytes.readUInt32LE(offset + 22) === 0))
+ requireThat((end - dataEnd === 12 && matches(dataEnd)) || (end - dataEnd === 16 &&
+ bytes.readUInt32LE(dataEnd) === 0x08074b50 && matches(dataEnd + 4)))
+ } else {
+ requireThat(dataEnd === end && matches(offset + 14))
+ }
+ entry.start = header
+ entry.end = dataEnd
+ }
+}
+
+// Use a local CRC to support Node 22.0 as well as versions with zlib.crc32().
+const crcTable = Uint32Array.from({ length: 256 }, (_, i) => {
+ for (let bit = 0; bit < 8; bit++) i = (i >>> 1) ^ ((i & 1) ? 0xedb88320 : 0)
+ return i
+})
+
+function readStructure(bytes, entry, limit, state) {
+ checkTime(state)
+ requireThat(entry && entry.size <= limit && entry.compressed <= limit)
+ state.metadata += entry.size
+ requireThat(state.metadata <= maxMetadata)
+ const input = bytes.subarray(entry.start, entry.end)
+ let data = input
+ if (entry.method === 8) {
+ // maxOutputLength is enforced by zlib's synchronous wrapper; info confirms
+ // exactly one raw deflate stream consumed the entire ZIP member.
+ const { buffer, engine } = inflateRawSync(input, { maxOutputLength: entry.size, info: true })
+ requireThat(engine.bytesWritten === input.length)
+ data = buffer
+ }
+ requireThat(data.length === entry.size)
+ let crc = 0xffffffff
+ for (let i = 0; i < data.length; i++) crc = (crc >>> 8) ^ crcTable[(crc ^ data[i]) & 255]
+ requireThat((~crc >>> 0) === entry.crc)
+ checkTime(state)
+ return data
+}
+
+const xmlChars = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u
+const whitespace = /[ \t\r\n]*/uy
+const xmlName = /[A-Za-z_][A-Za-z0-9_.-]*(?::[A-Za-z_][A-Za-z0-9_.-]*)?/uy
+const xmlDeclaration = /<\?xml[ \t\r\n]+version[ \t\r\n]*=[ \t\r\n]*(?:"1\.0"|'1\.0')(?:[ \t\r\n]+encoding[ \t\r\n]*=[ \t\r\n]*(?:"[Uu][Tt][Ff]-8"|'[Uu][Tt][Ff]-8'))?(?:[ \t\r\n]+standalone[ \t\r\n]*=[ \t\r\n]*(?:"(?:yes|no)"|'(?:yes|no)'))?[ \t\r\n]*\?>/uy
+const entity = /&(?:amp|lt|gt|apos|quot|#[0-9]{1,7}|#x[0-9A-Fa-f]{1,6});/uy
+const references = new Map([['&', '&'], ['<', '<'], ['>', '>'], ['"', '"'], [''', "'"]])
+
+function xmlValue(value, decoded) {
+ let start = 0
+ let result = ''
+ for (let at = value.indexOf('&'); at !== -1; at = value.indexOf('&', start)) {
+ entity.lastIndex = at
+ const match = entity.exec(value)?.[0]
+ requireThat(match)
+ let character = references.get(match)
+ if (character === undefined) {
+ const hex = match[2] === 'x'
+ const code = Number.parseInt(match.slice(hex ? 3 : 2, -1), hex ? 16 : 10)
+ requireThat(code === 9 || code === 10 || code === 13 || (code >= 32 && code <= 0xd7ff) ||
+ (code >= 0xe000 && code <= 0xfffd) || (code >= 0x10000 && code <= 0x10ffff))
+ if (decoded) character = String.fromCodePoint(code)
+ }
+ if (decoded) result += value.slice(start, at) + character
+ start = entity.lastIndex
+ }
+ return decoded ? result + value.slice(start) : undefined
+}
+
+function qualified(name, bindings, attribute) {
+ const colon = name.indexOf(':')
+ if (colon === -1) return [attribute ? '' : bindings[''] ?? '', name]
+ const prefix = name.slice(0, colon)
+ const namespace = bindings[prefix]
+ requireThat(namespace && prefix !== 'xmlns')
+ return [namespace, name.slice(colon + 1)]
+}
+
+// Parse just bounded UTF-8 XML. DTDs, custom entities and processing instructions
+// have no role here; there is no entity resolver or external I/O.
+function readXml(data, state, { element, strictNodes = false }) {
+ const xml = decodeUtf8.decode(data)
+ requireThat(!xmlChars.test(xml))
+ const stack = []
+ const base = Object.assign(Object.create(null), { xml: xmlNamespace })
+ let root = false
+ let at = 0
+ function take(pattern) {
+ pattern.lastIndex = at
+ const value = pattern.exec(xml)?.[0]
+ if (value !== undefined) at = pattern.lastIndex
+ return value
+ }
+ if (xml.startsWith(''))
+ xmlValue(value, false)
+ }
+ at += value.length
+ continue
+ }
+ if (xml.startsWith('