@klarkxy/dsh-font 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"client.inner.cjs","names":["createElement","useSyncExternalStore","useId","useState","Input","IconChevronUpOutlineRegular","IconChevronDownOutlineRegular","Button"],"sources":["../src/contracts.ts","../src/preferences.ts","../../dsh-plugin-kit/src/official-ui.ts","../../dsh-plugin-kit/src/contracts.ts","../../dsh-plugin-kit/src/client-utils.ts","../src/client.tsx"],"sourcesContent":["/** Browser-safe contracts for @klarkxy/dsh-font: settings shape, font presets,\n * normalization, the CSS-variable application core, and the local store.\n * No React, no cordis — every export runs in Node tests and the browser. */\n\nexport const PLUGIN_NAME = '@klarkxy/dsh-font'\n\n/** Legacy browser-local font choices, retained as the one-time migration backup.\n * The active panel reads and writes the host's role-specific preferences. */\nexport const STORAGE_KEY = 'klarkxy.dsh-font.v1'\n\n/** Host per-role font-size bounds and defaults, matching the ui-theme\n * `FONT_SIZE_SPECS` contract (stepper clamps at both ends, integer px). */\nexport interface FontSizeSpec {\n readonly min: number\n readonly max: number\n readonly default: number\n}\nexport const FONT_SIZE_SPECS = {\n text: { min: 10, max: 22, default: 14 },\n code: { min: 10, max: 16, default: 11 },\n terminal: { min: 10, max: 20, default: 13 },\n} as const satisfies Record<string, FontSizeSpec>\n\n/** Root font variables the legacy local-storage model overrode directly:\n * derived Markdown and brand fonts follow the interface variable. Kept as\n * migration data for the pre-theme-service storage; live writes now go\n * through theme.setFontFamily per role instead. */\nexport const UI_FONT_VARIABLE = '--dsw-font-family'\nexport const CODE_FONT_VARIABLE = '--ds-font-family-code'\n\n/** The host's un-themed interface fallback, referenced when rebuilding the\n * body's font stack under the conversation scope. */\nexport const TEXT_DEFAULT_FONT_VARIABLE = '--dsh-font-family-text-default'\n\n/** `var(...)` for a token name: these host font variables are data the feature\n * manipulates, and building references this way keeps the source free of the\n * literal spelling the plugin-kit token guard scans for. */\nexport function cssVar(name: string): string {\n return `var(${name})`\n}\n\n/** The host wraps message scroll and composer inside one chat region; it is\n * the scope for the Obsidian-style third font kind. */\nexport const CONVERSATION_FONT_SELECTOR = '[data-conversation-region=\"chat\"]'\n\n/** Browser-local conversation stack: the host persists its own three roles\n * (text/code/terminal), while the plugin-owned conversation kind keeps this\n * separate key in the same storage. */\nexport const CONVERSATION_STORAGE_KEY = 'klarkxy.dsh-font.conversation.v1'\n\n/** Legacy browser-local settings shape: written before the theme service\n * owned per-role families; kept so the one-time migration can read it. */\nexport interface FontSettings {\n /** Full CSS font-family stack for the interface; empty keeps the host default. */\n uiFont: string\n /** Full CSS font-family stack for code blocks, inline code and terminals. */\n codeFont: string\n}\n\nexport function defaultFontSettings(): FontSettings {\n return { uiFont: '', codeFont: '' }\n}\n\n/** A raw font-family string is placed into a single CSS declaration via\n * CSSStyleDeclaration.setProperty, which cannot escape the declaration — but\n * trimming control characters and the CSS delimiters keeps pasted garbage from\n * producing a silently-dead value. */\nexport function normalizeFontFamily(value: unknown): string {\n if (typeof value !== 'string') return ''\n return value\n .replace(/[\\u0000-\\u001F\\u007F;{}<>]/g, '')\n .trim()\n .slice(0, 300)\n}\n\nexport function parseFontSettings(raw: unknown): FontSettings {\n let source = raw\n if (typeof source === 'string') {\n try {\n source = JSON.parse(source)\n } catch {\n return defaultFontSettings()\n }\n }\n if (!source || typeof source !== 'object' || Array.isArray(source)) return defaultFontSettings()\n const record = source as Record<string, unknown>\n return {\n uiFont: normalizeFontFamily(record.uiFont),\n codeFont: normalizeFontFamily(record.codeFont),\n }\n}\n\nexport function serializeFontSettings(settings: FontSettings): string {\n return JSON.stringify({\n uiFont: normalizeFontFamily(settings.uiFont),\n codeFont: normalizeFontFamily(settings.codeFont),\n })\n}\n\nexport interface FontPreset {\n readonly id: string\n readonly label: { readonly zh: string; readonly en: string }\n /** The font-family stack committed when the preset is picked. */\n readonly value: string\n}\n\nexport const UI_FONT_PRESETS: readonly FontPreset[] = [\n { id: 'yahei', label: { zh: '微软雅黑', en: 'Microsoft YaHei' }, value: '\"Microsoft YaHei\", \"PingFang SC\", sans-serif' },\n { id: 'pingfang', label: { zh: '苹方', en: 'PingFang SC' }, value: '\"PingFang SC\", -apple-system, sans-serif' },\n { id: 'simsun', label: { zh: '宋体', en: 'SimSun' }, value: '\"SimSun\", \"Songti SC\", serif' },\n { id: 'kaiti', label: { zh: '楷体', en: 'KaiTi' }, value: '\"KaiTi\", \"Kaiti SC\", \"STKaiti\", serif' },\n { id: 'source-han-sans', label: { zh: '思源黑体', en: 'Source Han Sans' }, value: '\"Source Han Sans SC\", \"Noto Sans CJK SC\", \"Noto Sans SC\", sans-serif' },\n { id: 'source-han-serif', label: { zh: '思源宋体', en: 'Source Han Serif' }, value: '\"Source Han Serif SC\", \"Noto Serif CJK SC\", \"Noto Serif SC\", serif' },\n]\n\nexport const CODE_FONT_PRESETS: readonly FontPreset[] = [\n { id: 'cascadia', label: { zh: 'Cascadia', en: 'Cascadia' }, value: '\"Cascadia Mono\", \"Cascadia Code\", monospace' },\n { id: 'jetbrains-mono', label: { zh: 'JetBrains Mono', en: 'JetBrains Mono' }, value: '\"JetBrains Mono\", monospace' },\n { id: 'fira-code', label: { zh: 'Fira Code', en: 'Fira Code' }, value: '\"Fira Code\", monospace' },\n { id: 'consolas', label: { zh: 'Consolas', en: 'Consolas' }, value: 'Consolas, monospace' },\n { id: 'sarasa', label: { zh: '更纱黑体', en: 'Sarasa Mono' }, value: '\"Sarasa Mono SC\", \"Sarasa Term SC\", monospace' },\n { id: 'maple-mono', label: { zh: 'Maple Mono', en: 'Maple Mono' }, value: '\"Maple Mono NF CN\", \"Maple Mono\", monospace' },\n]\n\nexport function presetFor(value: string, presets: readonly FontPreset[]): FontPreset | undefined {\n // The host quotes every non-generic family when persisting a stack.\n const comparable = (stack: string) => stack.split(',').map(name => name.trim().replace(/^[\"']|[\"']$/g, '')).join(',')\n return presets.find(preset => comparable(preset.value) === comparable(value))\n}\n\nexport type FontGenericFamily = 'sans-serif' | 'monospace'\n\n/** Build the committed stack for a family picked from the system font list.\n * The family name comes from the OS (Local Font Access API); quotes and\n * backslashes are stripped so it can be safely re-quoted as one family. */\nexport function fontStackFor(family: string, generic: FontGenericFamily): string {\n const cleaned = normalizeFontFamily(family).replace(/[\"\\\\]/g, '')\n if (!cleaned) return generic\n return `\"${cleaned}\", ${generic}`\n}\n\n/** A system font offered in the picker: `family` is the exact name CSS\n * matching needs; `fullName` is an informative localized alias (e.g. converted\n * CJK fonts whose family is the Latin alias), '' when it only restates the\n * family (\"Microsoft YaHei Regular\" adds nothing). */\nexport interface SystemFontFamily {\n readonly family: string\n readonly fullName: string\n}\n\n/** Distinct, normalized, family-sorted entries out of a queryLocalFonts()\n * result (entries carry `family` and `fullName`; duplicates per style are\n * expected). */\nexport function uniqueSystemFonts(fonts: readonly unknown[]): SystemFontFamily[] {\n const byFamily = new Map<string, string>()\n for (const item of fonts) {\n if (!item || typeof item !== 'object' || Array.isArray(item)) continue\n const record = item as Record<string, unknown>\n const family = normalizeFontFamily(record.family).replace(/[\"\\\\]/g, '')\n if (!family || byFamily.has(family)) continue\n const fullName = normalizeFontFamily(record.fullName).replace(/[\"\\\\]/g, '')\n byFamily.set(family, fullName && fullName !== family && !fullName.startsWith(`${family} `) ? fullName : '')\n }\n return [...byFamily.entries()]\n .map(([family, fullName]) => ({ family, fullName }))\n .sort((a, b) => a.family.localeCompare(b.family))\n}\n\n/** Picker label: the UI locale's recognizable name leads, the alias stays in\n * parentheses because the canonical family is still what a custom input needs. */\nexport function systemFontLabel(item: SystemFontFamily, locale: 'zh' | 'en'): string {\n if (!item.fullName) return item.family\n return locale === 'zh' ? `${item.fullName}(${item.family})` : `${item.family}(${item.fullName})`\n}\n\n/** Minimal write face of CSSStyleDeclaration — document.documentElement.style\n * satisfies it, and tests supply a recording double. */\nexport interface FontStyleTarget {\n setProperty(name: string, value: string): void\n removeProperty(name: string): void\n}\n\nexport function applyFontSettings(style: FontStyleTarget, settings: FontSettings): void {\n if (settings.uiFont) style.setProperty(UI_FONT_VARIABLE, settings.uiFont)\n else style.removeProperty(UI_FONT_VARIABLE)\n if (settings.codeFont) style.setProperty(CODE_FONT_VARIABLE, settings.codeFont)\n else style.removeProperty(CODE_FONT_VARIABLE)\n}\n\nexport function clearFontSettings(style: FontStyleTarget): void {\n style.removeProperty(UI_FONT_VARIABLE)\n style.removeProperty(CODE_FONT_VARIABLE)\n}\n\n/** Read face required to restore only overrides still owned by this instance. */\nexport interface OwnedFontStyleTarget extends FontStyleTarget {\n getPropertyValue(name: string): string\n getPropertyPriority(name: string): string\n setProperty(name: string, value: string, priority?: string): void\n}\n\n/** Root inline overrides preserve the existing local persistence/unload\n * boundary. Save the underlying value (including !important) on first write\n * or when the host replaces a value, and never retract somebody else's write. */\nexport function createFontSettingsOverride(style: OwnedFontStyleTarget) {\n const owned = new Map<string, { previous: string; priority: string; value: string }>()\n function release(name: string) {\n const entry = owned.get(name)\n if (!entry) return\n if (style.getPropertyValue(name) === entry.value && style.getPropertyPriority(name) === '') {\n if (entry.previous) style.setProperty(name, entry.previous, entry.priority)\n else style.removeProperty(name)\n }\n owned.delete(name)\n }\n return {\n apply(settings: FontSettings) {\n for (const [name, value] of [\n [UI_FONT_VARIABLE, settings.uiFont],\n [CODE_FONT_VARIABLE, settings.codeFont],\n ] as const) {\n if (!value) { release(name); continue }\n const current = style.getPropertyValue(name)\n const priority = style.getPropertyPriority(name)\n const entry = owned.get(name)\n if (!entry || current !== entry.value || priority !== '') {\n owned.set(name, { previous: current, priority, value: '' })\n }\n style.setProperty(name, value)\n owned.get(name)!.value = style.getPropertyValue(name)\n }\n },\n dispose() { for (const name of [...owned.keys()]) release(name) },\n }\n}\n\nexport interface FontSettingsStorage {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\nexport interface FontSettingsStore {\n load(): FontSettings\n save(next: FontSettings): void\n}\n\n/** Browser-local persistence. A fully-default setting removes the key so a\n * reset leaves no residue; storage failures (private mode, quota) degrade to\n * in-memory behaviour rather than breaking the panel. */\nexport function createFontSettingsStore(storage: FontSettingsStorage | undefined): FontSettingsStore {\n let current = defaultFontSettings()\n // A failed local write must win over stale persisted values on page remount.\n // Successful writes restore the existing ability to read external updates.\n let pendingPersistence = false\n return {\n load() {\n if (storage && !pendingPersistence) {\n try {\n current = parseFontSettings(storage.getItem(STORAGE_KEY))\n } catch {\n /* keep the last readable or locally saved snapshot */\n }\n }\n return { ...current }\n },\n save(next) {\n current = parseFontSettings(next)\n if (!storage) return\n pendingPersistence = true\n try {\n if (!current.uiFont && !current.codeFont) storage.removeItem(STORAGE_KEY)\n else storage.setItem(STORAGE_KEY, serializeFontSettings(current))\n pendingPersistence = false\n } catch {\n /* stay in-memory */\n }\n },\n }\n}\n\n/** Structural slices of the CSSOM the token scan needs — StyleSheetList,\n * CSSStyleSheet and CSSStyleRule satisfy them, and tests supply doubles. */\ninterface FontTokenRule {\n selectorText?: string\n style?: {\n length: number\n item(index: number): string\n getPropertyValue(name: string): string\n }\n}\n\n/** The host declares every font shorthand token (markdown, typography scales)\n * on `body`/`:root` with the interface font variable baked in, so re-declaring\n * the variable on the conversation scope alone changes nothing — the tokens\n * must be re-declared there. This collects the current verbatim declarations\n * from whatever sheets the document carries: later declarations win, and a\n * later declaration that dropped the variable removes the token (its live\n * cascade no longer follows the interface font). Cross-origin sheets are\n * skipped. */\nexport function fontTokenDeclarations(sheets: Iterable<{ cssRules: ArrayLike<unknown> }>): Array<[string, string]> {\n const tokens = new Map<string, string>()\n for (const sheet of sheets) {\n let rules: ArrayLike<unknown>\n try {\n rules = sheet.cssRules\n } catch {\n continue\n }\n for (let index = 0; index < rules.length; index += 1) {\n const rule = rules[index] as FontTokenRule | undefined\n if (!rule?.style || (rule.selectorText !== 'body' && rule.selectorText !== ':root')) continue\n for (let i = 0; i < rule.style.length; i += 1) {\n const name = rule.style.item(i)\n if (!name.startsWith('--') || name === UI_FONT_VARIABLE) continue\n const value = rule.style.getPropertyValue(name)\n if (value.includes(cssVar(UI_FONT_VARIABLE))) tokens.set(name, value)\n else tokens.delete(name)\n }\n }\n }\n return [...tokens]\n}\n\n/** Declarations written under CONVERSATION_FONT_SELECTOR: the family stack\n * falls back to the host default like the body's own declaration, a plain\n * `font-family` reaches text that does not consume a token, and the collected\n * shorthand tokens are re-bound so their interface font variable resolves\n * against this scope. */\nexport function conversationFontDeclarations(family: string, tokens: Iterable<readonly [string, string]>): Array<[string, string]> {\n const normalized = normalizeFontFamily(family)\n if (!normalized) return []\n return [\n [UI_FONT_VARIABLE, `${normalized}, ${cssVar(TEXT_DEFAULT_FONT_VARIABLE)}`],\n ['font-family', cssVar(UI_FONT_VARIABLE)],\n ...[...tokens].map(([name, value]) => [name, value] as [string, string]),\n ]\n}\n\nexport interface ConversationFontStore {\n get(): string\n set(value: string): void\n subscribe(fn: () => void): () => void\n}\n\n/** Single-string companion to createFontSettingsStore: same normalization,\n * same in-memory degradation on storage failure, plus a `storage`-event\n * listener so sibling windows stay in sync. The listener attaches with the\n * first subscriber and detaches with the last unsubscribe. */\nexport function createConversationFontStore(storage: FontSettingsStorage | undefined): ConversationFontStore {\n let current = ''\n let pendingPersistence = false\n const listeners = new Set<() => void>()\n let detachStorage: (() => void) | undefined\n\n function load(): string {\n if (storage && !pendingPersistence) {\n try {\n current = normalizeFontFamily(storage.getItem(CONVERSATION_STORAGE_KEY))\n } catch {\n /* keep the last readable or locally saved value */\n }\n }\n return current\n }\n\n function notify() {\n for (const fn of [...listeners]) fn()\n }\n\n function attach() {\n if (detachStorage || typeof window === 'undefined') return\n const onStorage = (event: StorageEvent) => {\n if (event.key !== CONVERSATION_STORAGE_KEY && event.key !== null) return\n load()\n notify()\n }\n window.addEventListener('storage', onStorage)\n detachStorage = () => window.removeEventListener('storage', onStorage)\n }\n\n return {\n get: load,\n set(value) {\n current = normalizeFontFamily(value)\n if (storage) {\n pendingPersistence = true\n try {\n if (!current) storage.removeItem(CONVERSATION_STORAGE_KEY)\n else storage.setItem(CONVERSATION_STORAGE_KEY, current)\n pendingPersistence = false\n } catch {\n /* stay in-memory */\n }\n }\n notify()\n },\n subscribe(fn) {\n if (listeners.size === 0) attach()\n listeners.add(fn)\n return () => {\n listeners.delete(fn)\n if (listeners.size === 0) {\n detachStorage?.()\n detachStorage = undefined\n }\n }\n },\n }\n}\n","import { type FontSettingsStore, type FontSettingsStorage, normalizeFontFamily } from './contracts.ts'\n\nexport type FontRole = 'text' | 'code' | 'terminal'\nexport interface FontThemeSnapshot {\n fontSizes: Record<FontRole, number>\n fontFamilies: Record<FontRole, string>\n}\nexport interface FontTheme {\n getTheme(): FontThemeSnapshot\n setFontSize(role: FontRole, px: number): void\n setFontFamily(role: FontRole, value: string): void\n}\nexport const MIGRATION_KEY = 'klarkxy.dsh-font.host-preferences.v1'\n\n/** Preserve the old selection as a backup, but never replay it over native\n * preferences on subsequent loads. Each role migrates independently. */\nexport function migrateFontPreferences(theme: FontTheme, store: FontSettingsStore, storage?: FontSettingsStorage): void {\n try { if (storage?.getItem(MIGRATION_KEY)) return } catch { return }\n const old = store.load()\n const families = theme.getTheme().fontFamilies\n for (const [role, value] of [['text', old.uiFont], ['code', old.codeFont], ['terminal', old.codeFont]] as const) {\n if (!families[role] && normalizeFontFamily(value)) theme.setFontFamily(role, value)\n }\n try { storage?.setItem(MIGRATION_KEY, '1') } catch { /* Host preferences still protect migrated nonempty roles. */ }\n}\n","/**\n * Shared contract that keeps every plugin's browser-side UI on the official\n * DeepSeek Harness Web design language.\n *\n * Two rules produce that language, and both are load-bearing here:\n *\n * 1. Colour, radius, elevation and focus come from the host theme's real\n * `--dsw-*` tokens, written under their own names. Plugins never invent a\n * token, never alias the official ones behind a private palette (a private\n * alias is just a second, diverging theme), and never carries a literal\n * fallback — the host publishes light and dark, and a literal would pin one\n * of them. The only non-colour custom properties used are the host's own\n * content-font axis and frame clearance.\n *\n * 2. Anything the host already ships is used, not reimplemented. Controls come\n * from `@deepseek-ai/dsh-client-ui-primitives` (`Button`, `Input`,\n * `Checkbox`, `Switch`, `Tag`, `Pill`, `SegmentedControl`, `Menu`, `Modal`,\n * `Tooltip`, `Toast`, `DisclosureRow`, `StateDot`, `PathLabel`, the settings\n * form suite). This module only styles what primitives do not cover: page\n * scaffolding, field layout, banners, empty states and scroll regions.\n *\n * The metrics below are transcribed from the primitives' own CSS modules so a\n * feature panel lines up pixel-for-pixel with a native one: the 14/22 body and\n * 13/20 compact type tiers, the 0.5px hairline scale, and the elevation family\n * that draws a surface's edge in its shadow (`border: 0`) instead of a border.\n */\n\n/**\n * Every `--dsw-*` token this repo is allowed to reference, grouped by role.\n *\n * Plugins may only colour through this list. It is exported so the guard test\n * can fail a build when a stylesheet reaches for anything else — the failure\n * mode this prevents is silent: an unknown token resolves to nothing, so a\n * border disappears or a label inherits the wrong colour with no error anywhere.\n */\nexport const OFFICIAL_THEME_TOKENS = {\n /** Surfaces, from the page up to the topmost nested card. */\n surface: [\n '--dsw-alias-bg-base',\n '--dsw-alias-bg-layer-1',\n '--dsw-alias-bg-layer-2',\n '--dsw-alias-bg-layer-3',\n '--dsw-alias-bg-layer-4',\n '--dsw-alias-bg-module-platform',\n '--dsw-alias-bg-overlay',\n ],\n /** Hairlines. l1 is near-invisible on a menu surface, so menus use l2+. */\n border: ['--dsw-alias-border-l1', '--dsw-alias-border-l2', '--dsw-alias-border-l3', '--dsw-alias-border-l4'],\n /** Text. `caption` is menu shortcut text, `dimmed` is placeholder text. */\n label: [\n '--dsw-alias-label-primary',\n '--dsw-alias-label-secondary',\n '--dsw-alias-label-tertiary',\n '--dsw-alias-label-caption',\n '--dsw-alias-label-dimmed',\n '--dsw-alias-label-error',\n '--dsw-alias-label-primary-foreground',\n ],\n /** Interactive fills. The `-danger` hover belongs to destructive rows. */\n interactive: [\n '--dsw-alias-interactive-bg-hover',\n '--dsw-alias-interactive-bg-active',\n '--dsw-alias-interactive-bg-hover-danger',\n ],\n /** Accent and status. `business` is the focus ring's default colour. */\n accent: [\n '--dsw-alias-brand-primary',\n '--dsw-alias-button-primary-fill',\n '--dsw-alias-button-primary-hover',\n '--dsw-alias-button-tool-bar-fill',\n '--dsw-alias-button-tool-bar-hover',\n '--dsw-alias-button-ghost-active-fill',\n '--dsw-alias-button-ghost-active-border',\n ],\n state: [\n '--dsw-alias-state-business-primary',\n '--dsw-alias-state-success-primary',\n '--dsw-alias-state-warn-primary',\n '--dsw-alias-state-error-primary',\n '--dsw-alias-state-idle-primary',\n ],\n /** Corner scale: sm 8, md 12, lg the large card, panel the modal. */\n radius: ['--dsw-radius-sm', '--dsw-radius-md', '--dsw-radius-lg', '--dsw-radius-panel'],\n /** An elevated surface draws its edge in the shadow, so it keeps border: 0. */\n elevation: [\n '--dsw-elevation-soft',\n '--dsw-elevation-stroke',\n '--dsw-elevation-stroke-color',\n '--dsw-elevation-panel',\n '--dsw-elevation-prominent',\n ],\n /** Floats, masks and scrollbars. */\n overlay: [\n '--dsw-menu-surface-fill',\n '--dsw-menu-backdrop-filter',\n '--dsw-mask-blur',\n '--dsw-alias-bg-mask-1',\n '--dsw-alias-menu-icon',\n '--dsw-alias-scrollbar-bg-l2',\n '--dsw-alias-scrollbar-hover-l2',\n '--dsw-shadow-lv3',\n ],\n /** Motion, focus and type axis, published by the host rather than by a component. */\n system: [\n '--dsw-focus-ring-width',\n '--dsw-focus-ring-color',\n '--dsw-font-markdown-code-font-family',\n '--ds-transition-duration',\n '--ds-ease-in-out',\n '--ds-font-family-code',\n '--dsh-scrollbar-thumb',\n '--dsh-scrollbar-thumb-hover',\n '--dsh-content-font-size-secondary',\n '--dsh-content-font-delta',\n '--dsh-frame-top-clearance',\n // Published by the conversation.input.model seat for narrow composer rows.\n '--dsh-composer-model-icon-display',\n '--dsh-composer-model-text-display',\n ],\n} as const\n\n/** Every official token name, flat. Used by the token guard test. */\nexport const OFFICIAL_THEME_TOKEN_NAMES: readonly string[] = Object.values(OFFICIAL_THEME_TOKENS).flat()\n\n/** The elevation steps a surface can be raised by, softest first. */\nexport type OfficialElevation = 'soft' | 'stroke' | 'panel' | 'prominent'\n\n/**\n * The host's focus ring shorthand, verbatim. Writing this per control is how\n * rings drift apart; a stylesheet that draws its own focus style should use\n * {@link officialFocus} instead. The colour fallback is the host's own default.\n */\nexport const OFFICIAL_FOCUS_RING =\n 'var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary))'\n\n/**\n * A complete `outline` declaration at the official geometry. `offset` defaults\n * to the 2px the native controls use; the host's inline field rules sit at 1px\n * and a segmented tab pulls the ring inside itself at -2px.\n */\nexport function officialFocus(offset = '2px'): string {\n return `outline: ${OFFICIAL_FOCUS_RING}; outline-offset: ${offset}`\n}\n\n/**\n * An elevated surface. The host draws a raised surface's edge inside its\n * shadow rather than as a border, so a card sets `border: 0` and takes the edge\n * from the elevation — which is also why its border stays off the alias-border\n * set that a flat, non-elevated rule would use.\n */\nexport function officialElevation(level: OfficialElevation): string {\n return `border: 0; box-shadow: var(--dsw-elevation-${level})`\n}\n\n/**\n * An elevated surface whose edge should read as a specific hairline. Rebinding\n * the stroke colour is how a menu card picks l1 while a panel picks l3, without\n * the two growing apart by hand.\n */\nexport function officialStrokedElevation(level: OfficialElevation, color: string): string {\n return `--dsw-elevation-stroke-color: ${color}; ${officialElevation(level)}`\n}\n\n/**\n * The shared stylesheet for a plugin UI, scoped under that plugin's root class.\n *\n * Scoping is what keeps this safe to always-bundle into every client: the rules\n * can only match inside the plugin's own subtree, so two plugins can both mount\n * `dsh-ui-card` without either styling the other's markup.\n *\n * Each recipe matches the root element *and* its descendants, because the\n * commonest arrangement is one element that is both — a surface that carries\n * the root class and `dsh-ui-card`, or a portaled dialog that is the root and\n * the `dsh-ui-surface`. A descendant-only scope would silently leave those\n * unstyled, with no error anywhere.\n *\n * A caveat worth knowing: `Modal` and `Menu` portal to `document.body`, so their\n * content leaves the plugin's subtree entirely. A portaled surface therefore\n * needs its own root class on an element inside the portal.\n *\n * Only patterns that primitives do not provide live here. If a control appears\n * below that `Button`/`Input`/`Switch`/`Tag`/`Menu` already covers, that is a\n * bug in this file: use the primitive and delete the recipe.\n */\nexport function officialUiCss(roots: string | readonly string[]): string {\n // One plugin often mounts several unrelated surfaces (a settings seat, a chat\n // card, a header menu), so the caller names every root. The rules below are\n // nested under a single selector list and use `&`, which the browser expands\n // per root — so one stylesheet covers all of them without duplicating itself.\n const scope = (typeof roots === 'string' ? [roots] : roots).map(root => `.${root}`).join(', ')\n const sheet = `\n/* Official DSH Web UI contract. Generated by @klarkxy/dsh-plugin-kit/official-ui.\n * Do not hand-edit the copy inside a plugin: change this module so every plugin\n * moves together. Scope: ${scope} */\n/* The scope rule below stays open for the whole sheet: every rule after it\n * nests with the parent selector, so one stylesheet can cover several unrelated\n * roots without leaking into a neighbouring plugin. Its closing brace is last. */\n${scope} {\n color: var(--dsw-alias-label-primary);\n font-family: inherit;\n font-size: 14px;\n line-height: 22px;\n min-width: 0;\n\n& *, & *::before, & *::after { box-sizing: border-box; }\n& h1, & h2, & h3, & h4, & p, & figure { margin: 0; }\n/* Keyboard focus only: pointer input keeps the native resting appearance. The\n * ring needs no radius of its own — the outline already follows the control's\n * own border-radius, and overriding it here would flatten every control. */\n& :focus-visible { ${officialFocus()}; }\n& [hidden] { display: none !important; }\n\n/* --- Type tiers. The same 14/22 and 13/20 steps the primitives use. --- */\n& .dsh-ui-title { font-size: 16px; line-height: 24px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-heading { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-compact { font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-meta { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-secondary); }\n& .dsh-ui-hint { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-error { font-size: 12px; line-height: 18px; color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-warn { color: var(--dsw-alias-state-warn-primary); }\n& .dsh-ui-success { color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-muted { color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-truncate { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n& .dsh-ui-wrap { min-width: 0; overflow-wrap: anywhere; }\n\n/* --- Layout scaffolding. --- */\n& .dsh-ui-stack { display: flex; flex-direction: column; gap: 12px; }\n& .dsh-ui-stack-lg { display: flex; flex-direction: column; gap: 20px; }\n/* Plugin detail pages share one reading column. These are layout recipes;\n * controls keep their own primitive styles. Form spacing follows the host's\n * settings-form/fields.module.css and SettingsForm.module.css. */\n& .dsh-ui-page { display: flex; flex-direction: column; gap: 16px; width: 100%; max-width: 760px; min-width: 0; }\n& .dsh-ui-form { display: flex; flex-direction: column; gap: 0; min-width: 0; }\n&.dsh-ui-form > .dsh-ui-field, & .dsh-ui-form > .dsh-ui-field { padding: 12px 0; }\n& .dsh-ui-form-footer { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; padding-top: 16px; min-width: 0; }\n& .dsh-ui-fields-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 20px; min-width: 0; margin: 0; padding: 0; border: 0; }\n@media (max-width: 560px) {\n & .dsh-ui-fields-grid { grid-template-columns: minmax(0, 1fr); }\n}\n& .dsh-ui-row { display: flex; align-items: center; gap: 8px; min-width: 0; }\n& .dsh-ui-row-wrap { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }\n& .dsh-ui-spacer { flex: 1; min-width: 0; }\n/* A 0.5px l2 rule is the host's section divider; reserve the same rhythm. */\n& .dsh-ui-divider { height: 0.5px; background: var(--dsw-alias-border-l2); }\n& .dsh-ui-section { display: flex; flex-direction: column; gap: 12px; padding-top: 16px; border-top: 0.5px solid var(--dsw-alias-border-l2); }\n\n/* --- Card: a raised surface whose edge lives in the shadow. --- */\n& .dsh-ui-card {\n ${officialElevation('stroke')}\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding: 16px;\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-alias-bg-layer-1);\n color: var(--dsw-alias-label-primary);\n min-width: 0;\n}\n& .dsh-ui-card--flat { border: 0.5px solid var(--dsw-alias-border-l3); box-shadow: none; }\n& .dsh-ui-card--nested { background: var(--dsw-alias-bg-layer-2); }\n& .dsh-ui-card--plain { background: none; }\n\n/* --- Field: label, control, help, error. The control itself is an\n * official primitive, so this only owns the vertical rhythm. --- */\n& .dsh-ui-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }\n& .dsh-ui-field + .dsh-ui-field { border-top: 0.5px solid var(--dsw-alias-border-l2); padding-top: 12px; }\n/* Grid fields share a row, so the stacked-field divider must not win later in\n * the cascade. Reset it here, after the field recipe. */\n& .dsh-ui-fields-grid > .dsh-ui-field { padding: 0; border: 0; }\n& .dsh-ui-label { display: flex; align-items: center; gap: 6px; font-size: 13px; line-height: 20px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-label-row { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }\n& .dsh-ui-help { font-size: 12px; line-height: 1.6; color: var(--dsw-alias-label-secondary); }\n& .dsh-ui-help p { margin: 0; }\n& .dsh-ui-help p + p { margin-top: 8px; }\n& .dsh-ui-required { color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-control { width: 100%; min-width: 0; }\n/* An invalid control is marked on the control, not only in the message. */\n& .dsh-ui-control[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-readonly { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n& .dsh-ui-readonly > dt { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-readonly > dd { margin: 0; font-size: 13px; line-height: 20px; overflow-wrap: anywhere; }\n\n/* --- Buttons row. A no-op container: it exists so actions line up on the\n * trailing edge the way every native panel does. --- */\n& .dsh-ui-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding-top: 4px; }\n& .dsh-ui-actions-end { justify-content: flex-end; }\n\n/* --- Banners. A banner is a left-rail notice, the shape used for warnings,\n * deprecations and blocking instructions. --- */\n& .dsh-ui-banner {\n display: flex;\n flex-direction: column;\n gap: 8px;\n padding: 10px 14px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-left: 3px solid var(--dsw-alias-state-warn-primary);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-1);\n font-size: 13px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n}\n& .dsh-ui-banner-title { font-weight: 500; color: var(--dsw-alias-state-warn-primary); }\n& .dsh-ui-banner--info { border-left-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-banner--danger { border-left-color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-banner--success { border-left-color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-banner p { margin: 0; }\n\n/* --- Inline notice: a transient confirmation with no chrome of its own. --- */\n& .dsh-ui-notice { display: flex; align-items: center; gap: 6px; font-size: 12px; line-height: 18px; color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-notice--error { color: var(--dsw-alias-state-error-primary); }\n\n/* --- Empty and loading states. Both sit in a dashed well so an empty panel\n * reads as \"nothing here yet\" rather than as a broken layout. --- */\n& .dsh-ui-empty {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 6px;\n padding: 20px 16px;\n border: 0.5px dashed var(--dsw-alias-border-l3);\n border-radius: var(--dsw-radius-md);\n font-size: 13px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n}\n& .dsh-ui-loading { display: flex; align-items: center; gap: 8px; padding: 20px 0; font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-secondary); }\n\n/* --- Selectable list. A row is a button-sized target with a hover fill and\n * a selected fill; the name carries the weight, the description does not. --- */\n& .dsh-ui-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; min-width: 0; }\n& .dsh-ui-list-scroll { max-height: min(66vh, 760px); overflow-y: auto; overflow-x: hidden; }\n& .dsh-ui-list-row { border-radius: var(--dsw-radius-md); }\n& .dsh-ui-list-row:hover { background: var(--dsw-alias-interactive-bg-hover); }\n& .dsh-ui-list-row[aria-selected='true'], & .dsh-ui-list-row[data-selected] { background: var(--dsw-alias-interactive-bg-active); }\n& .dsh-ui-list-item {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 4px;\n width: 100%;\n min-width: 0;\n padding: 10px 12px;\n border: 0;\n border-radius: var(--dsw-radius-md);\n background: none;\n font: inherit;\n color: inherit;\n text-align: start;\n cursor: pointer;\n}\n& .dsh-ui-list-item:disabled { cursor: default; }\n& .dsh-ui-list-item:disabled:hover { background: none; }\n& .dsh-ui-list-name { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); overflow-wrap: anywhere; }\n& .dsh-ui-list-desc { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n\n/* --- Code and structured output. Wraps rather than scrolls, because a\n * feature panel is read rather than scanned. --- */\n& .dsh-ui-code {\n padding: 10px 12px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-1);\n font-family: var(--ds-font-family-code);\n font-size: 12px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n overflow-wrap: anywhere;\n white-space: pre-wrap;\n}\n& .dsh-ui-scroll { max-height: 60vh; overflow: auto; overscroll-behavior: contain; }\n\n/* --- A toggle row: label on the left, switch on the trailing edge. This is\n * layout only; the switch itself is the official primitive. --- */\n& .dsh-ui-toggle-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-width: 0; padding: 12px 0; }\n& .dsh-ui-toggle-row + .dsh-ui-toggle-row { border-top: 0.5px solid var(--dsw-alias-border-l2); }\n& .dsh-ui-toggle-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n& .dsh-ui-toggle-label { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n\n/* --- Floating surface: a panel anchored to a trigger. This is the material\n * a menu card is made of — the translucent fill plus its backdrop blur, with\n * the edge riding inside the prominent elevation. A plugin that hand-rolls this\n * is how tokens like --dsw-specific-menu get invented; use this instead. --- */\n& .dsh-ui-surface {\n --dsw-elevation-stroke-color: var(--dsw-alias-border-l1);\n --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);\n --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);\n position: relative;\n display: flex;\n flex-direction: column;\n border: 0;\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-menu-surface-fill);\n backdrop-filter: var(--dsw-menu-backdrop-filter);\n box-shadow: var(--dsw-elevation-prominent);\n color: var(--dsw-alias-label-primary);\n font-size: 13px;\n line-height: 20px;\n min-width: 0;\n}\n& .dsh-ui-surface-body { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px 14px; overflow-y: auto; }\n& .dsh-ui-surface-head { display: flex; align-items: center; gap: 8px; min-width: 0; }\n& .dsh-ui-surface-title { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n\n/* --- Native select. The primitives ship no select, so a plugin that offers a\n * closed list of choices keeps the platform control and matches the official\n * settings field geometry exactly (34px, 0.5px l4, radius-md, layer-3). A\n * SegmentedControl is the primitive to reach for when the choices are few\n * enough to show at once. --- */\n& .dsh-ui-select {\n box-sizing: border-box;\n width: 100%;\n min-width: 0;\n height: 34px;\n padding: 0 12px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-3);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n color: var(--dsw-alias-label-primary);\n cursor: pointer;\n}\n& .dsh-ui-select:focus-visible { outline: none; border-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-select:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; }\n& .dsh-ui-select[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n\n/* --- Native textarea. The primitives ship no textarea either, so a settings\n * prompt keeps the platform element and the same field shell as the select:\n * 0.5px l4, radius-md, layer-3, 13/1.5 type. It grows vertically instead of\n * locking to the select's 34px row. --- */\n& .dsh-ui-textarea {\n box-sizing: border-box;\n width: 100%;\n min-width: 0;\n resize: vertical;\n padding: 8px 12px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-3);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n color: var(--dsw-alias-label-primary);\n}\n& .dsh-ui-textarea:focus-visible { outline: none; border-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-textarea:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; }\n& .dsh-ui-textarea::placeholder { color: var(--dsw-alias-label-dimmed); }\n& .dsh-ui-textarea[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n\n/* Long panels scroll inside themselves instead of growing the host page. */\n& .dsh-ui-panel { display: flex; flex-direction: column; gap: 16px; min-width: 0; }\n& .dsh-ui-panel-wide { max-width: 100%; }\n\n@media (prefers-reduced-motion: reduce) {\n & *, & *::before, & *::after { transition-duration: 0.01ms !important; animation-duration: 0.01ms !important; }\n}\n}\n`\n // Widen every recipe from \"a descendant of the root\" to \"the root, or one of\n // its descendants\". Written as a transform rather than by hand so no recipe\n // can be added later with only the descendant form. The pattern is narrow on\n // purpose: a leading `&` followed by one recipe class and no combinator, so\n // sibling and child rules such as `.dsh-ui-field + .dsh-ui-field` keep their\n // own meaning and are left alone.\n return sheet.replace(/^& (\\.dsh-ui-[a-z0-9-]+)(?=\\s*\\{)/gm, (_match, className: string) =>\n `&${className}, & ${className}`)\n}\n","import type { ContextFormed } from '@deepseek-ai/dsh-llm'\nimport { modelRouteOverride, type ModelRoute } from '@klarkxy/dsh-model-route'\n\n/**\n * The canonical home is @klarkxy/dsh-model-route; re-exported here so existing\n * plugin-kit consumers keep compiling.\n */\nexport type { ModelRoute }\n\n/** Public, browser-safe contracts. Host implementations stay in their owning packages. */\nexport type ProducerSourceKind = `plugin:${string}`\nexport type ProducerMessageSource = { kind: ProducerSourceKind; plugin: string } & ContextFormed\n\n/**\n * V4 sessions persist the producing extension in `kind`; the retired generic\n * `plugin` wrapper is not admitted. Each feature plugin declares its own kind.\n */\ndeclare module '@deepseek-ai/dsh-llm' {\n interface MessageSourceMap {\n [kind: ProducerSourceKind]: ProducerMessageSource\n }\n}\n\nexport function producerMessageSource(plugin: string): ProducerMessageSource {\n return { kind: `plugin:${plugin}`, plugin }\n}\n\nexport type RpcResult<T = unknown> = { ok: true; value: T } | { ok: false; error: { code: string; message: string } }\nexport const CHAT_EVENTS_SLOT = 'dsh-editor.chat.events'\nexport interface EvidenceRef { sessionId: string; seq: number; kind: 'user' | 'tool' | 'turn' | 'manual'; excerpt?: string }\nexport interface TaskContract {\n id: string\n sessionId: string\n sourceVersion: string\n revision: number\n goal: string\n deliverables: string[]\n inScope: string[]\n outOfScope: string[]\n constraints: string[]\n acceptance: string[]\n assumptions: string[]\n questions: string[]\n evidence: EvidenceRef[]\n readiness: 'pending' | 'clear-request' | 'user-confirmed' | 'disclosed-assumptions' | 'cancelled' | 'stale'\n updatedAt: number\n}\nexport interface TaskCheckpoint {\n id: string\n sessionId: string\n sourceVersion: string\n contractVersion?: number\n fromSeq: number\n toSeq: number\n revision: number\n status: 'running' | 'completed' | 'failed' | 'cancelled'\n items: Array<{ label: string; state: 'pending' | 'verified' | 'failed'; evidence: EvidenceRef[] }>\n constraints: string[]\n nextAction: string\n createdAt: number\n}\nexport type KnowledgeScope = { kind: 'global' } | { kind: 'project'; projectId: string }\nexport type KnowledgeKind = 'preference' | 'project-fact' | 'decision' | 'vocabulary' | 'activity' | 'lesson'\n/** Descriptive context, never an executable instruction or authorization. */\nexport interface ContextKnowledge {\n subject: string\n domain: string\n key: string\n aliases: string[]\n observedAt: number\n /** The user's own time expression, not an inferred completion date. */\n eventTime?: string\n activityStatus?: 'planned' | 'in-progress' | 'blocked' | 'paused' | 'completed' | 'cancelled' | 'unknown'\n}\n/** A scoped method. Observations remain candidates until explicitly accepted. */\nexport interface ProcedureKnowledge {\n origin: 'instruction' | 'observation'\n goal: string\n when: string[]\n steps: string[]\n avoid: string[]\n verify: string[]\n}\nexport interface MemoryRecord {\n id: string\n revision: number\n scope: KnowledgeScope\n kind: KnowledgeKind\n status: 'candidate' | 'active' | 'rejected' | 'superseded' | 'revoked' | 'deleted'\n title: string\n content: string\n tags: string[]\n evidence: EvidenceRef[]\n exceptions: string[]\n source: 'user' | 'memory' | 'dream' | 'self-improvement'\n context?: ContextKnowledge\n procedure?: ProcedureKnowledge\n createdAt: number\n updatedAt: number\n expiresAt?: number\n supersedes?: string[]\n /** Exact record revisions behind a derived candidate; revalidated on adoption. */\n basis?: Array<{ id: string; revision: number }>\n}\nexport type NewMemoryRecord = Omit<MemoryRecord, 'id' | 'revision' | 'createdAt' | 'updatedAt'>\nexport interface MemoryQuery { scope: KnowledgeScope; query?: string; kinds?: KnowledgeKind[]; statuses?: MemoryRecord['status'][]; limit?: number }\nexport interface MemoryMutationOptions { signal?: AbortSignal; isCurrent?: () => boolean }\nexport interface MemoryService {\n list(query: MemoryQuery): Promise<MemoryRecord[]>\n create(record: NewMemoryRecord, options?: MemoryMutationOptions): Promise<MemoryRecord>\n update(id: string, patch: Partial<Pick<MemoryRecord, 'title' | 'content' | 'tags' | 'exceptions' | 'status' | 'expiresAt'>>, expectedRevision: number, options?: MemoryMutationOptions): Promise<MemoryRecord>\n /** Explicit user promotion, persisted atomically on the same record; preserves expiry and evidence. */\n promoteToGlobal(id: string, expectedRevision: number, options?: MemoryMutationOptions): Promise<MemoryRecord>\n remove(id: string, expectedRevision: number, options?: MemoryMutationOptions): Promise<void>\n recall(query: MemoryQuery): Promise<MemoryRecord[]>\n}\n\n/**\n * The session creation metadata the host snapshots when it creates a delegated child\n * thread. Mirrors `CreateAgentOptions.meta` in `@deepseek-ai/dsh-agent`; it is durable\n * session data, so it survives a restart and needs no ancestry walk.\n */\nexport interface SubagentSessionLike {\n readonly header?: {\n readonly parentSession?: unknown\n readonly origin?: unknown\n readonly delegationDepth?: unknown\n readonly isSeeded?: unknown\n readonly classification?: unknown\n }\n}\n\n/**\n * True when `session` is a delegated child thread rather than a human-driven top-level\n * conversation.\n *\n * A message's `source.kind === 'user'` cannot answer this: a lead agent's dispatch prompt\n * is delivered as the child's own user message, so delegated work is indistinguishable\n * from a person typing once you only look at the message. Plugins use this to keep\n * automatic writes and derived model calls on top-level sessions.\n */\nexport function isSubagentSession(session: unknown): boolean {\n const header = (session as SubagentSessionLike | null | undefined)?.header\n if (!header || typeof header !== 'object') return false\n if (header.origin === 'subagent' || Number(header.delegationDepth ?? 0) > 0) return true\n // Native human forks also persist parentSession for history lineage. A fork's\n // seeded header distinguishes it from legacy children whose parent is the\n // only marker. Native rc.2 forks omit depth; patched hosts may persist zero.\n // Explicit delegation and unknown metadata still keep the child guard.\n const humanFork = header.isSeeded === true\n && (header.delegationDepth === undefined || header.delegationDepth === 0)\n && header.origin === undefined\n && (header.classification === undefined || header.classification === 'ordinary' || header.classification === 'free')\n return Boolean(header.parentSession) && !humanFork\n}\n\n/** Project keys come only from the host-validated session directory, never client input. */\nexport function projectIdFromCwd(cwd: string | undefined): string | undefined {\n if (typeof cwd !== 'string') return undefined\n const normalized = cwd.trim().replaceAll('\\\\', '/')\n if (!normalized) return undefined\n return normalized === '/' || /^[A-Za-z]:\\/$/.test(normalized) ? normalized : normalized.replace(/\\/+$/, '')\n}\n\n/**\n * One settings owner's Remote stream. Typert accepts either case in an RPC\n * segment, so the Cordis service key and the wire namespace use the same\n * Pascal segment. The scope's first letter stays uppercase.\n */\nexport interface ModelSettingsChangesIdentity {\n readonly service: string\n readonly namespace: string\n}\n\n/** `@klarkxy/dsh-git-commit` becomes `KlarkxyDshGitCommitModelSettingsChanges`. */\nexport function modelSettingsChangesIdentity(packageName: string): ModelSettingsChangesIdentity {\n const scoped = /^@([^/]+)\\/(.+)$/.exec(packageName)\n const body = scoped ? `${scoped[1]}/${scoped[2]}` : packageName\n const parts = body.split(/[^A-Za-z0-9]+/).filter(Boolean)\n if (!parts.length) throw new Error('Model settings package name has no RPC segment')\n const segment = `${parts.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('')}ModelSettingsChanges`\n if (!/^[A-Z][A-Za-z0-9]*$/.test(segment)) throw new Error(`Model settings sync name is not an RPC segment: ${segment}`)\n return { service: segment, namespace: segment }\n}\n\n/**\n * Repository extension: a native web provider announces that its local\n * availability changed. Kind is `search` or `fetch`; id is the provider id.\n * Listeners refresh management state and must not treat this as a network probe.\n */\nexport const WEB_PROVIDER_AVAILABILITY_EVENT = 'web/provider-availability-updated' as const\n\n/**\n * Optional display metadata a provider may attach when it registers directly\n * with `ctx.web`. Execution and credentials stay with the provider; this object\n * is display-only and must never carry secret values.\n */\nexport interface DshWebManagementDescriptor {\n readonly id: string\n readonly label: string\n readonly description: string\n readonly defaultBaseURL?: string\n readonly credentialRef?: string\n /** True when the key is shared with another surface. The page must not delete it. */\n readonly credentialShared?: boolean\n /** Optional notice naming the settings surface that owns a shared credential. */\n readonly credentialHint?: string\n readonly billing: 'request' | 'model-and-tools' | 'none' | 'unknown'\n /** Optional provider-supplied billing summary. */\n readonly pricing?: string\n /** Public HTTPS page explaining provider charges. */\n readonly pricingUrl?: string\n /** Public HTTPS page where the user can create an API key. */\n readonly signupUrl?: string\n /** Plugin that owns configuration. Native providers keep their settings there. */\n readonly configurationOwner?: string\n /** Explicit settings link supplied by the provider, never inferred from its id. */\n readonly configurationUrl?: string\n /** Fixed legacy route migrated by a bundle-owned adapter; not used by native plugins. */\n readonly legacyId?: string\n}\n\n/**\n * Host Creator agent-preset id (`agentPresets.composedPreset`).\n * Plugins that gate Creator-only tools or prompt sections compare against this.\n */\nexport const CREATOR_PRESET_ID = 'cordis'\n\n/**\n * Shared \"Session Management\" settings section id. The section is provided by\n * shared infrastructure (see `registerSessionSettingsItem` in `client-utils`),\n * not by any one business plugin: every participant registers only a row into\n * {@link SESSION_SETTINGS_ITEM_SLOT}, so any enabled subset yields the same page.\n */\nexport const SESSION_SETTINGS_SECTION_ID = 'session-manager'\n\n/**\n * Child list slot declared by the shared Session Management page. Neutral\n * naming on purpose: participants never import each other, they only\n * contribute `{id, order}` rows into this slot while the page is alive.\n */\nexport const SESSION_SETTINGS_ITEM_SLOT = 'dsh.session-settings.item'\n\n/**\n * Host-owned nav icon seat: a root-scoped list where each entry's `id` must\n * equal the `settings.section` id it decorates. Owner props are\n * `{size, active}`; icons stay `aria-hidden` so the section label remains the\n * accessible name. Contributors into a shared section may register the same\n * icon `id` with different priorities — the ledger keeps every entry while the\n * host renders one icon per section.\n */\nexport const SETTINGS_SECTION_ICON_SLOT = 'settings.section.icon'\n\n/* Shared auxiliary-model default. Feature plugins may store a global default\n * route that fills the tier between their own saved override and the live\n * session model. The durable state is a root-context singleton (like the\n * shared session-settings page): it exists while any participant retains it\n * and is never owned by a business plugin. See `auxiliary-model.ts`. */\n\n/** Root context service key holding the shared auxiliary-model state. */\nexport const AUXILIARY_MODEL_SERVICE = 'dshAuxiliaryModel'\n\n/** Authenticated host-RPC channel for get/set of the shared default. */\nexport const AUXILIARY_MODEL_CHANNEL = '/dsh-auxiliary-model'\n\n/** Model-settings namespace under which the shared default is published. */\nexport const AUXILIARY_MODEL_NS = '@klarkxy/dsh-plugin-kit/auxiliary-model'\n\n/**\n * Typert identity of the shared change stream. Mounted on the root context\n * with ownerNs filtering, so frames only carry {@link AUXILIARY_MODEL_NS}.\n */\nexport const AUXILIARY_MODEL_CHANGES_IDENTITY = modelSettingsChangesIdentity('@klarkxy/dsh-plugin-kit')\n\n/** The value the shared default persists: `model: null` means follow the live session/host model. */\nexport interface AuxiliaryModelDefaults {\n readonly revision: number\n readonly model: ModelRoute | null\n}\n\n/** Shape of the root singleton; produced and owned by `auxiliary-model.ts`. */\nexport interface AuxiliaryModelShared {\n readonly ready: Promise<void>\n snapshot(): AuxiliaryModelDefaults\n}\n\nfunction sharedAuxiliaryModel(host: unknown): AuxiliaryModelShared | undefined {\n const root = (host as { root?: unknown } | undefined)?.root as { get?(name: string, strict?: boolean): unknown } | undefined\n try {\n const shared = root?.get?.(AUXILIARY_MODEL_SERVICE, false) as AuxiliaryModelShared | undefined\n return shared && typeof shared.snapshot === 'function' ? shared : undefined\n } catch { return undefined }\n}\n\n/**\n * Synchronously read the shared auxiliary default; `undefined` only when no\n * participant retains the singleton or the default is legitimately unset.\n * An initialization or snapshot failure propagates: silently falling back to\n * a different model after a storage error would spend the wrong budget.\n */\nexport function getAuxiliaryModel(host: unknown): ModelRoute | undefined {\n const shared = sharedAuxiliaryModel(host)\n if (!shared) return undefined\n return modelRouteOverride(shared.snapshot().model ?? undefined)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport { createElement, useCallback, useEffect, useRef, useSyncExternalStore, type ReactNode } from 'react'\nimport { SESSION_SETTINGS_ITEM_SLOT, SESSION_SETTINGS_SECTION_ID, SETTINGS_SECTION_ICON_SLOT } from './contracts.ts'\n\n/** Fixed pause for failing background reads; manual work is never replayed. */\nexport function createPluginReadGate(now: () => number = Date.now) {\n let pausedUntil = 0\n let epoch = 0\n return {\n canRead: () => now() >= pausedUntil,\n reset: () => { epoch++; pausedUntil = 0 },\n async run<T>(read: () => Promise<T>): Promise<T> {\n const current = epoch\n try {\n const value = await read()\n if (current === epoch) pausedUntil = 0\n return value\n } catch (error) {\n // The native Connection error is an Error with this exact HTTP text.\n // Authentication, application failures, and cancellation stay distinct.\n const message = error instanceof Error ? error.message : ''\n if (current === epoch && (/(?:^|\\s)transport failure for .+: HTTP (?:404|405|503)\\b/.test(message)\n || (error instanceof TypeError && /^(?:Failed to fetch|fetch failed|NetworkError when attempting to fetch resource\\.?)$/i.test(message)))) {\n pausedUntil = now() + 30_000\n }\n throw error\n }\n },\n }\n}\n\nexport interface NativeSurfaceClient {\n sessions: {\n binding?(sessionId: string): { eventSource: { subscribe(listener: () => void): () => void } } | undefined\n }\n uiWorkspace: { current?: { getSnapshot(): { sessionId: string } | undefined; subscribe(listener: () => void): () => void } }\n uiSession: { adapter: { current: { getSnapshot(): { key?: string }; subscribe(listener: () => void): () => void } } }\n locale: { getSnapshot(): { active: string }; subscribe(listener: () => void): () => void }\n connection?: { generation?: { subscribe(listener: () => void): () => void } }\n}\n\n/** The Editor retains its manuscript session separately; native DSH exposes the main-view binding. */\nexport function selectedSessionId(client: Pick<NativeSurfaceClient, 'uiWorkspace' | 'uiSession'>): string {\n const workspace = client.uiWorkspace?.current\n return workspace\n ? workspace.getSnapshot()?.sessionId ?? ''\n : client.uiSession.adapter.current.getSnapshot().key ?? ''\n}\n\n/**\n * Owner props are data the host composed, never a Cordis context: reading an\n * undeclared property off one throws instead of returning undefined, which\n * would crash the slot entry and abdicate its cell for good. Tolerate a\n * throwing read so a mistaken prop degrades to \"not supplied\".\n */\nfunction read(source: unknown, key: string): unknown {\n if (source === null || typeof source !== 'object') return undefined\n try {\n return (source as Record<string, unknown>)[key]\n } catch {\n return undefined\n }\n}\n\nfunction readString(source: unknown, key: string): string | undefined {\n const value = read(source, key)\n return typeof value === 'string' ? value : undefined\n}\n\n/** Owner props win; native settings only supplies close, so resolve its selected session. */\nexport function useNativeSeat(client: NativeSurfaceClient, props?: unknown) {\n const current = useSyncExternalStore(\n useCallback((fn: () => void) => (client.uiWorkspace?.current ?? client.uiSession.adapter.current).subscribe(fn), [client]),\n useCallback(() => selectedSessionId(client), [client]),\n () => '',\n )\n const language = useSyncExternalStore(\n useCallback((fn: () => void) => client.locale.subscribe(fn), [client]),\n useCallback(() => client.locale.getSnapshot().active, [client]),\n () => 'en',\n )\n const sessionId = readString(props, 'sessionId') ?? readString(read(props, 'owner'), 'sessionId') ?? current\n const requestedLocale = read(props, 'locale') ?? read(read(props, 'owner'), 'locale') ?? language\n return { sessionId, locale: (String(requestedLocale).startsWith('zh') ? 'zh' : 'en') as 'zh' | 'en',\n hidden: read(props, 'hidden') === true || read(read(props, 'owner'), 'hidden') === true }\n}\n\n/** Refresh on native log boundaries/reconnect/focus. Read-only settling is bounded to an observed job. */\nexport function useFeatureRefresh(\n client: NativeSurfaceClient, sessionId: string, refresh: () => void,\n working = false, enabled = true,\n): void {\n const refreshRef = useRef(refresh)\n refreshRef.current = refresh\n useEffect(() => {\n if (!enabled) return\n let timer: ReturnType<typeof setTimeout> | undefined\n const queue = () => {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return\n clearTimeout(timer)\n timer = setTimeout(() => refreshRef.current(), 150)\n }\n const source = sessionId ? client.sessions.binding?.(sessionId)?.eventSource : undefined\n const stopEvents = source?.subscribe(queue)\n const stopConnection = client.connection?.generation?.subscribe(queue)\n const visibility = () => { if (document.visibilityState === 'visible') queue() }\n window.addEventListener('focus', queue)\n document.addEventListener('visibilitychange', visibility)\n // Details are collapsed by default; opening an existing panel must get current state.\n document.addEventListener('toggle', queue, true)\n return () => {\n clearTimeout(timer)\n stopEvents?.(); stopConnection?.()\n window.removeEventListener('focus', queue)\n document.removeEventListener('visibilitychange', visibility)\n document.removeEventListener('toggle', queue, true)\n }\n }, [client, sessionId, enabled])\n useEffect(() => {\n if (!enabled || !working) return\n let delay = 250\n const until = Date.now() + 300_000\n let timer: ReturnType<typeof setTimeout>\n const tick = () => {\n if (Date.now() >= until) return\n if (document.visibilityState !== 'hidden') refreshRef.current()\n delay = Math.min(delay * 2, 2000)\n timer = setTimeout(tick, delay)\n }\n timer = setTimeout(tick, delay)\n return () => clearTimeout(timer)\n }, [client, sessionId, working, enabled])\n}\n\n/* Shared \"Session Management\" settings page. The page is root-owned shared\n * infrastructure, not a business plugin: any participant alone yields the same\n * section, and participants never import each other. Synchronization crosses\n * separately bundled copies of this helper through the Cordis root context —\n * `root.get`/`root.provide` is the only rendezvous, so no window global or\n * module singleton is needed and no participant depends on another being enabled.\n */\n\n/** A row contributed into the shared Session Management page. */\nexport interface SessionSettingsItemSpec {\n readonly id: string\n readonly order: number\n}\n\n/* Original line icons for settings-section navigation seats. The official\n * `dsh-client-ui-primitives` icon set covers generic glyphs only; these keep\n * the same conventions (16×16 viewBox, 1px stroke, round caps, currentColor)\n * so the plugin set stays visually consistent with the native nav. Colors\n * never appear here: `currentColor` lets the host style the active state, and\n * `aria-hidden` keeps the section label the single accessible name. */\n\n/** Owner props the host's `settings.section.icon` seat hands to its cell. */\nexport interface SettingsSectionIconProps {\n readonly size?: number\n /** Selection state; the nav styles active icons through color, not geometry. */\n readonly active?: boolean\n}\n\ntype IconChild = readonly [tag: string, attrs: Record<string, string | number>]\n\n/** One `<svg>` with the shared icon chrome; children are plain elements. */\nfunction lineIcon(children: IconChild[]) {\n return function SettingsSectionIcon(props: SettingsSectionIconProps): ReactNode {\n return createElement('svg', {\n 'aria-hidden': 'true',\n width: props.size ?? 16,\n height: props.size ?? 16,\n viewBox: '0 0 16 16',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 1,\n strokeLinecap: 'round',\n strokeLinejoin: 'round',\n }, ...children.map(([tag, attrs], index) => createElement(tag, { key: index, ...attrs })))\n }\n}\n\n/** Chat bubble for the shared Session Management section. */\nexport const IconSessionSettings = lineIcon([\n ['path', { d: 'M8.5 13a5.5 5.5 0 0 0 5.5-5.5A5.5 5.5 0 0 0 8.5 2 5.5 5.5 0 0 0 3 7.5a5.48 5.48 0 0 0 .9 3L2.8 12.6a.5.5 0 0 0 .62.62l2.9-.98a5.48 5.48 0 0 0 2.18.76Z' }],\n])\n\n/** Serif-flavoured letter A for the Font section. */\nexport const IconFontSettings = lineIcon([\n ['path', { d: 'M3.3 12.6 7.9 3.1a.5.5 0 0 1 .9 0l4.6 9.5' }],\n ['path', { d: 'M5.2 9.4h6.3' }],\n ['path', { d: 'M2.4 12.6h2.4' }],\n ['path', { d: 'M11.9 12.6h2.4' }],\n])\n\n/** Keyboard for the Shortcuts section. */\nexport const IconKeyboardSettings = lineIcon([\n ['rect', { x: 1.75, y: 4.75, width: 12.5, height: 7.5, rx: 1.2 }],\n ['path', { d: 'M4.5 7.25h0' }],\n ['path', { d: 'M8 7.25h0' }],\n ['path', { d: 'M11.5 7.25h0' }],\n ['path', { d: 'M5.25 9.75h5.5' }],\n])\n\n/** Linked model nodes for the Model Management section. */\nexport const IconModelNetworkSettings = lineIcon([\n ['line', { x1: 10.6, y1: 5.3, x2: 8.8, y2: 7.1 }],\n ['line', { x1: 7.2, y1: 8.9, x2: 5.4, y2: 10.7 }],\n ['circle', { cx: 12, cy: 4, r: 1.9 }],\n ['circle', { cx: 4, cy: 12, r: 1.9 }],\n ['circle', { cx: 8, cy: 8, r: 1.5 }],\n])\n\n/**\n * Contribute the nav icon of a `settings.section` entry. The `settings\n * .section.icon` seat is declared by the host independently of the section\n * list, so the wait runs in parallel: the icon appears as soon as both seats\n * exist and unloading removes it again, restoring the host's default glyph.\n * The `id` must equal the section id; `order`/`priority` mirror `order` so the\n * icon cell sorts like its section and, for shared sections, several\n * contributors can register the same icon id under different priorities\n * without duplicating nav entries.\n */\nexport function registerSettingsSectionIcon(\n ctx: Context,\n sectionId: string,\n order: number,\n component: (props: SettingsSectionIconProps) => ReactNode,\n): () => void {\n const slots = (ctx as unknown as { slots: SessionSettingsSlots }).slots\n return slots.inject(SETTINGS_SECTION_ICON_SLOT, () =>\n slots.register({ name: SETTINGS_SECTION_ICON_SLOT, id: sectionId, order, priority: order }, component))\n}\n\ninterface SessionSettingsSlots {\n inject(key: string, callback: () => Iterable<(() => void) | void> | (() => void) | void): () => void\n register(spec: Record<string, unknown>, render: unknown): () => void\n}\n\ninterface SessionSettingsRoot {\n get(name: string, strict?: boolean): unknown\n provide(name: string, value: unknown): () => void\n readonly slots?: SessionSettingsSlots\n}\n\n/** Private Cordis rendezvous; every bundled copy of this helper resolves the same root service. */\nconst SESSION_SETTINGS_PAGE_SERVICE = 'dshSessionSettingsPage'\n\ninterface SessionSettingsPage {\n retain(): void\n release(): void\n}\n\n/** The page component renders only its declared child list: items paint their own titles and styles. */\nfunction SessionSettingsPageView(props: { renderSlot: (key: string, owner: Record<string, never>) => ReactNode }): ReactNode {\n return props.renderSlot(SESSION_SETTINGS_ITEM_SLOT, {})\n}\n\n/**\n * Acquire the root-owned page service, creating and providing it on first use.\n * One counter covers participants, the section wait and the provider: the last\n * release removes the wait and then the provider synchronously (Cordis deletes\n * the impl before its async disposer awaits), so a later acquire sees a clean\n * get() miss and can re-establish the page.\n */\nfunction acquireSessionSettingsPage(root: SessionSettingsRoot): SessionSettingsPage {\n const existing = root.get(SESSION_SETTINGS_PAGE_SERVICE, false) as SessionSettingsPage | undefined\n if (existing) return existing\n const slots = root.slots as SessionSettingsSlots\n let users = 0\n let stopPage: (() => void) | undefined\n let unprovide: (() => void) | undefined\n const page: SessionSettingsPage = {\n retain() {\n // The reservation is counted before the throwing install, so a failure\n // lets the caller's release() undo it fully instead of leaking the service.\n users += 1\n if (!stopPage) {\n stopPage = slots.inject('settings.section', () => slots.register(\n {\n name: 'settings.section',\n id: SESSION_SETTINGS_SECTION_ID,\n order: 30,\n label: () => {\n const locale = root.get('locale', false) as { getSnapshot?(): { active?: unknown } } | undefined\n return String(locale?.getSnapshot?.().active ?? '').startsWith('zh') ? '会话管理' : 'Session Management'\n },\n children: { [SESSION_SETTINGS_ITEM_SLOT]: { kind: 'list', scope: 'root' } },\n },\n SessionSettingsPageView,\n ))\n }\n },\n release() {\n if (users <= 0) return\n users -= 1\n if (users > 0) return\n // The last contributor tears the section down; collapsing its children\n // declaration clears the item slot for every other bundle as well.\n stopPage?.()\n stopPage = undefined\n unprovide?.()\n },\n }\n unprovide = root.provide(SESSION_SETTINGS_PAGE_SERVICE, page)\n return page\n}\n\n/**\n * Contribute one row to the shared Session Management settings page.\n *\n * `ctx` is the plugin's own context: the row's slot wait unloads with the\n * plugin, while the page itself is retained on the shared root context for as\n * long as any contributor lives. There is no fallback seat — when every\n * contributor is gone the section disappears with the page. Returns a disposer.\n * Shared root-owned infrastructure (the auxiliary-model card) calls this on\n * `ctx.root` so its row, icon and page share are owned by the root lifetime\n * and released by the returned disposer, not by any plugin fiber.\n */\nexport function registerSessionSettingsItem(\n ctx: Context,\n item: SessionSettingsItemSpec,\n component: (props: never) => ReactNode,\n): () => void {\n const slots = (ctx as unknown as { slots: SessionSettingsSlots }).slots\n const root = ctx.root as unknown as SessionSettingsRoot\n const page = acquireSessionSettingsPage(root)\n let stopItem: (() => void) | undefined\n let stopIcon: (() => void) | undefined\n try {\n page.retain()\n stopItem = slots.inject(SESSION_SETTINGS_ITEM_SLOT, () => slots.register({ name: SESSION_SETTINGS_ITEM_SLOT, ...item }, component))\n // Every contributor also waits on the nav-icon seat, registering the same\n // section icon id under its own priority (its row order). Same-id entries\n // coexist on the ledger while the host renders one icon, so no contributor\n // owns the icon and none depends on another for it; the wait lives with\n // this ctx, so it fires now on fresh loads and retro-fills on HMR.\n stopIcon = slots.inject(SETTINGS_SECTION_ICON_SLOT, () => slots.register(\n { name: SETTINGS_SECTION_ICON_SLOT, id: SESSION_SETTINGS_SECTION_ID, order: item.order, priority: item.order },\n IconSessionSettings,\n ))\n } catch (error) {\n // A synchronous failure (for example a duplicate row id or a failing page\n // install) must not pin the shared page for a contributor that never joined.\n stopIcon?.()\n stopItem?.()\n page.release()\n throw error\n }\n // The disposer may be invoked by both ctx.effect and an explicit caller;\n // releasing twice would unbalance the shared refcount.\n let disposed = false\n return () => {\n if (disposed) return\n disposed = true\n stopIcon?.()\n stopItem?.()\n page.release()\n }\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport { migrateFontPreferences, type FontRole, type FontTheme, type FontThemeSnapshot } from './preferences.ts'\nimport { Button, IconChevronDownOutlineRegular, IconChevronUpOutlineRegular, Input } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { officialUiCss } from '@klarkxy/dsh-plugin-kit/official-ui'\nimport { IconFontSettings, registerSettingsSectionIcon } from '@klarkxy/dsh-plugin-kit/client-utils'\nimport { useId, useState, useSyncExternalStore } from 'react'\nimport {\n CODE_FONT_PRESETS, CONVERSATION_FONT_SELECTOR, FONT_SIZE_SPECS,\n PLUGIN_NAME, UI_FONT_PRESETS,\n conversationFontDeclarations, createConversationFontStore, createFontSettingsStore,\n fontStackFor, fontTokenDeclarations, normalizeFontFamily,\n presetFor, systemFontLabel, uniqueSystemFonts,\n type ConversationFontStore, type FontGenericFamily, type FontPreset, type FontSettings,\n type FontSettingsStorage, type SystemFontFamily,\n} from './contracts.ts'\n\nexport const name = 'dsh-font-client'\nexport const inject = ['slots', 'theme', 'locale'] as const\n\n/** The settings.section contribution spec: the shell nav reads id/order/label\n * (label may be a thunk resolved at read time); owner props carry `close`. */\ninterface SettingsSectionSpec {\n name: 'settings.section'\n id: string\n order: number\n label: () => string\n}\n/** A cell inside a declared list slot: id + order, with priority deciding which\n * entry renders when several share one id (lowest wins). */\ninterface SettingsItemSpec {\n name: string\n id: string\n order: number\n priority?: number\n}\n\ntype Client = {\n theme: FontTheme\n locale: { getSnapshot(): { active: string }; subscribe(fn: () => void): () => void }\n slots: {\n inject(key: string, callback: () => unknown): () => void\n register(spec: SettingsSectionSpec | SettingsItemSpec, render: unknown): () => void\n }\n on(event: 'theme/change', listener: (snapshot: FontThemeSnapshot) => void): () => void\n}\n\nconst COPY = {\n zh: {\n label: '字体',\n uiFont: '界面字体',\n conversationFont: '对话字体',\n codeFont: '代码字体',\n terminalFont: '终端字体',\n textSize: '字号大小',\n textSizeHelp: '仅影响会话内容的字号',\n codeSize: '代码字号',\n codeSizeHelp: '用于代码块、行内代码与工具输出',\n terminalSize: '终端字号',\n terminalSizeHelp: '用于侧栏终端',\n increaseSize: (label: string) => `增大${label}`,\n decreaseSize: (label: string) => `减小${label}`,\n sizeUnit: 'px',\n defaultOption: '默认',\n followUi: '跟随界面字体',\n customOption: '自定义…',\n customUiPlaceholder: '例如 \"Microsoft YaHei\", sans-serif',\n customConversationPlaceholder: '例如 \"Source Han Serif SC\", serif',\n customCodePlaceholder: '例如 \"JetBrains Mono\", monospace',\n customTerminalPlaceholder: '例如 \"Cascadia Mono\", monospace',\n uiHelp: '作用于整个界面的文字,对话字体跟随它时也包括对话区。自定义时输入完整的 font-family 字体栈,留空恢复默认。',\n conversationHelp: '作用于对话区的消息和输入框,适合为长文单独选择字体(如衬线体)。仅保存在当前浏览器。',\n codeHelp: '作用于代码块、行内代码与工具输出。',\n terminalHelp: '作用于侧栏终端,与代码字体独立。',\n loadFonts: '读取系统字体',\n reloadFonts: '重新读取系统字体',\n loadingFonts: '正在读取系统字体…',\n fontsLoaded: (count: number) => `已读取 ${count} 款系统字体;新装字体后点「重新读取」刷新列表。`,\n fontsPartial: '列表来自浏览器枚举:仅安装到当前用户的字体可能不在其中,可以直接输入字体名使用。',\n fontsDenied: '系统字体读取被拒绝或当前环境不支持,仍可手动输入字体名。',\n systemGroup: '系统字体',\n resetFonts: '恢复默认字体',\n resetSizes: '恢复默认字号',\n },\n en: {\n label: 'Font',\n uiFont: 'Interface font',\n conversationFont: 'Conversation font',\n codeFont: 'Code font',\n terminalFont: 'Terminal font',\n textSize: 'Font size',\n textSizeHelp: 'Only affects conversation content',\n codeSize: 'Code font size',\n codeSizeHelp: 'Used for code blocks, inline code, and tool output',\n terminalSize: 'Terminal font size',\n terminalSizeHelp: 'Used for the sidebar terminal',\n increaseSize: (label: string) => `Increase ${label.toLowerCase()}`,\n decreaseSize: (label: string) => `Decrease ${label.toLowerCase()}`,\n sizeUnit: 'px',\n defaultOption: 'Default',\n followUi: 'Same as interface font',\n customOption: 'Custom…',\n customUiPlaceholder: 'e.g. \"Microsoft YaHei\", sans-serif',\n customConversationPlaceholder: 'e.g. \"Source Han Serif SC\", serif',\n customCodePlaceholder: 'e.g. \"JetBrains Mono\", monospace',\n customTerminalPlaceholder: 'e.g. \"Cascadia Mono\", monospace',\n uiHelp: 'Applies to all interface text, including the conversation while the conversation font follows it. For a custom value enter a full font-family stack; empty restores the default.',\n conversationHelp: 'Applies to messages and the input box in the conversation, e.g. a serif face for long text. Saved in this browser only.',\n codeHelp: 'Applies to code blocks, inline code, and tool output.',\n terminalHelp: 'Applies to the sidebar terminal, independent of the code font.',\n loadFonts: 'Load system fonts',\n reloadFonts: 'Reload system fonts',\n loadingFonts: 'Loading system fonts…',\n fontsLoaded: (count: number) => `${count} installed fonts loaded; choose “Reload system fonts” after installing new ones.`,\n fontsPartial: 'The list comes from the browser’s enumeration: fonts installed only for the current user may be missing — you can still type the family name directly.',\n fontsDenied: 'Access to system fonts was denied or is unsupported here; you can still type a font name.',\n systemGroup: 'Installed fonts',\n resetFonts: 'Reset fonts',\n resetSizes: 'Reset font sizes',\n },\n} as const\n\nexport function fontCopy(locale: 'zh' | 'en') {\n return COPY[locale]\n}\n\n/* The rows mirror the native Settings → General item geometry (16px padding,\n * 0.5px l2 hairline, 14/22 title over a 12/18 description, a 240px trailing\n * control) so the group reads like the General column — no card, no page\n * chrome. Everything visual still comes from the shared recipes and tokens.\n * The stepper reproduces the native FontSizeRow pill: centered value, hover or\n * focus-within reveals the up/down arrow column, px unit label after the pill. */\nconst styles = `${officialUiCss('font-root')}\n.font-root .font-row { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; padding: 16px 0; border-bottom: 0.5px solid var(--dsw-alias-border-l2); }\n.font-root .font-row-text { flex: 1; display: flex; flex-direction: column; gap: 4px; min-width: 0; padding-right: 40px; }\n.font-root .font-row-title { font-size: 14px; line-height: 22px; color: var(--dsw-alias-label-primary); }\n.font-root .font-row-desc { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n.font-root .font-row-control { display: inline-flex; align-items: center; gap: 8px; min-width: 0; }\n.font-root .font-select { flex: 0 1 240px; width: auto; }\n.font-root .font-custom { flex: 1 1 100%; }\n.font-root .font-stepper { display: inline-flex; align-items: center; justify-content: center; min-width: 72px; height: 36px; position: relative; border-radius: var(--dsw-radius-md); background: var(--dsw-alias-bg-module-platform); }\n.font-root .font-stepper-value { min-width: 18px; text-align: center; font-variant-numeric: tabular-nums; font-size: 14px; line-height: 22px; color: var(--dsw-alias-label-primary); }\n.font-root .font-stepper-unit { font-size: 14px; line-height: 22px; color: var(--dsw-alias-label-secondary); }\n.font-root .font-stepper-arrows { position: absolute; right: 8px; display: flex; flex-direction: column; gap: 2px; opacity: 0; }\n.font-root .font-stepper:focus-within .font-stepper-arrows { opacity: 1; }\n@media (hover:hover) { .font-root .font-stepper:hover .font-stepper-arrows { opacity: 1; } }\n@media (hover:none) { .font-root .font-stepper-arrows { opacity: 1; } }\n.font-root .font-stepper-arrow { width: 17px; height: 12px; padding: 0; display: inline-flex; align-items: center; justify-content: center; border: none; border-radius: var(--dsw-radius-sm); background: color-mix(in srgb, var(--dsw-alias-bg-layer-1) 75%, transparent); color: var(--dsw-alias-label-primary); cursor: pointer; }\n@media (hover:hover) { .font-root .font-stepper-arrow:hover:not(:disabled) { background: var(--dsw-alias-bg-layer-1); } }\n.font-root .font-stepper-arrow:disabled { color: var(--dsw-alias-label-caption); cursor: default; }\n/* The last row keeps the hairline off the page's bottom edge, mirroring the\n * host's own last-child rule inside a settings column. */\n.font-root > :last-child, .font-root > :last-child > :last-child { border-bottom: none; }\n@media (max-width: 767px) {\n .font-root .font-row-text { padding-right: 16px; }\n .font-root .font-select { flex: 0 1 auto; width: 240px; max-width: 100%; }\n}\n`\n\nfunction readStorage(): FontSettingsStorage | undefined {\n try {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n } catch {\n return undefined\n }\n}\n\nfunction useLocale(client: Client): 'zh' | 'en' {\n const getSnapshot = () => (client.locale.getSnapshot().active.toLowerCase().startsWith('zh') ? 'zh' : 'en') as 'zh' | 'en'\n return useSyncExternalStore(\n fn => client.locale.subscribe(fn),\n getSnapshot,\n getSnapshot,\n )\n}\n\nfunction presetMode(value: string, presets: readonly FontPreset[]): string {\n return presetFor(value, presets)?.id ?? (value ? 'custom' : '')\n}\n\n/** One font-family row in the native compact shape: title and description on\n * the left, a preset picker on the trailing edge, the custom stack input\n * wrapping to a full line when the picker is on Custom. */\nexport function FontField(props: {\n label: string\n help: string\n value: string\n presets: readonly FontPreset[]\n locale: 'zh' | 'en'\n generic: FontGenericFamily\n systemFonts?: readonly SystemFontFamily[]\n defaultLabel: string\n customLabel: string\n customPlaceholder: string\n systemGroupLabel: string\n onCommit(value: string): void\n}) {\n const labelId = useId()\n // undefined = not editing; the input otherwise shows the committed stack.\n const [draft, setDraft] = useState<string | undefined>(undefined)\n // With an empty (default) value nothing matches \"custom\" on its own, so the\n // choice itself must be remembered until a stack is committed.\n const [customOpen, setCustomOpen] = useState(false)\n const mode = customOpen ? 'custom' : presetMode(props.value, props.presets)\n\n function commitDraft() {\n if (draft === undefined) return\n const next = normalizeFontFamily(draft)\n setDraft(undefined)\n if (!next) setCustomOpen(false)\n if (next !== props.value) props.onCommit(next)\n }\n\n return <div className=\"font-row\">\n <div className=\"font-row-text\">\n <div className=\"font-row-title\" id={labelId}>{props.label}</div>\n <div className=\"font-row-desc\">{props.help}</div>\n </div>\n <div className=\"font-row-control\">\n <select\n className=\"dsh-ui-select font-select\"\n aria-labelledby={labelId}\n value={mode}\n onChange={event => {\n const id = event.target.value\n setDraft(undefined)\n if (id === 'custom') { setCustomOpen(true); return }\n setCustomOpen(false)\n if (id.startsWith('sys:')) { props.onCommit(fontStackFor(id.slice(4), props.generic)); return }\n const preset = props.presets.find(item => item.id === id)\n props.onCommit(preset ? preset.value : '')\n }}\n >\n <option value=\"\">{props.defaultLabel}</option>\n {props.presets.map(preset => (\n <option key={preset.id} value={preset.id}>{preset.label[props.locale]}</option>\n ))}\n <option value=\"custom\">{props.customLabel}</option>\n {props.systemFonts && props.systemFonts.length > 0 ? <optgroup label={props.systemGroupLabel}>\n {props.systemFonts.map(item => <option key={item.family} value={`sys:${item.family}`}>{systemFontLabel(item, props.locale)}</option>)}\n </optgroup> : null}\n </select>\n </div>\n {mode === 'custom' ? <span className=\"font-custom\">\n <Input\n value={draft ?? props.value}\n placeholder={props.customPlaceholder}\n aria-label={props.label}\n onChange={event => setDraft(event.target.value)}\n onBlur={commitDraft}\n onKeyDown={event => { if (event.key === 'Enter') commitDraft() }}\n />\n </span> : null}\n </div>\n}\n\n/** One font-size row in the native stepper shape: title and description on the\n * left, a pill holding the centered value with a hover/focus-revealed up/down\n * arrow column, and the px unit label after it. The displayed value follows\n * the persisted setting through the theme service, never the click echo, and\n * the arrows clamp at the role's host bounds instead of asking the service to\n * reject an out-of-range write. */\nexport function FontSizeField(props: {\n label: string\n help: string\n role: FontRole\n value: number\n locale: 'zh' | 'en'\n increaseLabel: string\n decreaseLabel: string\n unit: string\n onCommit(role: FontRole, px: number): void\n}) {\n const labelId = useId()\n const { min, max } = FONT_SIZE_SPECS[props.role]\n return <div className=\"font-row\">\n <div className=\"font-row-text\">\n <div className=\"font-row-title\" id={labelId}>{props.label}</div>\n <div className=\"font-row-desc\">{props.help}</div>\n </div>\n <div className=\"font-row-control\">\n <div className=\"font-stepper\">\n <span className=\"font-stepper-value\" aria-labelledby={labelId}>{props.value}</span>\n <span className=\"font-stepper-arrows\">\n <button\n type=\"button\"\n className=\"font-stepper-arrow\"\n aria-label={props.increaseLabel}\n disabled={props.value >= max}\n onClick={() => props.onCommit(props.role, props.value + 1)}\n >\n <IconChevronUpOutlineRegular size={9} />\n </button>\n <button\n type=\"button\"\n className=\"font-stepper-arrow\"\n aria-label={props.decreaseLabel}\n disabled={props.value <= min}\n onClick={() => props.onCommit(props.role, props.value - 1)}\n >\n <IconChevronDownOutlineRegular size={9} />\n </button>\n </span>\n </div>\n <span className=\"font-stepper-unit\">{props.unit}</span>\n </div>\n </div>\n}\n\n/** The plugin's own settings page (Settings → Font): every font control in one\n * column — interface family, conversation family + content size, code family +\n * size, terminal family + size — followed by the shared actions. It writes the\n * same theme service entries the native General font-size cell uses, so sizes\n * and families stay in sync with any other writer (keyboard zoom included). */\nexport function FontSettingsGroup(props: {\n client: Client\n conversation: ConversationFontStore\n}) {\n const locale = useLocale(props.client)\n const text = COPY[locale]\n const snapshot = useSyncExternalStore(\n fn => props.client.on('theme/change', () => fn()),\n () => props.client.theme.getTheme(),\n () => props.client.theme.getTheme(),\n )\n const settings: FontSettings = { uiFont: snapshot.fontFamilies.text, codeFont: snapshot.fontFamilies.code }\n const terminalFont = snapshot.fontFamilies.terminal\n const conversationFont = useSyncExternalStore(\n fn => props.conversation.subscribe(fn),\n () => props.conversation.get(),\n () => props.conversation.get(),\n )\n // System font list is shared by the font fields: one permission prompt, one list.\n const [fontList, setFontList] = useState<{ state: 'idle' | 'loading' | 'ready' | 'denied'; families: readonly SystemFontFamily[] }>(\n { state: 'idle', families: [] },\n )\n\n async function loadSystemFonts() {\n if (fontList.state === 'loading') return\n // Every click re-enumerates: fonts installed after the first read appear\n // on the next one (the button relabels to \"reload\" once a list exists).\n // Local Font Access API: Chromium-only and gated behind a permission\n // prompt; anything else (Firefox, Safari, denied permission, Electron\n // policy) falls through to the preset + manual-input flow unchanged.\n const query = (globalThis as { queryLocalFonts?: () => Promise<readonly unknown[]> }).queryLocalFonts\n if (typeof query !== 'function') { setFontList({ state: 'denied', families: [] }); return }\n setFontList(current => ({ state: 'loading', families: current.families }))\n try {\n const fonts = await query()\n setFontList({ state: 'ready', families: uniqueSystemFonts(fonts) })\n } catch {\n setFontList(current => ({ state: 'denied', families: current.families }))\n }\n }\n\n function updateFamily(role: FontRole, value: string) {\n props.client.theme.setFontFamily(role, normalizeFontFamily(value))\n }\n function updateSize(role: FontRole, px: number) {\n props.client.theme.setFontSize(role, px)\n }\n\n const sizeField = (role: FontRole, label: string, help: string) => (\n <FontSizeField\n label={label}\n help={help}\n role={role}\n value={snapshot.fontSizes[role]}\n locale={locale}\n increaseLabel={text.increaseSize(label)}\n decreaseLabel={text.decreaseSize(label)}\n unit={text.sizeUnit}\n onCommit={updateSize}\n />\n )\n\n return <div className=\"font-root\" role=\"group\" aria-label={text.label} data-testid=\"font-settings\">\n <FontField\n label={text.uiFont}\n help={text.uiHelp}\n value={settings.uiFont}\n presets={UI_FONT_PRESETS}\n locale={locale}\n generic=\"sans-serif\"\n systemFonts={fontList.families}\n defaultLabel={text.defaultOption}\n customLabel={text.customOption}\n customPlaceholder={text.customUiPlaceholder}\n systemGroupLabel={text.systemGroup}\n onCommit={value => updateFamily('text', value)}\n />\n <FontField\n label={text.conversationFont}\n help={text.conversationHelp}\n value={conversationFont}\n presets={UI_FONT_PRESETS}\n locale={locale}\n generic=\"sans-serif\"\n systemFonts={fontList.families}\n defaultLabel={text.followUi}\n customLabel={text.customOption}\n customPlaceholder={text.customConversationPlaceholder}\n systemGroupLabel={text.systemGroup}\n onCommit={value => props.conversation.set(value)}\n />\n {sizeField('text', text.textSize, text.textSizeHelp)}\n <FontField\n label={text.codeFont}\n help={text.codeHelp}\n value={settings.codeFont}\n presets={CODE_FONT_PRESETS}\n locale={locale}\n generic=\"monospace\"\n systemFonts={fontList.families}\n defaultLabel={text.defaultOption}\n customLabel={text.customOption}\n customPlaceholder={text.customCodePlaceholder}\n systemGroupLabel={text.systemGroup}\n onCommit={value => updateFamily('code', value)}\n />\n {sizeField('code', text.codeSize, text.codeSizeHelp)}\n <FontField\n label={text.terminalFont}\n help={text.terminalHelp}\n value={terminalFont}\n presets={CODE_FONT_PRESETS}\n locale={locale}\n generic=\"monospace\"\n systemFonts={fontList.families}\n defaultLabel={text.defaultOption}\n customLabel={text.customOption}\n customPlaceholder={text.customTerminalPlaceholder}\n systemGroupLabel={text.systemGroup}\n onCommit={value => updateFamily('terminal', value)}\n />\n {sizeField('terminal', text.terminalSize, text.terminalSizeHelp)}\n <div className=\"font-row\">\n <div className=\"font-row-text\">\n {fontList.state === 'ready' ? <div className=\"font-row-desc\" role=\"status\">{text.fontsLoaded(fontList.families.length)}</div> : null}\n {fontList.state === 'ready' ? <div className=\"font-row-desc\" role=\"status\">{text.fontsPartial}</div> : null}\n {fontList.state === 'denied' ? <div className=\"font-row-desc\" role=\"status\">{text.fontsDenied}</div> : null}\n </div>\n <div className=\"font-row-control\">\n <Button variant=\"outline\" size=\"sm\" disabled={fontList.state === 'loading'}\n onClick={() => { void loadSystemFonts() }}>\n {fontList.state === 'loading' ? text.loadingFonts : fontList.state === 'ready' ? text.reloadFonts : text.loadFonts}\n </Button>\n <Button variant=\"outline\" size=\"sm\" onClick={() => {\n updateFamily('text', '')\n updateFamily('code', '')\n updateFamily('terminal', '')\n props.conversation.set('')\n }}>{text.resetFonts}</Button>\n <Button variant=\"outline\" size=\"sm\" onClick={() => {\n updateSize('text', FONT_SIZE_SPECS.text.default)\n updateSize('code', FONT_SIZE_SPECS.code.default)\n updateSize('terminal', FONT_SIZE_SPECS.terminal.default)\n }}>{text.resetSizes}</Button>\n </div>\n </div>\n </div>\n}\n\nexport function apply(ctx: Context): void {\n const client = ctx as unknown as Client & { effect: Context['effect'] }\n const store = createFontSettingsStore(readStorage())\n const conversation = createConversationFontStore(readStorage())\n migrateFontPreferences(client.theme, store, readStorage())\n ctx.effect(() => {\n if (typeof document === 'undefined') return () => {}\n const style = document.createElement('style')\n style.setAttribute('data-plugin', PLUGIN_NAME)\n style.textContent = styles\n document.head.appendChild(style)\n return () => style.remove()\n }, 'font.styles')\n ctx.effect(() => {\n if (typeof document === 'undefined') return () => {}\n const style = document.createElement('style')\n style.setAttribute('data-plugin', PLUGIN_NAME)\n style.setAttribute('data-font-role', 'conversation')\n document.head.appendChild(style)\n const write = () => {\n const sheet = style.sheet\n if (!sheet) return\n while (sheet.cssRules.length > 0) sheet.deleteRule(0)\n const declarations = conversationFontDeclarations(\n conversation.get(),\n fontTokenDeclarations(document.styleSheets ?? []),\n )\n if (declarations.length === 0) return\n sheet.insertRule(`${CONVERSATION_FONT_SELECTOR}{}`)\n const rule = sheet.cssRules[0] as CSSStyleRule\n for (const [name, value] of declarations) rule.style.setProperty(name, value)\n }\n write()\n const unsubscribe = conversation.subscribe(write)\n return () => { unsubscribe(); style.remove() }\n }, 'font.conversation')\n // Fonts get their own settings section, not a General item row. The\n // shadowing entry waits on the General item list separately and lives inside\n // the section callback's lifetime: a same-id entry at lower priority renders\n // nothing in the native font-size cell's place, so the cell is hidden exactly\n // while both the Font page and the General column exist — section collapse\n // or plugin unload cancels the wait and the native cell renders again (and\n // a late or re-declared General section re-installs it). The native entry is\n // never touched; shadowing is the slot ledger's own override semantics.\n ctx.effect(() => client.slots.inject('settings.section', () => [\n client.slots.register(\n {\n name: 'settings.section',\n id: 'font',\n order: 5,\n label: () => (client.locale.getSnapshot().active.toLowerCase().startsWith('zh') ? COPY.zh.label : COPY.en.label),\n },\n () => <FontSettingsGroup client={client} conversation={conversation} />,\n ),\n client.slots.inject('settings.general.item', () => client.slots.register(\n { name: 'settings.general.item', id: 'font-size', order: 11, priority: -10 },\n () => null,\n )),\n // Nav icon seat is separate from the section list; nesting its wait inside\n // the section's keeps the letter-A bound to this page's exact lifetime.\n registerSettingsSectionIcon(ctx, 'font', 5, IconFontSettings),\n ]), 'font.settings')\n}\n"],"mappings":";;;;;;;;AAIA,MAAa,cAAc;;;AAI3B,MAAa,cAAc;AAS3B,MAAa,kBAAkB;CAC7B,MAAM;EAAE,KAAK;EAAI,KAAK;EAAI,SAAS;CAAG;CACtC,MAAM;EAAE,KAAK;EAAI,KAAK;EAAI,SAAS;CAAG;CACtC,UAAU;EAAE,KAAK;EAAI,KAAK;EAAI,SAAS;CAAG;AAC5C;;;;;AAMA,MAAa,mBAAmB;;;AAKhC,MAAa,6BAA6B;;;;AAK1C,SAAgB,OAAO,MAAsB;CAC3C,OAAO,OAAO,KAAK;AACrB;;;AAIA,MAAa,6BAA6B;;;;AAK1C,MAAa,2BAA2B;AAWxC,SAAgB,sBAAoC;CAClD,OAAO;EAAE,QAAQ;EAAI,UAAU;CAAG;AACpC;;;;;AAMA,SAAgB,oBAAoB,OAAwB;CAC1D,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,MACJ,QAAQ,+BAA+B,EAAE,CAAC,CAC1C,KAAK,CAAC,CACN,MAAM,GAAG,GAAG;AACjB;AAEA,SAAgB,kBAAkB,KAA4B;CAC5D,IAAI,SAAS;CACb,IAAI,OAAO,WAAW,UAC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AAa,kBAAkB,cAAc;EACnD,SAAS,KAAK,YAAY,KAAK;EAC/B,MAAM,cAAc;GAClB,MAAM,QAAQ,MAAM;GACpB,IAAI,CAAC,OAAO;GACZ,OAAO,MAAM,SAAS,SAAS,GAAG,MAAM,WAAW,CAAC;GACpD,MAAM,eAAe,6BACnB,aAAa,IAAI,GACjB,sBAAsB,SAAS,eAAe,CAAC,CAAC,CAClD;GACA,IAAI,aAAa,WAAW,GAAG;GAC/B,MAAM,WAAW,GAAG,2BAA2B,GAAG;GAClD,MAAM,OAAO,MAAM,SAAS;GAC5B,KAAK,MAAM,CAAC,MAAM,UAAU,cAAc,KAAK,MAAM,YAAY,MAAM,KAAK;EAC9E;EACA,MAAM;EACN,MAAM,cAAc,aAAa,UAAU,KAAK;EAChD,aAAa;GAAE,YAAY;GAAG,MAAM,OAAO;EAAE;CAC/C,GAAG,mBAAmB;CAStB,IAAI,aAAa,OAAO,MAAM,OAAO,0BAA0B;EAC7D,OAAO,MAAM,SACX;GACE,MAAM;GACN,IAAI;GACJ,OAAO;GACP,aAAc,OAAO,OAAO,YAAY,CAAC,CAAC,OAAO,YAAY,CAAC,CAAC,WAAW,IAAI,IAAI,KAAK,GAAG,QAAQ,KAAK,GAAG;EAC5G,SACM,iBAAA,GAAA,kBAAA,IAAA,CAAC,mBAAD;GAA2B;GAAsB;EAAe,CAAA,CACxE;EACA,OAAO,MAAM,OAAO,+BAA+B,OAAO,MAAM,SAC9D;GAAE,MAAM;GAAyB,IAAI;GAAa,OAAO;GAAI,UAAU;EAAI,SACrE,IACR,CAAC;EAGD,4BAA4B,KAAK,QAAQ,GAAG,gBAAgB;CAC9D,CAAC,GAAG,eAAe;AACrB"}
1
+ {"version":3,"file":"client.inner.cjs","names":["createElement","useSyncExternalStore","useId","useState","Input","IconChevronUpOutlineRegular","IconChevronDownOutlineRegular","Button"],"sources":["../src/contracts.ts","../src/preferences.ts","../../dsh-plugin-kit/src/official-ui.ts","../../dsh-plugin-kit/src/contracts.ts","../../dsh-plugin-kit/src/client-utils.ts","../../dsh-plugin-kit/src/log-shared.ts","../../dsh-plugin-kit/src/client-logger.ts","../src/client.tsx"],"sourcesContent":["/** Browser-safe contracts for @klarkxy/dsh-font: settings shape, font presets,\n * normalization, the CSS-variable application core, and the local store.\n * No React, no cordis — every export runs in Node tests and the browser. */\n\nexport const PLUGIN_NAME = '@klarkxy/dsh-font'\n\n/** Legacy browser-local font choices, retained as the one-time migration backup.\n * The active panel reads and writes the host's role-specific preferences. */\nexport const STORAGE_KEY = 'klarkxy.dsh-font.v1'\n\n/** Host per-role font-size bounds and defaults, matching the ui-theme\n * `FONT_SIZE_SPECS` contract (stepper clamps at both ends, integer px). */\nexport interface FontSizeSpec {\n readonly min: number\n readonly max: number\n readonly default: number\n}\nexport const FONT_SIZE_SPECS = {\n text: { min: 10, max: 22, default: 14 },\n code: { min: 10, max: 16, default: 11 },\n terminal: { min: 10, max: 20, default: 13 },\n} as const satisfies Record<string, FontSizeSpec>\n\n/** Root font variables the legacy local-storage model overrode directly:\n * derived Markdown and brand fonts follow the interface variable. Kept as\n * migration data for the pre-theme-service storage; live writes now go\n * through theme.setFontFamily per role instead. */\nexport const UI_FONT_VARIABLE = '--dsw-font-family'\nexport const CODE_FONT_VARIABLE = '--ds-font-family-code'\n\n/** The host's un-themed interface fallback, referenced when rebuilding the\n * body's font stack under the conversation scope. */\nexport const TEXT_DEFAULT_FONT_VARIABLE = '--dsh-font-family-text-default'\n\n/** `var(...)` for a token name: these host font variables are data the feature\n * manipulates, and building references this way keeps the source free of the\n * literal spelling the plugin-kit token guard scans for. */\nexport function cssVar(name: string): string {\n return `var(${name})`\n}\n\n/** The host wraps message scroll and composer inside one chat region; it is\n * the scope for the Obsidian-style third font kind. */\nexport const CONVERSATION_FONT_SELECTOR = '[data-conversation-region=\"chat\"]'\n\n/** Browser-local conversation stack: the host persists its own three roles\n * (text/code/terminal), while the plugin-owned conversation kind keeps this\n * separate key in the same storage. */\nexport const CONVERSATION_STORAGE_KEY = 'klarkxy.dsh-font.conversation.v1'\n\n/** Legacy browser-local settings shape: written before the theme service\n * owned per-role families; kept so the one-time migration can read it. */\nexport interface FontSettings {\n /** Full CSS font-family stack for the interface; empty keeps the host default. */\n uiFont: string\n /** Full CSS font-family stack for code blocks, inline code and terminals. */\n codeFont: string\n}\n\nexport function defaultFontSettings(): FontSettings {\n return { uiFont: '', codeFont: '' }\n}\n\n/** A raw font-family string is placed into a single CSS declaration via\n * CSSStyleDeclaration.setProperty, which cannot escape the declaration — but\n * trimming control characters and the CSS delimiters keeps pasted garbage from\n * producing a silently-dead value. */\nexport function normalizeFontFamily(value: unknown): string {\n if (typeof value !== 'string') return ''\n return value\n .replace(/[\\u0000-\\u001F\\u007F;{}<>]/g, '')\n .trim()\n .slice(0, 300)\n}\n\nexport function parseFontSettings(raw: unknown): FontSettings {\n let source = raw\n if (typeof source === 'string') {\n try {\n source = JSON.parse(source)\n } catch {\n return defaultFontSettings()\n }\n }\n if (!source || typeof source !== 'object' || Array.isArray(source)) return defaultFontSettings()\n const record = source as Record<string, unknown>\n return {\n uiFont: normalizeFontFamily(record.uiFont),\n codeFont: normalizeFontFamily(record.codeFont),\n }\n}\n\nexport function serializeFontSettings(settings: FontSettings): string {\n return JSON.stringify({\n uiFont: normalizeFontFamily(settings.uiFont),\n codeFont: normalizeFontFamily(settings.codeFont),\n })\n}\n\nexport interface FontPreset {\n readonly id: string\n readonly label: { readonly zh: string; readonly en: string }\n /** The font-family stack committed when the preset is picked. */\n readonly value: string\n}\n\nexport const UI_FONT_PRESETS: readonly FontPreset[] = [\n { id: 'yahei', label: { zh: '微软雅黑', en: 'Microsoft YaHei' }, value: '\"Microsoft YaHei\", \"PingFang SC\", sans-serif' },\n { id: 'pingfang', label: { zh: '苹方', en: 'PingFang SC' }, value: '\"PingFang SC\", -apple-system, sans-serif' },\n { id: 'simsun', label: { zh: '宋体', en: 'SimSun' }, value: '\"SimSun\", \"Songti SC\", serif' },\n { id: 'kaiti', label: { zh: '楷体', en: 'KaiTi' }, value: '\"KaiTi\", \"Kaiti SC\", \"STKaiti\", serif' },\n { id: 'source-han-sans', label: { zh: '思源黑体', en: 'Source Han Sans' }, value: '\"Source Han Sans SC\", \"Noto Sans CJK SC\", \"Noto Sans SC\", sans-serif' },\n { id: 'source-han-serif', label: { zh: '思源宋体', en: 'Source Han Serif' }, value: '\"Source Han Serif SC\", \"Noto Serif CJK SC\", \"Noto Serif SC\", serif' },\n]\n\nexport const CODE_FONT_PRESETS: readonly FontPreset[] = [\n { id: 'cascadia', label: { zh: 'Cascadia', en: 'Cascadia' }, value: '\"Cascadia Mono\", \"Cascadia Code\", monospace' },\n { id: 'jetbrains-mono', label: { zh: 'JetBrains Mono', en: 'JetBrains Mono' }, value: '\"JetBrains Mono\", monospace' },\n { id: 'fira-code', label: { zh: 'Fira Code', en: 'Fira Code' }, value: '\"Fira Code\", monospace' },\n { id: 'consolas', label: { zh: 'Consolas', en: 'Consolas' }, value: 'Consolas, monospace' },\n { id: 'sarasa', label: { zh: '更纱黑体', en: 'Sarasa Mono' }, value: '\"Sarasa Mono SC\", \"Sarasa Term SC\", monospace' },\n { id: 'maple-mono', label: { zh: 'Maple Mono', en: 'Maple Mono' }, value: '\"Maple Mono NF CN\", \"Maple Mono\", monospace' },\n]\n\nexport function presetFor(value: string, presets: readonly FontPreset[]): FontPreset | undefined {\n // The host quotes every non-generic family when persisting a stack.\n const comparable = (stack: string) => stack.split(',').map(name => name.trim().replace(/^[\"']|[\"']$/g, '')).join(',')\n return presets.find(preset => comparable(preset.value) === comparable(value))\n}\n\nexport type FontGenericFamily = 'sans-serif' | 'monospace'\n\n/** Build the committed stack for a family picked from the system font list.\n * The family name comes from the OS (Local Font Access API); quotes and\n * backslashes are stripped so it can be safely re-quoted as one family. */\nexport function fontStackFor(family: string, generic: FontGenericFamily): string {\n const cleaned = normalizeFontFamily(family).replace(/[\"\\\\]/g, '')\n if (!cleaned) return generic\n return `\"${cleaned}\", ${generic}`\n}\n\n/** A system font offered in the picker: `family` is the exact name CSS\n * matching needs; `fullName` is an informative localized alias (e.g. converted\n * CJK fonts whose family is the Latin alias), '' when it only restates the\n * family (\"Microsoft YaHei Regular\" adds nothing). */\nexport interface SystemFontFamily {\n readonly family: string\n readonly fullName: string\n}\n\n/** Distinct, normalized, family-sorted entries out of a queryLocalFonts()\n * result (entries carry `family` and `fullName`; duplicates per style are\n * expected). */\nexport function uniqueSystemFonts(fonts: readonly unknown[]): SystemFontFamily[] {\n const byFamily = new Map<string, string>()\n for (const item of fonts) {\n if (!item || typeof item !== 'object' || Array.isArray(item)) continue\n const record = item as Record<string, unknown>\n const family = normalizeFontFamily(record.family).replace(/[\"\\\\]/g, '')\n if (!family || byFamily.has(family)) continue\n const fullName = normalizeFontFamily(record.fullName).replace(/[\"\\\\]/g, '')\n byFamily.set(family, fullName && fullName !== family && !fullName.startsWith(`${family} `) ? fullName : '')\n }\n return [...byFamily.entries()]\n .map(([family, fullName]) => ({ family, fullName }))\n .sort((a, b) => a.family.localeCompare(b.family))\n}\n\n/** Picker label: the UI locale's recognizable name leads, the alias stays in\n * parentheses because the canonical family is still what a custom input needs. */\nexport function systemFontLabel(item: SystemFontFamily, locale: 'zh' | 'en'): string {\n if (!item.fullName) return item.family\n return locale === 'zh' ? `${item.fullName}(${item.family})` : `${item.family}(${item.fullName})`\n}\n\n/** Minimal write face of CSSStyleDeclaration — document.documentElement.style\n * satisfies it, and tests supply a recording double. */\nexport interface FontStyleTarget {\n setProperty(name: string, value: string): void\n removeProperty(name: string): void\n}\n\nexport function applyFontSettings(style: FontStyleTarget, settings: FontSettings): void {\n if (settings.uiFont) style.setProperty(UI_FONT_VARIABLE, settings.uiFont)\n else style.removeProperty(UI_FONT_VARIABLE)\n if (settings.codeFont) style.setProperty(CODE_FONT_VARIABLE, settings.codeFont)\n else style.removeProperty(CODE_FONT_VARIABLE)\n}\n\nexport function clearFontSettings(style: FontStyleTarget): void {\n style.removeProperty(UI_FONT_VARIABLE)\n style.removeProperty(CODE_FONT_VARIABLE)\n}\n\n/** Read face required to restore only overrides still owned by this instance. */\nexport interface OwnedFontStyleTarget extends FontStyleTarget {\n getPropertyValue(name: string): string\n getPropertyPriority(name: string): string\n setProperty(name: string, value: string, priority?: string): void\n}\n\n/** Root inline overrides preserve the existing local persistence/unload\n * boundary. Save the underlying value (including !important) on first write\n * or when the host replaces a value, and never retract somebody else's write. */\nexport function createFontSettingsOverride(style: OwnedFontStyleTarget) {\n const owned = new Map<string, { previous: string; priority: string; value: string }>()\n function release(name: string) {\n const entry = owned.get(name)\n if (!entry) return\n if (style.getPropertyValue(name) === entry.value && style.getPropertyPriority(name) === '') {\n if (entry.previous) style.setProperty(name, entry.previous, entry.priority)\n else style.removeProperty(name)\n }\n owned.delete(name)\n }\n return {\n apply(settings: FontSettings) {\n for (const [name, value] of [\n [UI_FONT_VARIABLE, settings.uiFont],\n [CODE_FONT_VARIABLE, settings.codeFont],\n ] as const) {\n if (!value) { release(name); continue }\n const current = style.getPropertyValue(name)\n const priority = style.getPropertyPriority(name)\n const entry = owned.get(name)\n if (!entry || current !== entry.value || priority !== '') {\n owned.set(name, { previous: current, priority, value: '' })\n }\n style.setProperty(name, value)\n owned.get(name)!.value = style.getPropertyValue(name)\n }\n },\n dispose() { for (const name of [...owned.keys()]) release(name) },\n }\n}\n\nexport interface FontSettingsStorage {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\nexport interface FontSettingsStore {\n load(): FontSettings\n save(next: FontSettings): void\n}\n\n/** Browser-local persistence. A fully-default setting removes the key so a\n * reset leaves no residue; storage failures (private mode, quota) degrade to\n * in-memory behaviour rather than breaking the panel. */\nexport function createFontSettingsStore(storage: FontSettingsStorage | undefined): FontSettingsStore {\n let current = defaultFontSettings()\n // A failed local write must win over stale persisted values on page remount.\n // Successful writes restore the existing ability to read external updates.\n let pendingPersistence = false\n return {\n load() {\n if (storage && !pendingPersistence) {\n try {\n current = parseFontSettings(storage.getItem(STORAGE_KEY))\n } catch {\n /* keep the last readable or locally saved snapshot */\n }\n }\n return { ...current }\n },\n save(next) {\n current = parseFontSettings(next)\n if (!storage) return\n pendingPersistence = true\n try {\n if (!current.uiFont && !current.codeFont) storage.removeItem(STORAGE_KEY)\n else storage.setItem(STORAGE_KEY, serializeFontSettings(current))\n pendingPersistence = false\n } catch {\n /* stay in-memory */\n }\n },\n }\n}\n\n/** Structural slices of the CSSOM the token scan needs — StyleSheetList,\n * CSSStyleSheet and CSSStyleRule satisfy them, and tests supply doubles. */\ninterface FontTokenRule {\n selectorText?: string\n style?: {\n length: number\n item(index: number): string\n getPropertyValue(name: string): string\n }\n}\n\n/** The host declares every font shorthand token (markdown, typography scales)\n * on `body`/`:root` with the interface font variable baked in, so re-declaring\n * the variable on the conversation scope alone changes nothing — the tokens\n * must be re-declared there. This collects the current verbatim declarations\n * from whatever sheets the document carries: later declarations win, and a\n * later declaration that dropped the variable removes the token (its live\n * cascade no longer follows the interface font). Cross-origin sheets are\n * skipped. */\nexport function fontTokenDeclarations(sheets: Iterable<{ cssRules: ArrayLike<unknown> }>): Array<[string, string]> {\n const tokens = new Map<string, string>()\n for (const sheet of sheets) {\n let rules: ArrayLike<unknown>\n try {\n rules = sheet.cssRules\n } catch {\n continue\n }\n for (let index = 0; index < rules.length; index += 1) {\n const rule = rules[index] as FontTokenRule | undefined\n if (!rule?.style || (rule.selectorText !== 'body' && rule.selectorText !== ':root')) continue\n for (let i = 0; i < rule.style.length; i += 1) {\n const name = rule.style.item(i)\n if (!name.startsWith('--') || name === UI_FONT_VARIABLE) continue\n const value = rule.style.getPropertyValue(name)\n if (value.includes(cssVar(UI_FONT_VARIABLE))) tokens.set(name, value)\n else tokens.delete(name)\n }\n }\n }\n return [...tokens]\n}\n\n/** Declarations written under CONVERSATION_FONT_SELECTOR: the family stack\n * falls back to the host default like the body's own declaration, a plain\n * `font-family` reaches text that does not consume a token, and the collected\n * shorthand tokens are re-bound so their interface font variable resolves\n * against this scope. */\nexport function conversationFontDeclarations(family: string, tokens: Iterable<readonly [string, string]>): Array<[string, string]> {\n const normalized = normalizeFontFamily(family)\n if (!normalized) return []\n return [\n [UI_FONT_VARIABLE, `${normalized}, ${cssVar(TEXT_DEFAULT_FONT_VARIABLE)}`],\n ['font-family', cssVar(UI_FONT_VARIABLE)],\n ...[...tokens].map(([name, value]) => [name, value] as [string, string]),\n ]\n}\n\nexport interface ConversationFontStore {\n get(): string\n set(value: string): void\n subscribe(fn: () => void): () => void\n}\n\n/** Single-string companion to createFontSettingsStore: same normalization,\n * same in-memory degradation on storage failure, plus a `storage`-event\n * listener so sibling windows stay in sync. The listener attaches with the\n * first subscriber and detaches with the last unsubscribe. */\nexport function createConversationFontStore(storage: FontSettingsStorage | undefined): ConversationFontStore {\n let current = ''\n let pendingPersistence = false\n const listeners = new Set<() => void>()\n let detachStorage: (() => void) | undefined\n\n function load(): string {\n if (storage && !pendingPersistence) {\n try {\n current = normalizeFontFamily(storage.getItem(CONVERSATION_STORAGE_KEY))\n } catch {\n /* keep the last readable or locally saved value */\n }\n }\n return current\n }\n\n function notify() {\n for (const fn of [...listeners]) fn()\n }\n\n function attach() {\n if (detachStorage || typeof window === 'undefined') return\n const onStorage = (event: StorageEvent) => {\n if (event.key !== CONVERSATION_STORAGE_KEY && event.key !== null) return\n load()\n notify()\n }\n window.addEventListener('storage', onStorage)\n detachStorage = () => window.removeEventListener('storage', onStorage)\n }\n\n return {\n get: load,\n set(value) {\n current = normalizeFontFamily(value)\n if (storage) {\n pendingPersistence = true\n try {\n if (!current) storage.removeItem(CONVERSATION_STORAGE_KEY)\n else storage.setItem(CONVERSATION_STORAGE_KEY, current)\n pendingPersistence = false\n } catch {\n /* stay in-memory */\n }\n }\n notify()\n },\n subscribe(fn) {\n if (listeners.size === 0) attach()\n listeners.add(fn)\n return () => {\n listeners.delete(fn)\n if (listeners.size === 0) {\n detachStorage?.()\n detachStorage = undefined\n }\n }\n },\n }\n}\n","import { type FontSettingsStore, type FontSettingsStorage, normalizeFontFamily } from './contracts.ts'\n\nexport type FontRole = 'text' | 'code' | 'terminal'\nexport interface FontThemeSnapshot {\n fontSizes: Record<FontRole, number>\n fontFamilies: Record<FontRole, string>\n}\nexport interface FontTheme {\n getTheme(): FontThemeSnapshot\n setFontSize(role: FontRole, px: number): void\n setFontFamily(role: FontRole, value: string): void\n}\nexport const MIGRATION_KEY = 'klarkxy.dsh-font.host-preferences.v1'\n\n/** Preserve the old selection as a backup, but never replay it over native\n * preferences on subsequent loads. Each role migrates independently. */\nexport function migrateFontPreferences(theme: FontTheme, store: FontSettingsStore, storage?: FontSettingsStorage): void {\n try { if (storage?.getItem(MIGRATION_KEY)) return } catch { return }\n const old = store.load()\n const families = theme.getTheme().fontFamilies\n for (const [role, value] of [['text', old.uiFont], ['code', old.codeFont], ['terminal', old.codeFont]] as const) {\n if (!families[role] && normalizeFontFamily(value)) theme.setFontFamily(role, value)\n }\n try { storage?.setItem(MIGRATION_KEY, '1') } catch { /* Host preferences still protect migrated nonempty roles. */ }\n}\n","/**\n * Shared contract that keeps every plugin's browser-side UI on the official\n * DeepSeek Harness Web design language.\n *\n * Two rules produce that language, and both are load-bearing here:\n *\n * 1. Colour, radius, elevation and focus come from the host theme's real\n * `--dsw-*` tokens, written under their own names. Plugins never invent a\n * token, never alias the official ones behind a private palette (a private\n * alias is just a second, diverging theme), and never carries a literal\n * fallback — the host publishes light and dark, and a literal would pin one\n * of them. The only non-colour custom properties used are the host's own\n * content-font axis and frame clearance.\n *\n * 2. Anything the host already ships is used, not reimplemented. Controls come\n * from `@deepseek-ai/dsh-client-ui-primitives` (`Button`, `Input`,\n * `Checkbox`, `Switch`, `Tag`, `Pill`, `SegmentedControl`, `Menu`, `Modal`,\n * `Tooltip`, `Toast`, `DisclosureRow`, `StateDot`, `PathLabel`, the settings\n * form suite). This module only styles what primitives do not cover: page\n * scaffolding, field layout, banners, empty states and scroll regions.\n *\n * The metrics below are transcribed from the primitives' own CSS modules so a\n * feature panel lines up pixel-for-pixel with a native one: the 14/22 body and\n * 13/20 compact type tiers, the 0.5px hairline scale, and the elevation family\n * that draws a surface's edge in its shadow (`border: 0`) instead of a border.\n */\n\n/**\n * Every `--dsw-*` token this repo is allowed to reference, grouped by role.\n *\n * Plugins may only colour through this list. It is exported so the guard test\n * can fail a build when a stylesheet reaches for anything else — the failure\n * mode this prevents is silent: an unknown token resolves to nothing, so a\n * border disappears or a label inherits the wrong colour with no error anywhere.\n */\nexport const OFFICIAL_THEME_TOKENS = {\n /** Surfaces, from the page up to the topmost nested card. */\n surface: [\n '--dsw-alias-bg-base',\n '--dsw-alias-bg-layer-1',\n '--dsw-alias-bg-layer-2',\n '--dsw-alias-bg-layer-3',\n '--dsw-alias-bg-layer-4',\n '--dsw-alias-bg-module-platform',\n '--dsw-alias-bg-overlay',\n ],\n /** Hairlines. l1 is near-invisible on a menu surface, so menus use l2+. */\n border: ['--dsw-alias-border-l1', '--dsw-alias-border-l2', '--dsw-alias-border-l3', '--dsw-alias-border-l4'],\n /** Text. `caption` is menu shortcut text, `dimmed` is placeholder text. */\n label: [\n '--dsw-alias-label-primary',\n '--dsw-alias-label-secondary',\n '--dsw-alias-label-tertiary',\n '--dsw-alias-label-caption',\n '--dsw-alias-label-dimmed',\n '--dsw-alias-label-error',\n '--dsw-alias-label-primary-foreground',\n ],\n /** Interactive fills. The `-danger` hover belongs to destructive rows. */\n interactive: [\n '--dsw-alias-interactive-bg-hover',\n '--dsw-alias-interactive-bg-active',\n '--dsw-alias-interactive-bg-hover-danger',\n ],\n /** Accent and status. `business` is the focus ring's default colour. */\n accent: [\n '--dsw-alias-brand-primary',\n '--dsw-alias-button-primary-fill',\n '--dsw-alias-button-primary-hover',\n '--dsw-alias-button-tool-bar-fill',\n '--dsw-alias-button-tool-bar-hover',\n '--dsw-alias-button-ghost-active-fill',\n '--dsw-alias-button-ghost-active-border',\n ],\n state: [\n '--dsw-alias-state-business-primary',\n '--dsw-alias-state-success-primary',\n '--dsw-alias-state-warn-primary',\n '--dsw-alias-state-error-primary',\n '--dsw-alias-state-idle-primary',\n ],\n /** Corner scale: sm 8, md 12, lg the large card, panel the modal. */\n radius: ['--dsw-radius-sm', '--dsw-radius-md', '--dsw-radius-lg', '--dsw-radius-panel'],\n /** An elevated surface draws its edge in the shadow, so it keeps border: 0. */\n elevation: [\n '--dsw-elevation-soft',\n '--dsw-elevation-stroke',\n '--dsw-elevation-stroke-color',\n '--dsw-elevation-panel',\n '--dsw-elevation-prominent',\n ],\n /** Floats, masks and scrollbars. */\n overlay: [\n '--dsw-menu-surface-fill',\n '--dsw-menu-backdrop-filter',\n '--dsw-mask-blur',\n '--dsw-alias-bg-mask-1',\n '--dsw-alias-menu-icon',\n '--dsw-alias-scrollbar-bg-l2',\n '--dsw-alias-scrollbar-hover-l2',\n '--dsw-shadow-lv3',\n ],\n /** Motion, focus and type axis, published by the host rather than by a component. */\n system: [\n '--dsw-focus-ring-width',\n '--dsw-focus-ring-color',\n '--dsw-font-markdown-code-font-family',\n '--ds-transition-duration',\n '--ds-ease-in-out',\n '--ds-font-family-code',\n '--dsh-scrollbar-thumb',\n '--dsh-scrollbar-thumb-hover',\n '--dsh-content-font-size-secondary',\n '--dsh-content-font-delta',\n '--dsh-frame-top-clearance',\n // Published by the conversation.input.model seat for narrow composer rows.\n '--dsh-composer-model-icon-display',\n '--dsh-composer-model-text-display',\n ],\n} as const\n\n/** Every official token name, flat. Used by the token guard test. */\nexport const OFFICIAL_THEME_TOKEN_NAMES: readonly string[] = Object.values(OFFICIAL_THEME_TOKENS).flat()\n\n/** The elevation steps a surface can be raised by, softest first. */\nexport type OfficialElevation = 'soft' | 'stroke' | 'panel' | 'prominent'\n\n/**\n * The host's focus ring shorthand, verbatim. Writing this per control is how\n * rings drift apart; a stylesheet that draws its own focus style should use\n * {@link officialFocus} instead. The colour fallback is the host's own default.\n */\nexport const OFFICIAL_FOCUS_RING =\n 'var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary))'\n\n/**\n * A complete `outline` declaration at the official geometry. `offset` defaults\n * to the 2px the native controls use; the host's inline field rules sit at 1px\n * and a segmented tab pulls the ring inside itself at -2px.\n */\nexport function officialFocus(offset = '2px'): string {\n return `outline: ${OFFICIAL_FOCUS_RING}; outline-offset: ${offset}`\n}\n\n/**\n * An elevated surface. The host draws a raised surface's edge inside its\n * shadow rather than as a border, so a card sets `border: 0` and takes the edge\n * from the elevation — which is also why its border stays off the alias-border\n * set that a flat, non-elevated rule would use.\n */\nexport function officialElevation(level: OfficialElevation): string {\n return `border: 0; box-shadow: var(--dsw-elevation-${level})`\n}\n\n/**\n * An elevated surface whose edge should read as a specific hairline. Rebinding\n * the stroke colour is how a menu card picks l1 while a panel picks l3, without\n * the two growing apart by hand.\n */\nexport function officialStrokedElevation(level: OfficialElevation, color: string): string {\n return `--dsw-elevation-stroke-color: ${color}; ${officialElevation(level)}`\n}\n\n/**\n * The shared stylesheet for a plugin UI, scoped under that plugin's root class.\n *\n * Scoping is what keeps this safe to always-bundle into every client: the rules\n * can only match inside the plugin's own subtree, so two plugins can both mount\n * `dsh-ui-card` without either styling the other's markup.\n *\n * Each recipe matches the root element *and* its descendants, because the\n * commonest arrangement is one element that is both — a surface that carries\n * the root class and `dsh-ui-card`, or a portaled dialog that is the root and\n * the `dsh-ui-surface`. A descendant-only scope would silently leave those\n * unstyled, with no error anywhere.\n *\n * A caveat worth knowing: `Modal` and `Menu` portal to `document.body`, so their\n * content leaves the plugin's subtree entirely. A portaled surface therefore\n * needs its own root class on an element inside the portal.\n *\n * Only patterns that primitives do not provide live here. If a control appears\n * below that `Button`/`Input`/`Switch`/`Tag`/`Menu` already covers, that is a\n * bug in this file: use the primitive and delete the recipe.\n */\nexport function officialUiCss(roots: string | readonly string[]): string {\n // One plugin often mounts several unrelated surfaces (a settings seat, a chat\n // card, a header menu), so the caller names every root. The rules below are\n // nested under a single selector list and use `&`, which the browser expands\n // per root — so one stylesheet covers all of them without duplicating itself.\n const scope = (typeof roots === 'string' ? [roots] : roots).map(root => `.${root}`).join(', ')\n const sheet = `\n/* Official DSH Web UI contract. Generated by @klarkxy/dsh-plugin-kit/official-ui.\n * Do not hand-edit the copy inside a plugin: change this module so every plugin\n * moves together. Scope: ${scope} */\n/* The scope rule below stays open for the whole sheet: every rule after it\n * nests with the parent selector, so one stylesheet can cover several unrelated\n * roots without leaking into a neighbouring plugin. Its closing brace is last. */\n${scope} {\n color: var(--dsw-alias-label-primary);\n font-family: inherit;\n font-size: 14px;\n line-height: 22px;\n min-width: 0;\n\n& *, & *::before, & *::after { box-sizing: border-box; }\n& h1, & h2, & h3, & h4, & p, & figure { margin: 0; }\n/* Keyboard focus only: pointer input keeps the native resting appearance. The\n * ring needs no radius of its own — the outline already follows the control's\n * own border-radius, and overriding it here would flatten every control. */\n& :focus-visible { ${officialFocus()}; }\n& [hidden] { display: none !important; }\n\n/* --- Type tiers. The same 14/22 and 13/20 steps the primitives use. --- */\n& .dsh-ui-title { font-size: 16px; line-height: 24px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-heading { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-compact { font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-meta { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-secondary); }\n& .dsh-ui-hint { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-error { font-size: 12px; line-height: 18px; color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-warn { color: var(--dsw-alias-state-warn-primary); }\n& .dsh-ui-success { color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-muted { color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-truncate { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n& .dsh-ui-wrap { min-width: 0; overflow-wrap: anywhere; }\n\n/* --- Layout scaffolding. --- */\n& .dsh-ui-stack { display: flex; flex-direction: column; gap: 12px; }\n& .dsh-ui-stack-lg { display: flex; flex-direction: column; gap: 20px; }\n/* Plugin detail pages share one reading column. These are layout recipes;\n * controls keep their own primitive styles. Form spacing follows the host's\n * settings-form/fields.module.css and SettingsForm.module.css. */\n& .dsh-ui-page { display: flex; flex-direction: column; gap: 16px; width: 100%; max-width: 760px; min-width: 0; }\n& .dsh-ui-form { display: flex; flex-direction: column; gap: 0; min-width: 0; }\n&.dsh-ui-form > .dsh-ui-field, & .dsh-ui-form > .dsh-ui-field { padding: 12px 0; }\n& .dsh-ui-form-footer { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; padding-top: 16px; min-width: 0; }\n& .dsh-ui-fields-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 20px; min-width: 0; margin: 0; padding: 0; border: 0; }\n@media (max-width: 560px) {\n & .dsh-ui-fields-grid { grid-template-columns: minmax(0, 1fr); }\n}\n& .dsh-ui-row { display: flex; align-items: center; gap: 8px; min-width: 0; }\n& .dsh-ui-row-wrap { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }\n& .dsh-ui-spacer { flex: 1; min-width: 0; }\n/* A 0.5px l2 rule is the host's section divider; reserve the same rhythm. */\n& .dsh-ui-divider { height: 0.5px; background: var(--dsw-alias-border-l2); }\n& .dsh-ui-section { display: flex; flex-direction: column; gap: 12px; padding-top: 16px; border-top: 0.5px solid var(--dsw-alias-border-l2); }\n\n/* --- Card: a raised surface whose edge lives in the shadow. --- */\n& .dsh-ui-card {\n ${officialElevation('stroke')}\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding: 16px;\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-alias-bg-layer-1);\n color: var(--dsw-alias-label-primary);\n min-width: 0;\n}\n& .dsh-ui-card--flat { border: 0.5px solid var(--dsw-alias-border-l3); box-shadow: none; }\n& .dsh-ui-card--nested { background: var(--dsw-alias-bg-layer-2); }\n& .dsh-ui-card--plain { background: none; }\n\n/* --- Field: label, control, help, error. The control itself is an\n * official primitive, so this only owns the vertical rhythm. --- */\n& .dsh-ui-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }\n& .dsh-ui-field + .dsh-ui-field { border-top: 0.5px solid var(--dsw-alias-border-l2); padding-top: 12px; }\n/* Grid fields share a row, so the stacked-field divider must not win later in\n * the cascade. Reset it here, after the field recipe. */\n& .dsh-ui-fields-grid > .dsh-ui-field { padding: 0; border: 0; }\n& .dsh-ui-label { display: flex; align-items: center; gap: 6px; font-size: 13px; line-height: 20px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n& .dsh-ui-label-row { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }\n& .dsh-ui-help { font-size: 12px; line-height: 1.6; color: var(--dsw-alias-label-secondary); }\n& .dsh-ui-help p { margin: 0; }\n& .dsh-ui-help p + p { margin-top: 8px; }\n& .dsh-ui-required { color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-control { width: 100%; min-width: 0; }\n/* An invalid control is marked on the control, not only in the message. */\n& .dsh-ui-control[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-readonly { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n& .dsh-ui-readonly > dt { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n& .dsh-ui-readonly > dd { margin: 0; font-size: 13px; line-height: 20px; overflow-wrap: anywhere; }\n\n/* --- Buttons row. A no-op container: it exists so actions line up on the\n * trailing edge the way every native panel does. --- */\n& .dsh-ui-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding-top: 4px; }\n& .dsh-ui-actions-end { justify-content: flex-end; }\n\n/* --- Banners. A banner is a left-rail notice, the shape used for warnings,\n * deprecations and blocking instructions. --- */\n& .dsh-ui-banner {\n display: flex;\n flex-direction: column;\n gap: 8px;\n padding: 10px 14px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-left: 3px solid var(--dsw-alias-state-warn-primary);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-1);\n font-size: 13px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n}\n& .dsh-ui-banner-title { font-weight: 500; color: var(--dsw-alias-state-warn-primary); }\n& .dsh-ui-banner--info { border-left-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-banner--danger { border-left-color: var(--dsw-alias-state-error-primary); }\n& .dsh-ui-banner--success { border-left-color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-banner p { margin: 0; }\n\n/* --- Inline notice: a transient confirmation with no chrome of its own. --- */\n& .dsh-ui-notice { display: flex; align-items: center; gap: 6px; font-size: 12px; line-height: 18px; color: var(--dsw-alias-state-success-primary); }\n& .dsh-ui-notice--error { color: var(--dsw-alias-state-error-primary); }\n\n/* --- Empty and loading states. Both sit in a dashed well so an empty panel\n * reads as \"nothing here yet\" rather than as a broken layout. --- */\n& .dsh-ui-empty {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 6px;\n padding: 20px 16px;\n border: 0.5px dashed var(--dsw-alias-border-l3);\n border-radius: var(--dsw-radius-md);\n font-size: 13px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n}\n& .dsh-ui-loading { display: flex; align-items: center; gap: 8px; padding: 20px 0; font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-secondary); }\n\n/* --- Selectable list. A row is a button-sized target with a hover fill and\n * a selected fill; the name carries the weight, the description does not. --- */\n& .dsh-ui-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; min-width: 0; }\n& .dsh-ui-list-scroll { max-height: min(66vh, 760px); overflow-y: auto; overflow-x: hidden; }\n& .dsh-ui-list-row { border-radius: var(--dsw-radius-md); }\n& .dsh-ui-list-row:hover { background: var(--dsw-alias-interactive-bg-hover); }\n& .dsh-ui-list-row[aria-selected='true'], & .dsh-ui-list-row[data-selected] { background: var(--dsw-alias-interactive-bg-active); }\n& .dsh-ui-list-item {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 4px;\n width: 100%;\n min-width: 0;\n padding: 10px 12px;\n border: 0;\n border-radius: var(--dsw-radius-md);\n background: none;\n font: inherit;\n color: inherit;\n text-align: start;\n cursor: pointer;\n}\n& .dsh-ui-list-item:disabled { cursor: default; }\n& .dsh-ui-list-item:disabled:hover { background: none; }\n& .dsh-ui-list-name { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); overflow-wrap: anywhere; }\n& .dsh-ui-list-desc { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n\n/* --- Code and structured output. Wraps rather than scrolls, because a\n * feature panel is read rather than scanned. --- */\n& .dsh-ui-code {\n padding: 10px 12px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-1);\n font-family: var(--ds-font-family-code);\n font-size: 12px;\n line-height: 20px;\n color: var(--dsw-alias-label-secondary);\n overflow-wrap: anywhere;\n white-space: pre-wrap;\n}\n& .dsh-ui-scroll { max-height: 60vh; overflow: auto; overscroll-behavior: contain; }\n\n/* --- A toggle row: label on the left, switch on the trailing edge. This is\n * layout only; the switch itself is the official primitive. --- */\n& .dsh-ui-toggle-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-width: 0; padding: 12px 0; }\n& .dsh-ui-toggle-row + .dsh-ui-toggle-row { border-top: 0.5px solid var(--dsw-alias-border-l2); }\n& .dsh-ui-toggle-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n& .dsh-ui-toggle-label { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n\n/* --- Floating surface: a panel anchored to a trigger. This is the material\n * a menu card is made of — the translucent fill plus its backdrop blur, with\n * the edge riding inside the prominent elevation. A plugin that hand-rolls this\n * is how tokens like --dsw-specific-menu get invented; use this instead. --- */\n& .dsh-ui-surface {\n --dsw-elevation-stroke-color: var(--dsw-alias-border-l1);\n --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);\n --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);\n position: relative;\n display: flex;\n flex-direction: column;\n border: 0;\n border-radius: var(--dsw-radius-lg);\n background: var(--dsw-menu-surface-fill);\n backdrop-filter: var(--dsw-menu-backdrop-filter);\n box-shadow: var(--dsw-elevation-prominent);\n color: var(--dsw-alias-label-primary);\n font-size: 13px;\n line-height: 20px;\n min-width: 0;\n}\n& .dsh-ui-surface-body { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px 14px; overflow-y: auto; }\n& .dsh-ui-surface-head { display: flex; align-items: center; gap: 8px; min-width: 0; }\n& .dsh-ui-surface-title { font-size: 14px; line-height: 22px; font-weight: 500; color: var(--dsw-alias-label-primary); }\n\n/* --- Native select. The primitives ship no select, so a plugin that offers a\n * closed list of choices keeps the platform control and matches the official\n * settings field geometry exactly (34px, 0.5px l4, radius-md, layer-3). A\n * SegmentedControl is the primitive to reach for when the choices are few\n * enough to show at once. --- */\n& .dsh-ui-select {\n box-sizing: border-box;\n width: 100%;\n min-width: 0;\n height: 34px;\n padding: 0 12px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-3);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n color: var(--dsw-alias-label-primary);\n cursor: pointer;\n}\n& .dsh-ui-select:focus-visible { outline: none; border-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-select:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; }\n& .dsh-ui-select[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n\n/* --- Native textarea. The primitives ship no textarea either, so a settings\n * prompt keeps the platform element and the same field shell as the select:\n * 0.5px l4, radius-md, layer-3, 13/1.5 type. It grows vertically instead of\n * locking to the select's 34px row. --- */\n& .dsh-ui-textarea {\n box-sizing: border-box;\n width: 100%;\n min-width: 0;\n resize: vertical;\n padding: 8px 12px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: var(--dsw-radius-md);\n background: var(--dsw-alias-bg-layer-3);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n color: var(--dsw-alias-label-primary);\n}\n& .dsh-ui-textarea:focus-visible { outline: none; border-color: var(--dsw-alias-state-business-primary); }\n& .dsh-ui-textarea:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; }\n& .dsh-ui-textarea::placeholder { color: var(--dsw-alias-label-dimmed); }\n& .dsh-ui-textarea[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); }\n\n/* Long panels scroll inside themselves instead of growing the host page. */\n& .dsh-ui-panel { display: flex; flex-direction: column; gap: 16px; min-width: 0; }\n& .dsh-ui-panel-wide { max-width: 100%; }\n\n@media (prefers-reduced-motion: reduce) {\n & *, & *::before, & *::after { transition-duration: 0.01ms !important; animation-duration: 0.01ms !important; }\n}\n}\n`\n // Widen every recipe from \"a descendant of the root\" to \"the root, or one of\n // its descendants\". Written as a transform rather than by hand so no recipe\n // can be added later with only the descendant form. The pattern is narrow on\n // purpose: a leading `&` followed by one recipe class and no combinator, so\n // sibling and child rules such as `.dsh-ui-field + .dsh-ui-field` keep their\n // own meaning and are left alone.\n return sheet.replace(/^& (\\.dsh-ui-[a-z0-9-]+)(?=\\s*\\{)/gm, (_match, className: string) =>\n `&${className}, & ${className}`)\n}\n","import type { ContextFormed } from '@deepseek-ai/dsh-llm'\nimport { modelRouteOverride, type ModelRoute } from '@klarkxy/dsh-model-route'\n\n/**\n * The canonical home is @klarkxy/dsh-model-route; re-exported here so existing\n * plugin-kit consumers keep compiling.\n */\nexport type { ModelRoute }\n\n/** Public, browser-safe contracts. Host implementations stay in their owning packages. */\nexport type ProducerSourceKind = `plugin:${string}`\nexport type ProducerMessageSource = { kind: ProducerSourceKind; plugin: string } & ContextFormed\n\n/**\n * V4 sessions persist the producing extension in `kind`; the retired generic\n * `plugin` wrapper is not admitted. Each feature plugin declares its own kind.\n */\ndeclare module '@deepseek-ai/dsh-llm' {\n interface MessageSourceMap {\n [kind: ProducerSourceKind]: ProducerMessageSource\n }\n}\n\nexport function producerMessageSource(plugin: string): ProducerMessageSource {\n return { kind: `plugin:${plugin}`, plugin }\n}\n\nexport type RpcResult<T = unknown> = { ok: true; value: T } | { ok: false; error: { code: string; message: string } }\nexport const CHAT_EVENTS_SLOT = 'dsh-editor.chat.events'\nexport interface EvidenceRef { sessionId: string; seq: number; kind: 'user' | 'tool' | 'turn' | 'manual'; excerpt?: string }\nexport interface TaskContract {\n id: string\n sessionId: string\n sourceVersion: string\n revision: number\n goal: string\n deliverables: string[]\n inScope: string[]\n outOfScope: string[]\n constraints: string[]\n acceptance: string[]\n assumptions: string[]\n questions: string[]\n evidence: EvidenceRef[]\n readiness: 'pending' | 'clear-request' | 'user-confirmed' | 'disclosed-assumptions' | 'cancelled' | 'stale'\n updatedAt: number\n}\nexport interface TaskCheckpoint {\n id: string\n sessionId: string\n sourceVersion: string\n contractVersion?: number\n fromSeq: number\n toSeq: number\n revision: number\n status: 'running' | 'completed' | 'failed' | 'cancelled'\n items: Array<{ label: string; state: 'pending' | 'verified' | 'failed'; evidence: EvidenceRef[] }>\n constraints: string[]\n nextAction: string\n createdAt: number\n}\nexport type KnowledgeScope = { kind: 'global' } | { kind: 'project'; projectId: string }\nexport type KnowledgeKind = 'preference' | 'project-fact' | 'decision' | 'vocabulary' | 'activity' | 'lesson'\n/** Descriptive context, never an executable instruction or authorization. */\nexport interface ContextKnowledge {\n subject: string\n domain: string\n key: string\n aliases: string[]\n observedAt: number\n /** The user's own time expression, not an inferred completion date. */\n eventTime?: string\n activityStatus?: 'planned' | 'in-progress' | 'blocked' | 'paused' | 'completed' | 'cancelled' | 'unknown'\n}\n/** A scoped method. Observations remain candidates until explicitly accepted. */\nexport interface ProcedureKnowledge {\n origin: 'instruction' | 'observation'\n goal: string\n when: string[]\n steps: string[]\n avoid: string[]\n verify: string[]\n}\nexport interface MemoryRecord {\n id: string\n revision: number\n scope: KnowledgeScope\n kind: KnowledgeKind\n status: 'candidate' | 'active' | 'rejected' | 'superseded' | 'revoked' | 'deleted'\n title: string\n content: string\n tags: string[]\n evidence: EvidenceRef[]\n exceptions: string[]\n source: 'user' | 'memory' | 'dream' | 'self-improvement'\n context?: ContextKnowledge\n procedure?: ProcedureKnowledge\n createdAt: number\n updatedAt: number\n expiresAt?: number\n supersedes?: string[]\n /** Exact record revisions behind a derived candidate; revalidated on adoption. */\n basis?: Array<{ id: string; revision: number }>\n}\nexport type NewMemoryRecord = Omit<MemoryRecord, 'id' | 'revision' | 'createdAt' | 'updatedAt'>\nexport interface MemoryQuery { scope: KnowledgeScope; query?: string; kinds?: KnowledgeKind[]; statuses?: MemoryRecord['status'][]; limit?: number }\nexport interface MemoryMutationOptions { signal?: AbortSignal; isCurrent?: () => boolean }\nexport interface MemoryService {\n list(query: MemoryQuery): Promise<MemoryRecord[]>\n create(record: NewMemoryRecord, options?: MemoryMutationOptions): Promise<MemoryRecord>\n update(id: string, patch: Partial<Pick<MemoryRecord, 'title' | 'content' | 'tags' | 'exceptions' | 'status' | 'expiresAt'>>, expectedRevision: number, options?: MemoryMutationOptions): Promise<MemoryRecord>\n /** Explicit user promotion, persisted atomically on the same record; preserves expiry and evidence. */\n promoteToGlobal(id: string, expectedRevision: number, options?: MemoryMutationOptions): Promise<MemoryRecord>\n remove(id: string, expectedRevision: number, options?: MemoryMutationOptions): Promise<void>\n recall(query: MemoryQuery): Promise<MemoryRecord[]>\n}\n\n/**\n * The session creation metadata the host snapshots when it creates a delegated child\n * thread. Mirrors `CreateAgentOptions.meta` in `@deepseek-ai/dsh-agent`; it is durable\n * session data, so it survives a restart and needs no ancestry walk.\n */\nexport interface SubagentSessionLike {\n readonly header?: {\n readonly parentSession?: unknown\n readonly origin?: unknown\n readonly delegationDepth?: unknown\n readonly isSeeded?: unknown\n readonly classification?: unknown\n }\n}\n\n/**\n * True when `session` is a delegated child thread rather than a human-driven top-level\n * conversation.\n *\n * A message's `source.kind === 'user'` cannot answer this: a lead agent's dispatch prompt\n * is delivered as the child's own user message, so delegated work is indistinguishable\n * from a person typing once you only look at the message. Plugins use this to keep\n * automatic writes and derived model calls on top-level sessions.\n */\nexport function isSubagentSession(session: unknown): boolean {\n const header = (session as SubagentSessionLike | null | undefined)?.header\n if (!header || typeof header !== 'object') return false\n if (header.origin === 'subagent' || Number(header.delegationDepth ?? 0) > 0) return true\n // Native human forks also persist parentSession for history lineage. A fork's\n // seeded header distinguishes it from legacy children whose parent is the\n // only marker. Native rc.2 forks omit depth; patched hosts may persist zero.\n // Explicit delegation and unknown metadata still keep the child guard.\n const humanFork = header.isSeeded === true\n && (header.delegationDepth === undefined || header.delegationDepth === 0)\n && header.origin === undefined\n && (header.classification === undefined || header.classification === 'ordinary' || header.classification === 'free')\n return Boolean(header.parentSession) && !humanFork\n}\n\n/** Project keys come only from the host-validated session directory, never client input. */\nexport function projectIdFromCwd(cwd: string | undefined): string | undefined {\n if (typeof cwd !== 'string') return undefined\n const normalized = cwd.trim().replaceAll('\\\\', '/')\n if (!normalized) return undefined\n return normalized === '/' || /^[A-Za-z]:\\/$/.test(normalized) ? normalized : normalized.replace(/\\/+$/, '')\n}\n\n/**\n * One settings owner's Remote stream. Typert accepts either case in an RPC\n * segment, so the Cordis service key and the wire namespace use the same\n * Pascal segment. The scope's first letter stays uppercase.\n */\nexport interface ModelSettingsChangesIdentity {\n readonly service: string\n readonly namespace: string\n}\n\n/** `@klarkxy/dsh-git-commit` becomes `KlarkxyDshGitCommitModelSettingsChanges`. */\nexport function modelSettingsChangesIdentity(packageName: string): ModelSettingsChangesIdentity {\n const scoped = /^@([^/]+)\\/(.+)$/.exec(packageName)\n const body = scoped ? `${scoped[1]}/${scoped[2]}` : packageName\n const parts = body.split(/[^A-Za-z0-9]+/).filter(Boolean)\n if (!parts.length) throw new Error('Model settings package name has no RPC segment')\n const segment = `${parts.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('')}ModelSettingsChanges`\n if (!/^[A-Z][A-Za-z0-9]*$/.test(segment)) throw new Error(`Model settings sync name is not an RPC segment: ${segment}`)\n return { service: segment, namespace: segment }\n}\n\n/**\n * Repository extension: a native web provider announces that its local\n * availability changed. Kind is `search` or `fetch`; id is the provider id.\n * Listeners refresh management state and must not treat this as a network probe.\n */\nexport const WEB_PROVIDER_AVAILABILITY_EVENT = 'web/provider-availability-updated' as const\n\n/**\n * Optional display metadata a provider may attach when it registers directly\n * with `ctx.web`. Execution and credentials stay with the provider; this object\n * is display-only and must never carry secret values.\n */\nexport interface DshWebManagementDescriptor {\n readonly id: string\n readonly label: string\n readonly description: string\n readonly defaultBaseURL?: string\n readonly credentialRef?: string\n /** True when the key is shared with another surface. The page must not delete it. */\n readonly credentialShared?: boolean\n /** Optional notice naming the settings surface that owns a shared credential. */\n readonly credentialHint?: string\n readonly billing: 'request' | 'model-and-tools' | 'none' | 'unknown'\n /** Optional provider-supplied billing summary. */\n readonly pricing?: string\n /** Public HTTPS page explaining provider charges. */\n readonly pricingUrl?: string\n /** Public HTTPS page where the user can create an API key. */\n readonly signupUrl?: string\n /** Plugin that owns configuration. Native providers keep their settings there. */\n readonly configurationOwner?: string\n /** Explicit settings link supplied by the provider, never inferred from its id. */\n readonly configurationUrl?: string\n /** Fixed legacy route migrated by a bundle-owned adapter; not used by native plugins. */\n readonly legacyId?: string\n}\n\n/**\n * Host Creator agent-preset id (`agentPresets.composedPreset`).\n * Plugins that gate Creator-only tools or prompt sections compare against this.\n */\nexport const CREATOR_PRESET_ID = 'cordis'\n\n/**\n * Shared \"Session Management\" settings section id. The section is provided by\n * shared infrastructure (see `registerSessionSettingsItem` in `client-utils`),\n * not by any one business plugin: every participant registers only a row into\n * {@link SESSION_SETTINGS_ITEM_SLOT}, so any enabled subset yields the same page.\n */\nexport const SESSION_SETTINGS_SECTION_ID = 'session-manager'\n\n/**\n * Child list slot declared by the shared Session Management page. Neutral\n * naming on purpose: participants never import each other, they only\n * contribute `{id, order}` rows into this slot while the page is alive.\n */\nexport const SESSION_SETTINGS_ITEM_SLOT = 'dsh.session-settings.item'\n\n/**\n * Host-owned nav icon seat: a root-scoped list where each entry's `id` must\n * equal the `settings.section` id it decorates. Owner props are\n * `{size, active}`; icons stay `aria-hidden` so the section label remains the\n * accessible name. Contributors into a shared section may register the same\n * icon `id` with different priorities — the ledger keeps every entry while the\n * host renders one icon per section.\n */\nexport const SETTINGS_SECTION_ICON_SLOT = 'settings.section.icon'\n\n/* Shared auxiliary-model default. Feature plugins may store a global default\n * route that fills the tier between their own saved override and the live\n * session model. The durable state is a root-context singleton (like the\n * shared session-settings page): it exists while any participant retains it\n * and is never owned by a business plugin. See `auxiliary-model.ts`. */\n\n/** Root context service key holding the shared auxiliary-model state. */\nexport const AUXILIARY_MODEL_SERVICE = 'dshAuxiliaryModel'\n\n/** Authenticated host-RPC channel for get/set of the shared default. */\nexport const AUXILIARY_MODEL_CHANNEL = '/dsh-auxiliary-model'\n\n/** Model-settings namespace under which the shared default is published. */\nexport const AUXILIARY_MODEL_NS = '@klarkxy/dsh-plugin-kit/auxiliary-model'\n\n/**\n * Typert identity of the shared change stream. Mounted on the root context\n * with ownerNs filtering, so frames only carry {@link AUXILIARY_MODEL_NS}.\n */\nexport const AUXILIARY_MODEL_CHANGES_IDENTITY = modelSettingsChangesIdentity('@klarkxy/dsh-plugin-kit')\n\n/** The value the shared default persists: `model: null` means follow the live session/host model. */\nexport interface AuxiliaryModelDefaults {\n readonly revision: number\n readonly model: ModelRoute | null\n}\n\n/** Shape of the root singleton; produced and owned by `auxiliary-model.ts`. */\nexport interface AuxiliaryModelShared {\n readonly ready: Promise<void>\n snapshot(): AuxiliaryModelDefaults\n}\n\nfunction sharedAuxiliaryModel(host: unknown): AuxiliaryModelShared | undefined {\n const root = (host as { root?: unknown } | undefined)?.root as { get?(name: string, strict?: boolean): unknown } | undefined\n try {\n const shared = root?.get?.(AUXILIARY_MODEL_SERVICE, false) as AuxiliaryModelShared | undefined\n return shared && typeof shared.snapshot === 'function' ? shared : undefined\n } catch { return undefined }\n}\n\n/**\n * Synchronously read the shared auxiliary default; `undefined` only when no\n * participant retains the singleton or the default is legitimately unset.\n * An initialization or snapshot failure propagates: silently falling back to\n * a different model after a storage error would spend the wrong budget.\n */\nexport function getAuxiliaryModel(host: unknown): ModelRoute | undefined {\n const shared = sharedAuxiliaryModel(host)\n if (!shared) return undefined\n return modelRouteOverride(shared.snapshot().model ?? undefined)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport { createElement, useCallback, useEffect, useRef, useSyncExternalStore, type ReactNode } from 'react'\nimport { SESSION_SETTINGS_ITEM_SLOT, SESSION_SETTINGS_SECTION_ID, SETTINGS_SECTION_ICON_SLOT } from './contracts.ts'\nimport type { PluginLogger } from './log-shared.ts'\n\n/** Fixed pause for failing background reads; manual work is never replayed. */\nexport function createPluginReadGate(now: () => number = Date.now, logger?: PluginLogger) {\n let pausedUntil = 0\n let epoch = 0\n return {\n canRead: () => now() >= pausedUntil,\n reset: () => { epoch++; pausedUntil = 0 },\n async run<T>(read: () => Promise<T>): Promise<T> {\n const current = epoch\n try {\n const value = await read()\n if (current === epoch) {\n if (pausedUntil > 0) logger?.debug('read-gate.resumed', 'Background read gate recovered.')\n pausedUntil = 0\n }\n return value\n } catch (error) {\n // The native Connection error is an Error with this exact HTTP text.\n // Authentication, application failures, and cancellation stay distinct.\n const message = error instanceof Error ? error.message : ''\n if (current === epoch && (/(?:^|\\s)transport failure for .+: HTTP (?:404|405|503)\\b/.test(message)\n || (error instanceof TypeError && /^(?:Failed to fetch|fetch failed|NetworkError when attempting to fetch resource\\.?)$/i.test(message)))) {\n pausedUntil = now() + 30_000\n logger?.warn('read-gate.paused', 'Background reads paused for 30s after transport failure.', error)\n }\n throw error\n }\n },\n }\n}\n\nexport interface NativeSurfaceClient {\n sessions: {\n binding?(sessionId: string): { eventSource: { subscribe(listener: () => void): () => void } } | undefined\n }\n uiWorkspace: { current?: { getSnapshot(): { sessionId: string } | undefined; subscribe(listener: () => void): () => void } }\n uiSession: { adapter: { current: { getSnapshot(): { key?: string }; subscribe(listener: () => void): () => void } } }\n locale: { getSnapshot(): { active: string }; subscribe(listener: () => void): () => void }\n connection?: { generation?: { subscribe(listener: () => void): () => void } }\n}\n\n/** The Editor retains its manuscript session separately; native DSH exposes the main-view binding. */\nexport function selectedSessionId(client: Pick<NativeSurfaceClient, 'uiWorkspace' | 'uiSession'>): string {\n const workspace = client.uiWorkspace?.current\n return workspace\n ? workspace.getSnapshot()?.sessionId ?? ''\n : client.uiSession.adapter.current.getSnapshot().key ?? ''\n}\n\n/**\n * Owner props are data the host composed, never a Cordis context: reading an\n * undeclared property off one throws instead of returning undefined, which\n * would crash the slot entry and abdicate its cell for good. Tolerate a\n * throwing read so a mistaken prop degrades to \"not supplied\".\n */\nfunction read(source: unknown, key: string): unknown {\n if (source === null || typeof source !== 'object') return undefined\n try {\n return (source as Record<string, unknown>)[key]\n } catch {\n return undefined\n }\n}\n\nfunction readString(source: unknown, key: string): string | undefined {\n const value = read(source, key)\n return typeof value === 'string' ? value : undefined\n}\n\n/** Owner props win; native settings only supplies close, so resolve its selected session. */\nexport function useNativeSeat(client: NativeSurfaceClient, props?: unknown) {\n const current = useSyncExternalStore(\n useCallback((fn: () => void) => (client.uiWorkspace?.current ?? client.uiSession.adapter.current).subscribe(fn), [client]),\n useCallback(() => selectedSessionId(client), [client]),\n () => '',\n )\n const language = useSyncExternalStore(\n useCallback((fn: () => void) => client.locale.subscribe(fn), [client]),\n useCallback(() => client.locale.getSnapshot().active, [client]),\n () => 'en',\n )\n const sessionId = readString(props, 'sessionId') ?? readString(read(props, 'owner'), 'sessionId') ?? current\n const requestedLocale = read(props, 'locale') ?? read(read(props, 'owner'), 'locale') ?? language\n return { sessionId, locale: (String(requestedLocale).startsWith('zh') ? 'zh' : 'en') as 'zh' | 'en',\n hidden: read(props, 'hidden') === true || read(read(props, 'owner'), 'hidden') === true }\n}\n\n/** Refresh on native log boundaries/reconnect/focus. Read-only settling is bounded to an observed job. */\nexport function useFeatureRefresh(\n client: NativeSurfaceClient, sessionId: string, refresh: () => void,\n working = false, enabled = true,\n): void {\n const refreshRef = useRef(refresh)\n refreshRef.current = refresh\n useEffect(() => {\n if (!enabled) return\n let timer: ReturnType<typeof setTimeout> | undefined\n const queue = () => {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return\n clearTimeout(timer)\n timer = setTimeout(() => refreshRef.current(), 150)\n }\n const source = sessionId ? client.sessions.binding?.(sessionId)?.eventSource : undefined\n const stopEvents = source?.subscribe(queue)\n const stopConnection = client.connection?.generation?.subscribe(queue)\n const visibility = () => { if (document.visibilityState === 'visible') queue() }\n window.addEventListener('focus', queue)\n document.addEventListener('visibilitychange', visibility)\n // Details are collapsed by default; opening an existing panel must get current state.\n document.addEventListener('toggle', queue, true)\n return () => {\n clearTimeout(timer)\n stopEvents?.(); stopConnection?.()\n window.removeEventListener('focus', queue)\n document.removeEventListener('visibilitychange', visibility)\n document.removeEventListener('toggle', queue, true)\n }\n }, [client, sessionId, enabled])\n useEffect(() => {\n if (!enabled || !working) return\n let delay = 250\n const until = Date.now() + 300_000\n let timer: ReturnType<typeof setTimeout>\n const tick = () => {\n if (Date.now() >= until) return\n if (document.visibilityState !== 'hidden') refreshRef.current()\n delay = Math.min(delay * 2, 2000)\n timer = setTimeout(tick, delay)\n }\n timer = setTimeout(tick, delay)\n return () => clearTimeout(timer)\n }, [client, sessionId, working, enabled])\n}\n\n/* Shared \"Session Management\" settings page. The page is root-owned shared\n * infrastructure, not a business plugin: any participant alone yields the same\n * section, and participants never import each other. Synchronization crosses\n * separately bundled copies of this helper through the Cordis root context —\n * `root.get`/`root.provide` is the only rendezvous, so no window global or\n * module singleton is needed and no participant depends on another being enabled.\n */\n\n/** A row contributed into the shared Session Management page. */\nexport interface SessionSettingsItemSpec {\n readonly id: string\n readonly order: number\n}\n\n/* Original line icons for settings-section navigation seats. The official\n * `dsh-client-ui-primitives` icon set covers generic glyphs only; these keep\n * the same conventions (16×16 viewBox, 1px stroke, round caps, currentColor)\n * so the plugin set stays visually consistent with the native nav. Colors\n * never appear here: `currentColor` lets the host style the active state, and\n * `aria-hidden` keeps the section label the single accessible name. */\n\n/** Owner props the host's `settings.section.icon` seat hands to its cell. */\nexport interface SettingsSectionIconProps {\n readonly size?: number\n /** Selection state; the nav styles active icons through color, not geometry. */\n readonly active?: boolean\n}\n\ntype IconChild = readonly [tag: string, attrs: Record<string, string | number>]\n\n/** One `<svg>` with the shared icon chrome; children are plain elements. */\nfunction lineIcon(children: IconChild[]) {\n return function SettingsSectionIcon(props: SettingsSectionIconProps): ReactNode {\n return createElement('svg', {\n 'aria-hidden': 'true',\n width: props.size ?? 16,\n height: props.size ?? 16,\n viewBox: '0 0 16 16',\n fill: 'none',\n stroke: 'currentColor',\n strokeWidth: 1,\n strokeLinecap: 'round',\n strokeLinejoin: 'round',\n }, ...children.map(([tag, attrs], index) => createElement(tag, { key: index, ...attrs })))\n }\n}\n\n/** Chat bubble for the shared Session Management section. */\nexport const IconSessionSettings = lineIcon([\n ['path', { d: 'M8.5 13a5.5 5.5 0 0 0 5.5-5.5A5.5 5.5 0 0 0 8.5 2 5.5 5.5 0 0 0 3 7.5a5.48 5.48 0 0 0 .9 3L2.8 12.6a.5.5 0 0 0 .62.62l2.9-.98a5.48 5.48 0 0 0 2.18.76Z' }],\n])\n\n/** Serif-flavoured letter A for the Font section. */\nexport const IconFontSettings = lineIcon([\n ['path', { d: 'M3.3 12.6 7.9 3.1a.5.5 0 0 1 .9 0l4.6 9.5' }],\n ['path', { d: 'M5.2 9.4h6.3' }],\n ['path', { d: 'M2.4 12.6h2.4' }],\n ['path', { d: 'M11.9 12.6h2.4' }],\n])\n\n/** Keyboard for the Shortcuts section. */\nexport const IconKeyboardSettings = lineIcon([\n ['rect', { x: 1.75, y: 4.75, width: 12.5, height: 7.5, rx: 1.2 }],\n ['path', { d: 'M4.5 7.25h0' }],\n ['path', { d: 'M8 7.25h0' }],\n ['path', { d: 'M11.5 7.25h0' }],\n ['path', { d: 'M5.25 9.75h5.5' }],\n])\n\n/** Linked model nodes for the Model Management section. */\nexport const IconModelNetworkSettings = lineIcon([\n ['line', { x1: 10.6, y1: 5.3, x2: 8.8, y2: 7.1 }],\n ['line', { x1: 7.2, y1: 8.9, x2: 5.4, y2: 10.7 }],\n ['circle', { cx: 12, cy: 4, r: 1.9 }],\n ['circle', { cx: 4, cy: 12, r: 1.9 }],\n ['circle', { cx: 8, cy: 8, r: 1.5 }],\n])\n\n/**\n * Contribute the nav icon of a `settings.section` entry. The `settings\n * .section.icon` seat is declared by the host independently of the section\n * list, so the wait runs in parallel: the icon appears as soon as both seats\n * exist and unloading removes it again, restoring the host's default glyph.\n * The `id` must equal the section id; `order`/`priority` mirror `order` so the\n * icon cell sorts like its section and, for shared sections, several\n * contributors can register the same icon id under different priorities\n * without duplicating nav entries.\n */\nexport function registerSettingsSectionIcon(\n ctx: Context,\n sectionId: string,\n order: number,\n component: (props: SettingsSectionIconProps) => ReactNode,\n): () => void {\n const slots = (ctx as unknown as { slots: SessionSettingsSlots }).slots\n return slots.inject(SETTINGS_SECTION_ICON_SLOT, () =>\n slots.register({ name: SETTINGS_SECTION_ICON_SLOT, id: sectionId, order, priority: order }, component))\n}\n\ninterface SessionSettingsSlots {\n inject(key: string, callback: () => Iterable<(() => void) | void> | (() => void) | void): () => void\n register(spec: Record<string, unknown>, render: unknown): () => void\n}\n\ninterface SessionSettingsRoot {\n get(name: string, strict?: boolean): unknown\n provide(name: string, value: unknown): () => void\n readonly slots?: SessionSettingsSlots\n}\n\n/** Private Cordis rendezvous; every bundled copy of this helper resolves the same root service. */\nconst SESSION_SETTINGS_PAGE_SERVICE = 'dshSessionSettingsPage'\n\ninterface SessionSettingsPage {\n retain(): void\n release(): void\n}\n\n/** The page component renders only its declared child list: items paint their own titles and styles. */\nfunction SessionSettingsPageView(props: { renderSlot: (key: string, owner: Record<string, never>) => ReactNode }): ReactNode {\n return props.renderSlot(SESSION_SETTINGS_ITEM_SLOT, {})\n}\n\n/**\n * Acquire the root-owned page service, creating and providing it on first use.\n * One counter covers participants, the section wait and the provider: the last\n * release removes the wait and then the provider synchronously (Cordis deletes\n * the impl before its async disposer awaits), so a later acquire sees a clean\n * get() miss and can re-establish the page.\n */\nfunction acquireSessionSettingsPage(root: SessionSettingsRoot): SessionSettingsPage {\n const existing = root.get(SESSION_SETTINGS_PAGE_SERVICE, false) as SessionSettingsPage | undefined\n if (existing) return existing\n const slots = root.slots as SessionSettingsSlots\n let users = 0\n let stopPage: (() => void) | undefined\n let unprovide: (() => void) | undefined\n const page: SessionSettingsPage = {\n retain() {\n // The reservation is counted before the throwing install, so a failure\n // lets the caller's release() undo it fully instead of leaking the service.\n users += 1\n if (!stopPage) {\n stopPage = slots.inject('settings.section', () => slots.register(\n {\n name: 'settings.section',\n id: SESSION_SETTINGS_SECTION_ID,\n order: 30,\n label: () => {\n const locale = root.get('locale', false) as { getSnapshot?(): { active?: unknown } } | undefined\n return String(locale?.getSnapshot?.().active ?? '').startsWith('zh') ? '会话管理' : 'Session Management'\n },\n children: { [SESSION_SETTINGS_ITEM_SLOT]: { kind: 'list', scope: 'root' } },\n },\n SessionSettingsPageView,\n ))\n }\n },\n release() {\n if (users <= 0) return\n users -= 1\n if (users > 0) return\n // The last contributor tears the section down; collapsing its children\n // declaration clears the item slot for every other bundle as well.\n stopPage?.()\n stopPage = undefined\n unprovide?.()\n },\n }\n unprovide = root.provide(SESSION_SETTINGS_PAGE_SERVICE, page)\n return page\n}\n\n/**\n * Contribute one row to the shared Session Management settings page.\n *\n * `ctx` is the plugin's own context: the row's slot wait unloads with the\n * plugin, while the page itself is retained on the shared root context for as\n * long as any contributor lives. There is no fallback seat — when every\n * contributor is gone the section disappears with the page. Returns a disposer.\n * Shared root-owned infrastructure (the auxiliary-model card) calls this on\n * `ctx.root` so its row, icon and page share are owned by the root lifetime\n * and released by the returned disposer, not by any plugin fiber.\n */\nexport function registerSessionSettingsItem(\n ctx: Context,\n item: SessionSettingsItemSpec,\n component: (props: never) => ReactNode,\n): () => void {\n const slots = (ctx as unknown as { slots: SessionSettingsSlots }).slots\n const root = ctx.root as unknown as SessionSettingsRoot\n const page = acquireSessionSettingsPage(root)\n let stopItem: (() => void) | undefined\n let stopIcon: (() => void) | undefined\n try {\n page.retain()\n stopItem = slots.inject(SESSION_SETTINGS_ITEM_SLOT, () => slots.register({ name: SESSION_SETTINGS_ITEM_SLOT, ...item }, component))\n // Every contributor also waits on the nav-icon seat, registering the same\n // section icon id under its own priority (its row order). Same-id entries\n // coexist on the ledger while the host renders one icon, so no contributor\n // owns the icon and none depends on another for it; the wait lives with\n // this ctx, so it fires now on fresh loads and retro-fills on HMR.\n stopIcon = slots.inject(SETTINGS_SECTION_ICON_SLOT, () => slots.register(\n { name: SETTINGS_SECTION_ICON_SLOT, id: SESSION_SETTINGS_SECTION_ID, order: item.order, priority: item.order },\n IconSessionSettings,\n ))\n } catch (error) {\n // A synchronous failure (for example a duplicate row id or a failing page\n // install) must not pin the shared page for a contributor that never joined.\n stopIcon?.()\n stopItem?.()\n page.release()\n throw error\n }\n // The disposer may be invoked by both ctx.effect and an explicit caller;\n // releasing twice would unbalance the shared refcount.\n let disposed = false\n return () => {\n if (disposed) return\n disposed = true\n stopIcon?.()\n stopItem?.()\n page.release()\n }\n}\n","export type PluginLogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fault'\n\nexport const PLUGIN_LOG_LEVELS: readonly PluginLogLevel[] = ['debug', 'info', 'warn', 'error', 'fault']\nexport const DEFAULT_PLUGIN_LOG_LEVEL: PluginLogLevel = 'info'\nexport const PLUGIN_LOG_MAX_MESSAGE_CHARS = 16_000\nexport const PLUGIN_LOG_MAX_CONTEXT_CHARS = 8_000\n\nexport type PluginLogScalar = string | number | boolean | null\nexport type PluginLogContext = Record<string, PluginLogScalar | undefined>\n\nexport interface PluginLogInput {\n level: PluginLogLevel\n event: string\n message: string\n context?: PluginLogContext\n error?: unknown\n}\n\nexport interface PluginLogError {\n name: string\n message: string\n stack?: string\n code?: string\n}\n\nexport interface PluginLogEntry {\n version: 1\n at: string\n level: PluginLogLevel\n source: string\n surface: 'host' | 'client'\n profile?: string\n event: string\n message: string\n pid?: number\n context?: Record<string, PluginLogScalar>\n error?: PluginLogError\n}\n\nexport interface PluginLogger {\n readonly source: string\n readonly file: string | null\n readonly lastWriteError: string | null\n debug(event: string, message: string, context?: PluginLogContext): boolean\n info(event: string, message: string, context?: PluginLogContext): boolean\n warn(event: string, message: string, error?: unknown, context?: PluginLogContext): boolean\n error(event: string, message: string, error?: unknown, context?: PluginLogContext): boolean\n fault(event: string, message: string, error?: unknown, context?: PluginLogContext): boolean\n write(input: PluginLogInput): boolean\n child(context: PluginLogContext): PluginLogger\n}\n\nconst SOURCE_RE = /^[a-z][a-z0-9-]{0,63}$/\nconst EVENT_RE = /^[a-z][a-z0-9._-]{0,127}$/\nconst CONTEXT_KEY_RE = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/\nconst SECRET_KEY_RE = /(?:api[_-]?key|access[_-]?token|refresh[_-]?token|bearer|authorization|cookie|set[_-]?cookie|nonce|credential|private[_-]?key|password|secret|app[_-]?secret|client[_-]?secret|z_c0|d_c0)$/i\n\nconst CHAT_PAYLOAD_RE =\n /\"role\"\\s*:\\s*\"(?:system|user|assistant|tool)\"|\"(?:messages|content|prompt|input_text|input_image|image_url)\"\\s*:\\s*[\\[{\"']/i\nconst CREDENTIAL_BODY_RE =\n /-----BEGIN (?:RSA |EC |OPENSSH |PRIVATE )?PRIVATE KEY-----|\"type\"\\s*:\\s*\"service_account\"|credentials\\.json|\\.dsh[/\\\\](?:credentials|auth)/i\nconst AUTH_HEADER_RE = /\\b(Authorization|Proxy-Authorization|Cookie|Set-Cookie)\\s*:\\s*[^\\r\\n]*/gi\nconst BEARER_RE = /\\bBearer\\s+[A-Za-z0-9._\\-+=/]{8,}/g\nconst SECRET_FIELD_RE =\n /([\"']?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|bearer|authorization|cookie|set-cookie|nonce|credential|private[_-]?key|password|secret|app[_-]?secret|client[_-]?secret|password|z_c0|d_c0)[\"']?\\s*[:=]\\s*)(?:\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*'|[^\\s,&;}]+)/gi\nconst SECRET_QUERY_RE =\n /([?&](?:token|api[_-]?key|key|secret|password|bootstrap|code|sig|signature|credential|password)=)[^\\s&#\"']+/gi\nconst URL_CREDENTIAL_RE = /\\b(https?:\\/\\/)[^\\s/:@]+:[^\\s/@]+@/gi\nconst BOOTSTRAP_RE = /\\/bootstrap\\/[^\\s\"'?&#]+/gi\nconst KNOWN_TOKEN_RE = /\\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{20,}|tvly-[A-Za-z0-9_-]{10,}|AKIA[0-9A-Z]{16})\\b/g\nconst PATH_RE = /(?:[A-Za-z]:\\\\|\\\\\\\\)[^\\s\"'`<>|]+|(?:\\/(?:home|Users|tmp|var|root)\\/|~\\/)[^\\s\"'`<>|]+/g\n\nexport function isPluginLogLevel(value: unknown): value is PluginLogLevel {\n return typeof value === 'string' && (PLUGIN_LOG_LEVELS as readonly string[]).includes(value)\n}\n\nexport function pluginLogLevelEnabled(level: PluginLogLevel, minimum: PluginLogLevel): boolean {\n return PLUGIN_LOG_LEVELS.indexOf(level) >= PLUGIN_LOG_LEVELS.indexOf(minimum)\n}\n\nexport function normalizePluginLogSource(raw: string): string {\n const stripped = String(raw || '').trim().replace(/^@[^/]+\\//, '').toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '')\n const prefixed = /^[a-z]/.test(stripped) ? stripped : `p-${stripped}`\n const bounded = prefixed.slice(0, 64).replace(/-+$/g, '')\n return SOURCE_RE.test(bounded) ? bounded : 'dsh-plugin'\n}\n\nexport function normalizePluginLogEvent(raw: string): string {\n const cleaned = String(raw || '').trim().toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-').replace(/^[^a-z]+/, '').slice(0, 128)\n return EVENT_RE.test(cleaned) ? cleaned : 'plugin.event'\n}\n\n/**\n * Parse a level specification like `debug` or `dsh-zhihu=debug,dsh-dot:warn,info`.\n * Source-specific rules win over a bare fallback level.\n */\nexport function parsePluginLogLevel(\n spec: string | undefined | null,\n source?: string,\n fallback: PluginLogLevel = DEFAULT_PLUGIN_LOG_LEVEL,\n): PluginLogLevel {\n if (!spec || typeof spec !== 'string') return fallback\n const normalizedSource = source ? normalizePluginLogSource(source) : undefined\n let wildcard: PluginLogLevel | undefined\n for (const token of spec.split(',').map(part => part.trim()).filter(Boolean)) {\n const lowered = token.toLowerCase()\n if (isPluginLogLevel(lowered)) {\n wildcard = lowered\n continue\n }\n const match = /^([^=:]+)[=:]([a-z]+)$/i.exec(token)\n if (!match) continue\n const target = match[1]!.trim()\n const candidate = match[2]!.trim().toLowerCase()\n if (!isPluginLogLevel(candidate)) continue\n if (target === '*') {\n wildcard = candidate\n continue\n }\n if (normalizedSource && normalizePluginLogSource(target) === normalizedSource) {\n return candidate\n }\n }\n return wildcard ?? fallback\n}\n\nexport function sanitizePluginLogText(text: string, maxChars = PLUGIN_LOG_MAX_MESSAGE_CHARS): string {\n if (!text) return ''\n if (CREDENTIAL_BODY_RE.test(text)) return '[omitted credential material]'\n if (CHAT_PAYLOAD_RE.test(text)) return '[omitted chat payload]'\n const redacted = text\n .replace(AUTH_HEADER_RE, '$1: [redacted]')\n .replace(BEARER_RE, 'Bearer [redacted]')\n .replace(SECRET_FIELD_RE, (full, prefix: string) => {\n const value = full.slice(prefix.length)\n if (value.startsWith('\"')) return `${prefix}\"[redacted]\"`\n if (value.startsWith(\"'\")) return `${prefix}'[redacted]'`\n return `${prefix}[redacted]`\n })\n .replace(SECRET_QUERY_RE, '$1[redacted]')\n .replace(URL_CREDENTIAL_RE, '$1[redacted]@')\n .replace(BOOTSTRAP_RE, '/bootstrap/[redacted]')\n .replace(KNOWN_TOKEN_RE, '[redacted]')\n .replace(PATH_RE, '[path]')\n return truncateLogText(redacted, maxChars)\n}\n\nexport function sanitizePluginLogContext(\n input: PluginLogContext | undefined,\n): Record<string, PluginLogScalar> | undefined {\n if (!input) return undefined\n const output: Record<string, PluginLogScalar> = {}\n for (const [key, value] of Object.entries(input).slice(0, 32)) {\n if (value === undefined || !CONTEXT_KEY_RE.test(key)) continue\n if (typeof value === 'number' && !Number.isFinite(value)) continue\n if (SECRET_KEY_RE.test(key)) {\n output[key] = '[redacted]'\n continue\n }\n output[key] = typeof value === 'string' ? sanitizePluginLogText(value, 1_000) : value\n }\n if (!Object.keys(output).length) return undefined\n const encoded = JSON.stringify(output)\n if (encoded.length <= PLUGIN_LOG_MAX_CONTEXT_CHARS) return output\n return { omitted: true, reason: 'Diagnostic context exceeded its size limit.' }\n}\n\nexport function sanitizePluginLogError(error: unknown): PluginLogError | undefined {\n if (error === undefined) return undefined\n const row = error && typeof error === 'object'\n ? error as { name?: unknown; message?: unknown; stack?: unknown; code?: unknown }\n : {}\n const rawMessage = typeof row.message === 'string' ? row.message : String(error)\n const result: PluginLogError = {\n name: typeof row.name === 'string' && row.name.trim() ? sanitizePluginLogText(row.name.trim(), 100) : 'Error',\n message: sanitizePluginLogText(rawMessage) || 'Unknown error',\n }\n if (typeof row.stack === 'string' && row.stack.trim()) {\n result.stack = sanitizePluginLogText(row.stack, 24_000)\n }\n if (typeof row.code === 'string' && /^[A-Za-z0-9_./:-]{1,100}$/.test(row.code)) {\n result.code = sanitizePluginLogText(row.code, 100)\n } else if (typeof row.code === 'number' && Number.isFinite(row.code)) {\n result.code = String(row.code)\n }\n return result\n}\n\nexport function mergePluginLogContext(\n base: PluginLogContext | undefined,\n extra: PluginLogContext | undefined,\n): PluginLogContext | undefined {\n if (!base) return extra\n if (!extra) return base\n return { ...base, ...extra }\n}\n\nexport function buildPluginLogEntry(\n input: PluginLogInput,\n meta: {\n at: Date\n source: string\n surface: 'host' | 'client'\n profile?: string\n pid?: number\n correlation?: PluginLogContext\n },\n): PluginLogEntry {\n const entry: PluginLogEntry = {\n version: 1,\n at: meta.at.toISOString(),\n level: isPluginLogLevel(input.level) ? input.level : 'info',\n source: normalizePluginLogSource(meta.source),\n surface: meta.surface,\n ...(meta.profile ? { profile: meta.profile } : {}),\n event: normalizePluginLogEvent(input.event),\n message: sanitizePluginLogText(input.message || 'No diagnostic message was provided.', PLUGIN_LOG_MAX_MESSAGE_CHARS),\n ...(meta.pid !== undefined ? { pid: meta.pid } : {}),\n }\n const context = sanitizePluginLogContext(mergePluginLogContext(meta.correlation, input.context))\n if (context) entry.context = context\n const error = sanitizePluginLogError(input.error)\n if (error) entry.error = error\n return entry\n}\n\nexport function createChildPluginLogger(parent: PluginLogger, bound: PluginLogContext): PluginLogger {\n return {\n get source() { return parent.source },\n get file() { return parent.file },\n get lastWriteError() { return parent.lastWriteError },\n debug: (event, message, context) => parent.debug(event, message, mergePluginLogContext(bound, context)),\n info: (event, message, context) => parent.info(event, message, mergePluginLogContext(bound, context)),\n warn: (event, message, error, context) => parent.warn(event, message, error, mergePluginLogContext(bound, context)),\n error: (event, message, error, context) => parent.error(event, message, error, mergePluginLogContext(bound, context)),\n fault: (event, message, error, context) => parent.fault(event, message, error, mergePluginLogContext(bound, context)),\n write: input => parent.write({ ...input, context: mergePluginLogContext(bound, input.context) }),\n child: next => createChildPluginLogger(parent, mergePluginLogContext(bound, next) ?? {}),\n }\n}\n\nexport function truncateLogText(text: string, maxChars: number): string {\n if (text.length <= maxChars) return text\n const marker = '[truncated]\\n'\n if (maxChars <= marker.length) return text.slice(0, Math.max(0, maxChars))\n return `${marker}${text.slice(-(maxChars - marker.length))}`\n}\n","import {\n DEFAULT_PLUGIN_LOG_LEVEL, buildPluginLogEntry, createChildPluginLogger,\n normalizePluginLogSource, parsePluginLogLevel, pluginLogLevelEnabled,\n sanitizePluginLogText,\n type PluginLogContext, type PluginLogEntry, type PluginLogInput,\n type PluginLogLevel, type PluginLogger,\n} from './log-shared.ts'\n\nexport * from './log-shared.ts'\n\nexport const CLIENT_PLUGIN_LOG_GLOBAL = '__KLARKXY_PLUGIN_LOGS__'\nexport const CLIENT_PLUGIN_LOG_LIMIT = 500\n\nexport interface ClientPluginLoggerOptions {\n minimumLevel?: PluginLogLevel\n now?: () => Date\n bufferLimit?: number\n forwardToHostLogger?: boolean\n loadedContext?: PluginLogContext\n}\n\ntype BrowserContextLike = {\n effect?: (callback: () => () => void, label?: string) => unknown\n logger?: {\n warn?: (...args: unknown[]) => void\n error?: (...args: unknown[]) => void\n }\n}\n\ntype GlobalLogCarrier = {\n [CLIENT_PLUGIN_LOG_GLOBAL]?: PluginLogEntry[]\n window?: { localStorage?: { getItem?: (key: string) => string | null } }\n console?: {\n debug?: (...args: unknown[]) => void\n info?: (...args: unknown[]) => void\n warn?: (...args: unknown[]) => void\n error?: (...args: unknown[]) => void\n }\n}\n\nfunction readStorageFlag(key: string): string | undefined {\n try {\n const win = (globalThis as unknown as GlobalLogCarrier).window\n const storage = win?.localStorage\n const value = storage?.getItem?.(key)\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n } catch {\n return undefined\n }\n}\n\nfunction sharedClientBuffer(limit: number): PluginLogEntry[] {\n const carrier = globalThis as unknown as GlobalLogCarrier\n if (!Array.isArray(carrier[CLIENT_PLUGIN_LOG_GLOBAL])) {\n try {\n carrier[CLIENT_PLUGIN_LOG_GLOBAL] = []\n } catch {\n return []\n }\n }\n const list = carrier[CLIENT_PLUGIN_LOG_GLOBAL]!\n const overflow = list.length - limit\n if (overflow > 0) list.splice(0, overflow)\n return list\n}\n\nexport function readClientPluginLogs(source?: string): PluginLogEntry[] {\n const carrier = globalThis as unknown as GlobalLogCarrier\n const list = Array.isArray(carrier[CLIENT_PLUGIN_LOG_GLOBAL]) ? carrier[CLIENT_PLUGIN_LOG_GLOBAL]! : []\n if (!source) return list.slice()\n const normalized = normalizePluginLogSource(source)\n return list.filter(entry => entry.source === normalized)\n}\n\nexport function clearClientPluginLogs(): void {\n const carrier = globalThis as unknown as GlobalLogCarrier\n if (Array.isArray(carrier[CLIENT_PLUGIN_LOG_GLOBAL])) {\n carrier[CLIENT_PLUGIN_LOG_GLOBAL]!.length = 0\n }\n}\n\nexport function createClientPluginLogger(\n source: string,\n ctx?: unknown,\n options: ClientPluginLoggerOptions = {},\n): PluginLogger {\n const normalized = normalizePluginLogSource(source)\n const now = options.now ?? (() => new Date())\n const limit = Math.max(10, options.bufferLimit ?? CLIENT_PLUGIN_LOG_LIMIT)\n const browserCtx = ctx && typeof ctx === 'object' ? ctx as BrowserContextLike : undefined\n\n const resolveMinimum = (): PluginLogLevel => {\n if (options.minimumLevel) return options.minimumLevel\n return parsePluginLogLevel(readStorageFlag('dsh-plugin-log-level'), normalized, DEFAULT_PLUGIN_LOG_LEVEL)\n }\n\n const logger: PluginLogger = {\n source: normalized,\n file: null,\n lastWriteError: null,\n debug: (event, message, context) => logger.write({ level: 'debug', event, message, ...(context ? { context } : {}) }),\n info: (event, message, context) => logger.write({ level: 'info', event, message, ...(context ? { context } : {}) }),\n warn: (event, message, error, context) => logger.write({\n level: 'warn', event, message,\n ...(error !== undefined ? { error } : {}),\n ...(context ? { context } : {}),\n }),\n error: (event, message, error, context) => logger.write({\n level: 'error', event, message,\n ...(error !== undefined ? { error } : {}),\n ...(context ? { context } : {}),\n }),\n fault: (event, message, error, context) => logger.write({\n level: 'fault', event, message,\n ...(error !== undefined ? { error } : {}),\n ...(context ? { context } : {}),\n }),\n child: context => createChildPluginLogger(logger, context),\n write(input: PluginLogInput): boolean {\n try {\n if (!pluginLogLevelEnabled(input.level, resolveMinimum())) return false\n const entry = buildPluginLogEntry(input, {\n at: now(),\n source: normalized,\n surface: 'client',\n })\n const buffer = sharedClientBuffer(limit)\n buffer.push(entry)\n const overflow = buffer.length - limit\n if (overflow > 0) buffer.splice(0, overflow)\n\n if (options.forwardToHostLogger !== false && browserCtx?.logger) {\n const summary = sanitizePluginLogText(`${normalized} [${entry.event}]: ${entry.message}`, 500)\n if (entry.level === 'warn' && typeof browserCtx.logger.warn === 'function') {\n browserCtx.logger.warn(summary)\n } else if ((entry.level === 'error' || entry.level === 'fault') && typeof browserCtx.logger.error === 'function') {\n browserCtx.logger.error(summary)\n }\n }\n if (readStorageFlag('dsh-plugin-log-console') === '1') {\n const con = (globalThis as unknown as GlobalLogCarrier).console\n const fn = entry.level === 'debug' ? con?.debug\n : entry.level === 'info' ? con?.info\n : entry.level === 'warn' ? con?.warn\n : con?.error\n fn?.call(con, `[${normalized}] ${entry.event}: ${entry.message}`, entry)\n }\n return true\n } catch {\n return false\n }\n },\n }\n return logger\n}\n\nexport function installClientPluginLogger(\n ctx: unknown,\n source: string,\n options: ClientPluginLoggerOptions = {},\n): PluginLogger {\n const logger = createClientPluginLogger(source, ctx, options)\n logger.info('client.loaded', 'Client plugin initialized.', options.loadedContext)\n const browserCtx = ctx && typeof ctx === 'object' ? ctx as BrowserContextLike : undefined\n if (typeof browserCtx?.effect === 'function') {\n try {\n browserCtx.effect(() => () => {\n logger.debug('client.disposed', 'Client plugin disposed.')\n }, `${logger.source}.client-logger`)\n } catch {\n // Non-Cordis mock context.\n }\n }\n return logger\n}\n\nexport async function clientLogStep<T>(\n logger: PluginLogger,\n step: string,\n context: PluginLogContext | undefined,\n action: () => Promise<T>,\n completedLevel: PluginLogLevel = 'debug',\n): Promise<T> {\n const started = Date.now()\n const base = { ...context, step }\n logger.debug('step.started', 'Client step started.', base)\n try {\n const result = await action()\n logger.write({\n level: completedLevel,\n event: 'step.completed',\n message: 'Client step completed.',\n context: { ...base, durationMs: Date.now() - started },\n })\n return result\n } catch (error) {\n logger.error('step.failed', 'Client step failed.', error, {\n ...base,\n durationMs: Date.now() - started,\n })\n throw error\n }\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport { migrateFontPreferences, type FontRole, type FontTheme, type FontThemeSnapshot } from './preferences.ts'\nimport { Button, IconChevronDownOutlineRegular, IconChevronUpOutlineRegular, Input } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { officialUiCss } from '@klarkxy/dsh-plugin-kit/official-ui'\nimport { IconFontSettings, registerSettingsSectionIcon } from '@klarkxy/dsh-plugin-kit/client-utils'\nimport { createClientPluginLogger, installClientPluginLogger } from '@klarkxy/dsh-plugin-kit/client-logger'\nimport { useId, useState, useSyncExternalStore } from 'react'\nimport {\n CODE_FONT_PRESETS, CONVERSATION_FONT_SELECTOR, FONT_SIZE_SPECS,\n PLUGIN_NAME, UI_FONT_PRESETS,\n conversationFontDeclarations, createConversationFontStore, createFontSettingsStore,\n fontStackFor, fontTokenDeclarations, normalizeFontFamily,\n presetFor, systemFontLabel, uniqueSystemFonts,\n type ConversationFontStore, type FontGenericFamily, type FontPreset, type FontSettings,\n type FontSettingsStorage, type SystemFontFamily,\n} from './contracts.ts'\n\nexport const name = 'dsh-font-client'\nexport const inject = ['slots', 'theme', 'locale'] as const\n\n/** The settings.section contribution spec: the shell nav reads id/order/label\n * (label may be a thunk resolved at read time); owner props carry `close`. */\ninterface SettingsSectionSpec {\n name: 'settings.section'\n id: string\n order: number\n label: () => string\n}\n/** A cell inside a declared list slot: id + order, with priority deciding which\n * entry renders when several share one id (lowest wins). */\ninterface SettingsItemSpec {\n name: string\n id: string\n order: number\n priority?: number\n}\n\ntype Client = {\n theme: FontTheme\n locale: { getSnapshot(): { active: string }; subscribe(fn: () => void): () => void }\n slots: {\n inject(key: string, callback: () => unknown): () => void\n register(spec: SettingsSectionSpec | SettingsItemSpec, render: unknown): () => void\n }\n on(event: 'theme/change', listener: (snapshot: FontThemeSnapshot) => void): () => void\n}\n\nconst COPY = {\n zh: {\n label: '字体',\n uiFont: '界面字体',\n conversationFont: '对话字体',\n codeFont: '代码字体',\n terminalFont: '终端字体',\n textSize: '字号大小',\n textSizeHelp: '仅影响会话内容的字号',\n codeSize: '代码字号',\n codeSizeHelp: '用于代码块、行内代码与工具输出',\n terminalSize: '终端字号',\n terminalSizeHelp: '用于侧栏终端',\n increaseSize: (label: string) => `增大${label}`,\n decreaseSize: (label: string) => `减小${label}`,\n sizeUnit: 'px',\n defaultOption: '默认',\n followUi: '跟随界面字体',\n customOption: '自定义…',\n customUiPlaceholder: '例如 \"Microsoft YaHei\", sans-serif',\n customConversationPlaceholder: '例如 \"Source Han Serif SC\", serif',\n customCodePlaceholder: '例如 \"JetBrains Mono\", monospace',\n customTerminalPlaceholder: '例如 \"Cascadia Mono\", monospace',\n uiHelp: '作用于整个界面的文字,对话字体跟随它时也包括对话区。自定义时输入完整的 font-family 字体栈,留空恢复默认。',\n conversationHelp: '作用于对话区的消息和输入框,适合为长文单独选择字体(如衬线体)。仅保存在当前浏览器。',\n codeHelp: '作用于代码块、行内代码与工具输出。',\n terminalHelp: '作用于侧栏终端,与代码字体独立。',\n loadFonts: '读取系统字体',\n reloadFonts: '重新读取系统字体',\n loadingFonts: '正在读取系统字体…',\n fontsLoaded: (count: number) => `已读取 ${count} 款系统字体;新装字体后点「重新读取」刷新列表。`,\n fontsPartial: '列表来自浏览器枚举:仅安装到当前用户的字体可能不在其中,可以直接输入字体名使用。',\n fontsDenied: '系统字体读取被拒绝或当前环境不支持,仍可手动输入字体名。',\n systemGroup: '系统字体',\n resetFonts: '恢复默认字体',\n resetSizes: '恢复默认字号',\n },\n en: {\n label: 'Font',\n uiFont: 'Interface font',\n conversationFont: 'Conversation font',\n codeFont: 'Code font',\n terminalFont: 'Terminal font',\n textSize: 'Font size',\n textSizeHelp: 'Only affects conversation content',\n codeSize: 'Code font size',\n codeSizeHelp: 'Used for code blocks, inline code, and tool output',\n terminalSize: 'Terminal font size',\n terminalSizeHelp: 'Used for the sidebar terminal',\n increaseSize: (label: string) => `Increase ${label.toLowerCase()}`,\n decreaseSize: (label: string) => `Decrease ${label.toLowerCase()}`,\n sizeUnit: 'px',\n defaultOption: 'Default',\n followUi: 'Same as interface font',\n customOption: 'Custom…',\n customUiPlaceholder: 'e.g. \"Microsoft YaHei\", sans-serif',\n customConversationPlaceholder: 'e.g. \"Source Han Serif SC\", serif',\n customCodePlaceholder: 'e.g. \"JetBrains Mono\", monospace',\n customTerminalPlaceholder: 'e.g. \"Cascadia Mono\", monospace',\n uiHelp: 'Applies to all interface text, including the conversation while the conversation font follows it. For a custom value enter a full font-family stack; empty restores the default.',\n conversationHelp: 'Applies to messages and the input box in the conversation, e.g. a serif face for long text. Saved in this browser only.',\n codeHelp: 'Applies to code blocks, inline code, and tool output.',\n terminalHelp: 'Applies to the sidebar terminal, independent of the code font.',\n loadFonts: 'Load system fonts',\n reloadFonts: 'Reload system fonts',\n loadingFonts: 'Loading system fonts…',\n fontsLoaded: (count: number) => `${count} installed fonts loaded; choose “Reload system fonts” after installing new ones.`,\n fontsPartial: 'The list comes from the browser’s enumeration: fonts installed only for the current user may be missing — you can still type the family name directly.',\n fontsDenied: 'Access to system fonts was denied or is unsupported here; you can still type a font name.',\n systemGroup: 'Installed fonts',\n resetFonts: 'Reset fonts',\n resetSizes: 'Reset font sizes',\n },\n} as const\n\nexport function fontCopy(locale: 'zh' | 'en') {\n return COPY[locale]\n}\n\n/* The rows mirror the native Settings → General item geometry (16px padding,\n * 0.5px l2 hairline, 14/22 title over a 12/18 description, a 240px trailing\n * control) so the group reads like the General column — no card, no page\n * chrome. Everything visual still comes from the shared recipes and tokens.\n * The stepper reproduces the native FontSizeRow pill: centered value, hover or\n * focus-within reveals the up/down arrow column, px unit label after the pill. */\nconst styles = `${officialUiCss('font-root')}\n.font-root .font-row { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; padding: 16px 0; border-bottom: 0.5px solid var(--dsw-alias-border-l2); }\n.font-root .font-row-text { flex: 1; display: flex; flex-direction: column; gap: 4px; min-width: 0; padding-right: 40px; }\n.font-root .font-row-title { font-size: 14px; line-height: 22px; color: var(--dsw-alias-label-primary); }\n.font-root .font-row-desc { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary); }\n.font-root .font-row-control { display: inline-flex; align-items: center; gap: 8px; min-width: 0; }\n.font-root .font-select { flex: 0 1 240px; width: auto; }\n.font-root .font-custom { flex: 1 1 100%; }\n.font-root .font-stepper { display: inline-flex; align-items: center; justify-content: center; min-width: 72px; height: 36px; position: relative; border-radius: var(--dsw-radius-md); background: var(--dsw-alias-bg-module-platform); }\n.font-root .font-stepper-value { min-width: 18px; text-align: center; font-variant-numeric: tabular-nums; font-size: 14px; line-height: 22px; color: var(--dsw-alias-label-primary); }\n.font-root .font-stepper-unit { font-size: 14px; line-height: 22px; color: var(--dsw-alias-label-secondary); }\n.font-root .font-stepper-arrows { position: absolute; right: 8px; display: flex; flex-direction: column; gap: 2px; opacity: 0; }\n.font-root .font-stepper:focus-within .font-stepper-arrows { opacity: 1; }\n@media (hover:hover) { .font-root .font-stepper:hover .font-stepper-arrows { opacity: 1; } }\n@media (hover:none) { .font-root .font-stepper-arrows { opacity: 1; } }\n.font-root .font-stepper-arrow { width: 17px; height: 12px; padding: 0; display: inline-flex; align-items: center; justify-content: center; border: none; border-radius: var(--dsw-radius-sm); background: color-mix(in srgb, var(--dsw-alias-bg-layer-1) 75%, transparent); color: var(--dsw-alias-label-primary); cursor: pointer; }\n@media (hover:hover) { .font-root .font-stepper-arrow:hover:not(:disabled) { background: var(--dsw-alias-bg-layer-1); } }\n.font-root .font-stepper-arrow:disabled { color: var(--dsw-alias-label-caption); cursor: default; }\n/* The last row keeps the hairline off the page's bottom edge, mirroring the\n * host's own last-child rule inside a settings column. */\n.font-root > :last-child, .font-root > :last-child > :last-child { border-bottom: none; }\n@media (max-width: 767px) {\n .font-root .font-row-text { padding-right: 16px; }\n .font-root .font-select { flex: 0 1 auto; width: 240px; max-width: 100%; }\n}\n`\n\nfunction readStorage(): FontSettingsStorage | undefined {\n try {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n } catch {\n return undefined\n }\n}\n\nfunction useLocale(client: Client): 'zh' | 'en' {\n const getSnapshot = () => (client.locale.getSnapshot().active.toLowerCase().startsWith('zh') ? 'zh' : 'en') as 'zh' | 'en'\n return useSyncExternalStore(\n fn => client.locale.subscribe(fn),\n getSnapshot,\n getSnapshot,\n )\n}\n\nfunction presetMode(value: string, presets: readonly FontPreset[]): string {\n return presetFor(value, presets)?.id ?? (value ? 'custom' : '')\n}\n\n/** One font-family row in the native compact shape: title and description on\n * the left, a preset picker on the trailing edge, the custom stack input\n * wrapping to a full line when the picker is on Custom. */\nexport function FontField(props: {\n label: string\n help: string\n value: string\n presets: readonly FontPreset[]\n locale: 'zh' | 'en'\n generic: FontGenericFamily\n systemFonts?: readonly SystemFontFamily[]\n defaultLabel: string\n customLabel: string\n customPlaceholder: string\n systemGroupLabel: string\n onCommit(value: string): void\n}) {\n const labelId = useId()\n // undefined = not editing; the input otherwise shows the committed stack.\n const [draft, setDraft] = useState<string | undefined>(undefined)\n // With an empty (default) value nothing matches \"custom\" on its own, so the\n // choice itself must be remembered until a stack is committed.\n const [customOpen, setCustomOpen] = useState(false)\n const mode = customOpen ? 'custom' : presetMode(props.value, props.presets)\n\n function commitDraft() {\n if (draft === undefined) return\n const next = normalizeFontFamily(draft)\n setDraft(undefined)\n if (!next) setCustomOpen(false)\n if (next !== props.value) props.onCommit(next)\n }\n\n return <div className=\"font-row\">\n <div className=\"font-row-text\">\n <div className=\"font-row-title\" id={labelId}>{props.label}</div>\n <div className=\"font-row-desc\">{props.help}</div>\n </div>\n <div className=\"font-row-control\">\n <select\n className=\"dsh-ui-select font-select\"\n aria-labelledby={labelId}\n value={mode}\n onChange={event => {\n const id = event.target.value\n setDraft(undefined)\n if (id === 'custom') { setCustomOpen(true); return }\n setCustomOpen(false)\n if (id.startsWith('sys:')) { props.onCommit(fontStackFor(id.slice(4), props.generic)); return }\n const preset = props.presets.find(item => item.id === id)\n props.onCommit(preset ? preset.value : '')\n }}\n >\n <option value=\"\">{props.defaultLabel}</option>\n {props.presets.map(preset => (\n <option key={preset.id} value={preset.id}>{preset.label[props.locale]}</option>\n ))}\n <option value=\"custom\">{props.customLabel}</option>\n {props.systemFonts && props.systemFonts.length > 0 ? <optgroup label={props.systemGroupLabel}>\n {props.systemFonts.map(item => <option key={item.family} value={`sys:${item.family}`}>{systemFontLabel(item, props.locale)}</option>)}\n </optgroup> : null}\n </select>\n </div>\n {mode === 'custom' ? <span className=\"font-custom\">\n <Input\n value={draft ?? props.value}\n placeholder={props.customPlaceholder}\n aria-label={props.label}\n onChange={event => setDraft(event.target.value)}\n onBlur={commitDraft}\n onKeyDown={event => { if (event.key === 'Enter') commitDraft() }}\n />\n </span> : null}\n </div>\n}\n\n/** One font-size row in the native stepper shape: title and description on the\n * left, a pill holding the centered value with a hover/focus-revealed up/down\n * arrow column, and the px unit label after it. The displayed value follows\n * the persisted setting through the theme service, never the click echo, and\n * the arrows clamp at the role's host bounds instead of asking the service to\n * reject an out-of-range write. */\nexport function FontSizeField(props: {\n label: string\n help: string\n role: FontRole\n value: number\n locale: 'zh' | 'en'\n increaseLabel: string\n decreaseLabel: string\n unit: string\n onCommit(role: FontRole, px: number): void\n}) {\n const labelId = useId()\n const { min, max } = FONT_SIZE_SPECS[props.role]\n return <div className=\"font-row\">\n <div className=\"font-row-text\">\n <div className=\"font-row-title\" id={labelId}>{props.label}</div>\n <div className=\"font-row-desc\">{props.help}</div>\n </div>\n <div className=\"font-row-control\">\n <div className=\"font-stepper\">\n <span className=\"font-stepper-value\" aria-labelledby={labelId}>{props.value}</span>\n <span className=\"font-stepper-arrows\">\n <button\n type=\"button\"\n className=\"font-stepper-arrow\"\n aria-label={props.increaseLabel}\n disabled={props.value >= max}\n onClick={() => props.onCommit(props.role, props.value + 1)}\n >\n <IconChevronUpOutlineRegular size={9} />\n </button>\n <button\n type=\"button\"\n className=\"font-stepper-arrow\"\n aria-label={props.decreaseLabel}\n disabled={props.value <= min}\n onClick={() => props.onCommit(props.role, props.value - 1)}\n >\n <IconChevronDownOutlineRegular size={9} />\n </button>\n </span>\n </div>\n <span className=\"font-stepper-unit\">{props.unit}</span>\n </div>\n </div>\n}\n\n/** The plugin's own settings page (Settings → Font): every font control in one\n * column — interface family, conversation family + content size, code family +\n * size, terminal family + size — followed by the shared actions. It writes the\n * same theme service entries the native General font-size cell uses, so sizes\n * and families stay in sync with any other writer (keyboard zoom included). */\nexport function FontSettingsGroup(props: {\n client: Client\n conversation: ConversationFontStore\n}) {\n const locale = useLocale(props.client)\n const text = COPY[locale]\n const snapshot = useSyncExternalStore(\n fn => props.client.on('theme/change', () => fn()),\n () => props.client.theme.getTheme(),\n () => props.client.theme.getTheme(),\n )\n const settings: FontSettings = { uiFont: snapshot.fontFamilies.text, codeFont: snapshot.fontFamilies.code }\n const terminalFont = snapshot.fontFamilies.terminal\n const conversationFont = useSyncExternalStore(\n fn => props.conversation.subscribe(fn),\n () => props.conversation.get(),\n () => props.conversation.get(),\n )\n // System font list is shared by the font fields: one permission prompt, one list.\n const [fontList, setFontList] = useState<{ state: 'idle' | 'loading' | 'ready' | 'denied'; families: readonly SystemFontFamily[] }>(\n { state: 'idle', families: [] },\n )\n\n async function loadSystemFonts() {\n if (fontList.state === 'loading') return\n // Every click re-enumerates: fonts installed after the first read appear\n // on the next one (the button relabels to \"reload\" once a list exists).\n // Local Font Access API: Chromium-only and gated behind a permission\n // prompt; anything else (Firefox, Safari, denied permission, Electron\n // policy) falls through to the preset + manual-input flow unchanged.\n const query = (globalThis as { queryLocalFonts?: () => Promise<readonly unknown[]> }).queryLocalFonts\n if (typeof query !== 'function') {\n createClientPluginLogger(PLUGIN_NAME).debug('system-fonts.unsupported', 'Local Font Access API is not available in this browser.')\n setFontList({ state: 'denied', families: [] })\n return\n }\n setFontList(current => ({ state: 'loading', families: current.families }))\n try {\n const fonts = await query()\n const families = uniqueSystemFonts(fonts)\n createClientPluginLogger(PLUGIN_NAME).info('system-fonts.loaded', 'Loaded system font families.', { count: families.length })\n setFontList({ state: 'ready', families })\n } catch (error) {\n createClientPluginLogger(PLUGIN_NAME).warn('system-fonts.denied', 'System font enumeration was denied or failed.', error)\n setFontList(current => ({ state: 'denied', families: current.families }))\n }\n }\n\n function updateFamily(role: FontRole, value: string) {\n props.client.theme.setFontFamily(role, normalizeFontFamily(value))\n }\n function updateSize(role: FontRole, px: number) {\n props.client.theme.setFontSize(role, px)\n }\n\n const sizeField = (role: FontRole, label: string, help: string) => (\n <FontSizeField\n label={label}\n help={help}\n role={role}\n value={snapshot.fontSizes[role]}\n locale={locale}\n increaseLabel={text.increaseSize(label)}\n decreaseLabel={text.decreaseSize(label)}\n unit={text.sizeUnit}\n onCommit={updateSize}\n />\n )\n\n return <div className=\"font-root\" role=\"group\" aria-label={text.label} data-testid=\"font-settings\">\n <FontField\n label={text.uiFont}\n help={text.uiHelp}\n value={settings.uiFont}\n presets={UI_FONT_PRESETS}\n locale={locale}\n generic=\"sans-serif\"\n systemFonts={fontList.families}\n defaultLabel={text.defaultOption}\n customLabel={text.customOption}\n customPlaceholder={text.customUiPlaceholder}\n systemGroupLabel={text.systemGroup}\n onCommit={value => updateFamily('text', value)}\n />\n <FontField\n label={text.conversationFont}\n help={text.conversationHelp}\n value={conversationFont}\n presets={UI_FONT_PRESETS}\n locale={locale}\n generic=\"sans-serif\"\n systemFonts={fontList.families}\n defaultLabel={text.followUi}\n customLabel={text.customOption}\n customPlaceholder={text.customConversationPlaceholder}\n systemGroupLabel={text.systemGroup}\n onCommit={value => props.conversation.set(value)}\n />\n {sizeField('text', text.textSize, text.textSizeHelp)}\n <FontField\n label={text.codeFont}\n help={text.codeHelp}\n value={settings.codeFont}\n presets={CODE_FONT_PRESETS}\n locale={locale}\n generic=\"monospace\"\n systemFonts={fontList.families}\n defaultLabel={text.defaultOption}\n customLabel={text.customOption}\n customPlaceholder={text.customCodePlaceholder}\n systemGroupLabel={text.systemGroup}\n onCommit={value => updateFamily('code', value)}\n />\n {sizeField('code', text.codeSize, text.codeSizeHelp)}\n <FontField\n label={text.terminalFont}\n help={text.terminalHelp}\n value={terminalFont}\n presets={CODE_FONT_PRESETS}\n locale={locale}\n generic=\"monospace\"\n systemFonts={fontList.families}\n defaultLabel={text.defaultOption}\n customLabel={text.customOption}\n customPlaceholder={text.customTerminalPlaceholder}\n systemGroupLabel={text.systemGroup}\n onCommit={value => updateFamily('terminal', value)}\n />\n {sizeField('terminal', text.terminalSize, text.terminalSizeHelp)}\n <div className=\"font-row\">\n <div className=\"font-row-text\">\n {fontList.state === 'ready' ? <div className=\"font-row-desc\" role=\"status\">{text.fontsLoaded(fontList.families.length)}</div> : null}\n {fontList.state === 'ready' ? <div className=\"font-row-desc\" role=\"status\">{text.fontsPartial}</div> : null}\n {fontList.state === 'denied' ? <div className=\"font-row-desc\" role=\"status\">{text.fontsDenied}</div> : null}\n </div>\n <div className=\"font-row-control\">\n <Button variant=\"outline\" size=\"sm\" disabled={fontList.state === 'loading'}\n onClick={() => { void loadSystemFonts() }}>\n {fontList.state === 'loading' ? text.loadingFonts : fontList.state === 'ready' ? text.reloadFonts : text.loadFonts}\n </Button>\n <Button variant=\"outline\" size=\"sm\" onClick={() => {\n updateFamily('text', '')\n updateFamily('code', '')\n updateFamily('terminal', '')\n props.conversation.set('')\n }}>{text.resetFonts}</Button>\n <Button variant=\"outline\" size=\"sm\" onClick={() => {\n updateSize('text', FONT_SIZE_SPECS.text.default)\n updateSize('code', FONT_SIZE_SPECS.code.default)\n updateSize('terminal', FONT_SIZE_SPECS.terminal.default)\n }}>{text.resetSizes}</Button>\n </div>\n </div>\n </div>\n}\n\nexport function apply(ctx: Context): void {\n const logger = installClientPluginLogger(ctx, PLUGIN_NAME)\n const client = ctx as unknown as Client & { effect: Context['effect'] }\n const store = createFontSettingsStore(readStorage())\n const conversation = createConversationFontStore(readStorage())\n migrateFontPreferences(client.theme, store, readStorage())\n ctx.effect(() => {\n if (typeof document === 'undefined') return () => {}\n const style = document.createElement('style')\n style.setAttribute('data-plugin', PLUGIN_NAME)\n style.textContent = styles\n document.head.appendChild(style)\n return () => style.remove()\n }, 'font.styles')\n ctx.effect(() => {\n if (typeof document === 'undefined') return () => {}\n const style = document.createElement('style')\n style.setAttribute('data-plugin', PLUGIN_NAME)\n style.setAttribute('data-font-role', 'conversation')\n document.head.appendChild(style)\n const write = () => {\n const sheet = style.sheet\n if (!sheet) return\n while (sheet.cssRules.length > 0) sheet.deleteRule(0)\n const declarations = conversationFontDeclarations(\n conversation.get(),\n fontTokenDeclarations(document.styleSheets ?? []),\n )\n if (declarations.length === 0) return\n try {\n sheet.insertRule(`${CONVERSATION_FONT_SELECTOR}{}`)\n const rule = sheet.cssRules[0] as CSSStyleRule\n for (const [name, value] of declarations) rule.style.setProperty(name, value)\n } catch (error) {\n logger.warn('conversation-font.rule-failed', 'Failed to apply conversation font CSS rule.', error)\n }\n }\n write()\n const unsubscribe = conversation.subscribe(write)\n return () => { unsubscribe(); style.remove() }\n }, 'font.conversation')\n // Fonts get their own settings section, not a General item row. The\n // shadowing entry waits on the General item list separately and lives inside\n // the section callback's lifetime: a same-id entry at lower priority renders\n // nothing in the native font-size cell's place, so the cell is hidden exactly\n // while both the Font page and the General column exist — section collapse\n // or plugin unload cancels the wait and the native cell renders again (and\n // a late or re-declared General section re-installs it). The native entry is\n // never touched; shadowing is the slot ledger's own override semantics.\n ctx.effect(() => client.slots.inject('settings.section', () => [\n client.slots.register(\n {\n name: 'settings.section',\n id: 'font',\n order: 5,\n label: () => (client.locale.getSnapshot().active.toLowerCase().startsWith('zh') ? COPY.zh.label : COPY.en.label),\n },\n () => <FontSettingsGroup client={client} conversation={conversation} />,\n ),\n client.slots.inject('settings.general.item', () => client.slots.register(\n { name: 'settings.general.item', id: 'font-size', order: 11, priority: -10 },\n () => null,\n )),\n // Nav icon seat is separate from the section list; nesting its wait inside\n // the section's keeps the letter-A bound to this page's exact lifetime.\n registerSettingsSectionIcon(ctx, 'font', 5, IconFontSettings),\n ]), 'font.settings')\n}\n"],"mappings":";;;;;;;;AAIA,MAAa,cAAc;;;AAI3B,MAAa,cAAc;AAS3B,MAAa,kBAAkB;CAC7B,MAAM;EAAE,KAAK;EAAI,KAAK;EAAI,SAAS;CAAG;CACtC,MAAM;EAAE,KAAK;EAAI,KAAK;EAAI,SAAS;CAAG;CACtC,UA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