dsh-client-auto-continue 0.17.4 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +230 -281
  3. package/README.ru.md +382 -0
  4. package/README.zh.md +229 -279
  5. package/docs/auto-continue-workflow.archify.json +3 -3
  6. package/docs/auto-continue-workflow.en.archify.json +3 -3
  7. package/docs/auto-continue-workflow.en.html +1 -1
  8. package/docs/auto-continue-workflow.html +1 -1
  9. package/docs/auto-continue-workflow.ru.svg +530 -0
  10. package/docs/banner-ru-dark.svg +38 -0
  11. package/docs/banner-ru.svg +38 -0
  12. package/docs/demo-ru-static.svg +115 -0
  13. package/docs/demo-ru.svg +147 -0
  14. package/docs/releases/v0.18.0.md +58 -0
  15. package/docs/releases/v0.19.0.md +62 -0
  16. package/docs/social-preview.png +0 -0
  17. package/docs/social-preview.svg +30 -1
  18. package/lib/client.js +347 -100
  19. package/lib/client.js.map +3 -3
  20. package/lib/index.js +790 -49
  21. package/lib/types/client/auto-continue-icon.d.ts +7 -0
  22. package/lib/types/client/bridge.d.ts +2 -0
  23. package/lib/types/client/composer-toggle.d.ts +2 -0
  24. package/lib/types/client/locales.d.ts +19 -0
  25. package/lib/types/client/settings-card.d.ts +8 -0
  26. package/lib/types/host/connectivity.d.ts +4 -0
  27. package/lib/types/host/engine.d.ts +97 -5
  28. package/lib/types/index.d.ts +64 -0
  29. package/lib/types/shared/core.d.ts +54 -1
  30. package/locale/ru.json +6 -0
  31. package/package.json +6 -4
  32. package/scripts/build-docs-assets.mjs +126 -0
  33. package/src/client/auto-continue-icon.tsx +6 -27
  34. package/src/client/bridge.ts +26 -6
  35. package/src/client/composer-toggle.tsx +22 -11
  36. package/src/client/index.ts +5 -1
  37. package/src/client/locales.ts +241 -38
  38. package/src/client/settings-card.tsx +31 -4
  39. package/src/client/settings-notifications.ts +3 -2
  40. package/src/client/styles.ts +17 -19
  41. package/src/host/connectivity.ts +54 -0
  42. package/src/host/engine.ts +852 -40
  43. package/src/host/settings-migration.ts +1 -1
  44. package/src/index.ts +26 -1
  45. package/src/shared/core.ts +94 -3
package/lib/client.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["src/client/index.ts", "src/shared/core.ts", "src/client/locales.ts", "src/client/settings-card.tsx", "src/client/native-switch.tsx", "src/client/dsh-store-compat.ts", "src/client/bridge.ts", "src/client/settings-form.ts", "src/client/styles.ts", "src/client/settings-notifications.ts", "src/client/composer-toggle.tsx", "src/client/mode-menu.tsx", "src/client/auto-continue-icon.tsx", "src/client/native-toast.tsx"],
4
- "sourcesContent": ["/**\n * Auto-continue plugin, browser half (thin shell).\n *\n * Since 0.8.0 the auto-continue ENGINE runs inside the host process (single\n * instance — see src/host/engine.ts), so this half only:\n * - registers the `auto-continue` settings card in the available plugin UI,\n * - adds a per-session composer switch and mode menu backed by host settings,\n * - subscribes to the host status bridge (SSE) and shows browser\n * notifications with action buttons (Resume now / Pause 1h) via the bridge\n * action endpoint,\n * - feeds the card's stats / paused-sessions panels from the bridge state.\n */\nimport type { Context as ClientContext } from '@deepseek-ai/cordis';\n// Type-only: the slot service is declared by the renderer in newer DSH SDKs.\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client';\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client';\n// Type-only: pulls the settings-surface SlotMap merge and ctx.settingsScope.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client';\n// Type-only: pulls the `settings.plugin.item` SlotMap merge.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings-plugins/client';\nimport { resolveLocale, type AutoContinueSettings } from '../shared/core.ts';\nimport { en, zh, type SettingsCardKey } from './locales.ts';\nimport {\n AutoContinueSettingsCard,\n AutoContinueSettingsCardController,\n AutoContinueSettingsPage,\n} from './settings-card.tsx';\nimport { startBridge } from './bridge.ts';\nimport { AutoContinueComposerToggle } from './composer-toggle.tsx';\nimport type { SettingsScope } from './dsh-store-compat.ts';\nimport { canWriteSettings } from './settings-form.ts';\n\n/** Dictionary namespace owned by this plugin. */\nconst NS = 'auto-continue';\n\n/** Settings namespace the settings card edits (the host engine reads it). */\nconst SETTINGS_NS = 'auto-continue';\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface SlotMap {\n /** Official compact composer tools; never occupy the resident single slot. */\n 'conversation.input.left': {\n kind: 'list';\n scope: 'session';\n };\n /** DSH 0.1.7's bundle configuration seat; only the owner props we consume. */\n 'plugins.bundle.config': {\n kind: 'keyed';\n scope: 'root';\n owner: { readonly view: 'summary' | 'page' };\n };\n }\n interface LocaleNamespaceMap {\n /** auto-continue settings-card copy. */\n 'auto-continue': SettingsCardKey;\n }\n}\n\n/** Shared subset of DSH 0.1.7's provider, without a new runtime dependency. */\ntype ConfigFormsContext = ClientContext & {\n configForms: { get<T>(entryId: string): SettingsScope<T> };\n};\n\n/** Settings services are injected separately: neither exists in every DSH cohort. */\nexport const inject = ['slots', 'locale'];\n\n// 浏览器侧辅助(设置卡片用): 桥状态读取与暂停解除。\nexport {\n pausedSessions,\n readTodayStats,\n readRecoveryAttempts,\n resetTodayStats,\n unpauseSession,\n} from './bridge.ts';\n\n/**\n * Plugin body: settings card + host status bridge (notifications, stats,\n * paused sessions).\n * @param ctx - client root context.\n */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'auto-continue: dictionaries');\n ctx.effect(() => startBridge(), 'auto-continue: host bridge');\n\n // Cordis waits for ALL top-level dependencies. Requiring settingsScope here\n // would leave DSH 0.1.7 pending forever; requiring configForms breaks older\n // hosts. Separate child fibers also follow late providers and their teardown.\n ctx.inject(['settingsScope'], (settingsCtx) => {\n mountSettings(settingsCtx, settingsCtx.settingsScope.bind<AutoContinueSettings>({ namespace: SETTINGS_NS }));\n });\n ctx.inject(['configForms'], (settingsCtx) => {\n const forms = (settingsCtx as ConfigFormsContext).configForms;\n mountSettings(settingsCtx, forms.get<AutoContinueSettings>(SETTINGS_NS));\n });\n}\n\n/** Attach this consumer's subscriptions and card to the provider's lifecycle. */\nfunction mountSettings(ctx: ClientContext, scope: SettingsScope<AutoContinueSettings>): void {\n /**\n * Mirror the browser locale into the host config, with a hard per-page budget.\n *\n * The write is only needed while the stored value disagrees with the page, so\n * every notification re-checks the snapshot — but two unbounded writers hid in\n * that check, and both of them hammer `settings.yaml` until the host settings\n * write queue backs up (observed: ~1 write / 400 ms when a completed write does\n * not fold back before the next document tick, and a two-page ping-pong when\n * two pages with different UI languages keep overwriting each other).\n *\n * So: keep the subscription and the `locale/change` hook (a scope that is not\n * `ready` yet still mirrors once it is, and a real language switch still wins),\n * but cap this page at {@link MAX_MIRROR_ATTEMPTS} writes per active locale.\n *\n * The budget must NOT be reset by a matching snapshot. In the real\n * `SettingsScopeController`, a successful `set()` folds the mutation response\n * into the WRITING page's own mirror (`mirror.acceptView` -> scope `derive()` ->\n * subscriber), so under the two-page ping-pong each page first sees its own\n * accepted value — matching its active locale — and would hand itself a fresh\n * budget before the other page writes back. That is an unbounded loop again\n * (probed: 400+ host writes). Reset only when the browser's active locale\n * genuinely changes; a matching snapshot then simply needs no write.\n */\n const MAX_MIRROR_ATTEMPTS = 3;\n let mirroredLocale: string | undefined;\n let mirrorAttempts = 0;\n const syncLocale = (): void => {\n const active = ctx.locale.getLocale().active;\n const target = resolveLocale(active);\n const snapshot = scope.getSnapshot();\n if (!canWriteSettings(snapshot)) return;\n // A genuine language switch is the only thing that earns a fresh budget: the\n // attempt count must survive matching snapshots, because the writing page's\n // own acknowledgement arrives as a match (see above). Tracking `mirroredLocale`\n // on every pass is what lets a later real switch be recognised.\n if (mirroredLocale !== active) {\n mirroredLocale = active;\n mirrorAttempts = 0;\n }\n // Converged: nothing to write.\n if (snapshot.value?.locale === target) return;\n if (mirrorAttempts >= MAX_MIRROR_ATTEMPTS) return;\n mirrorAttempts += 1;\n void scope.set('locale', target);\n };\n ctx.effect(() => scope.subscribe(syncLocale), 'auto-continue: locale settings sync');\n ctx.on('locale/change', syncLocale);\n syncLocale();\n\n const controller = new AutoContinueSettingsCardController(scope, () => ctx.locale.getLocale().active);\n ctx.effect(() => () => controller.dispose(), 'auto-continue: settings form');\n\n ctx.slots.inject('conversation.input.left', () =>\n ctx.slots.register(\n {\n name: 'conversation.input.left',\n id: 'auto-continue',\n locale: NS,\n inject: (sessionId) => controller.injectComposer(sessionId),\n },\n AutoContinueComposerToggle,\n ),\n );\n\n // Slot injection waits for the matching UI declaration. Keep the old\n // settings card and the new bundle page independent of service migration.\n ctx.slots.inject('settings.plugin.item', () =>\n ctx.slots.register(\n {\n name: 'settings.plugin.item',\n key: SETTINGS_NS,\n locale: NS,\n inject: () => controller.inject(),\n },\n AutoContinueSettingsCard,\n ),\n );\n ctx.slots.inject('plugins.bundle.config', () =>\n ctx.slots.register(\n {\n name: 'plugins.bundle.config',\n key: 'dsh-client-auto-continue',\n locale: NS,\n inject: () => controller.inject(),\n },\n AutoContinueSettingsPage,\n ),\n );\n}\n", "/** 共享核心: 平台无关的纯逻辑与类型。\n *\n * 被 host 引擎(src/host/engine.ts)与浏览器半侧共用: 配置解析、错误分类、\n * 模板填充、自适应退避、幂等护栏的工具结果提取、循环守卫的会话状态机,\n * 以及回显识别。引擎迁入 host 后(0.8.0), 浏览器半侧只 re-export 本模块。\n */\nimport type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';\n\n/** Supported UI/config locales; missing and unsupported values use English. */\nexport type AutoContinueLocale = 'en' | 'zh';\n\nexport function resolveLocale(locale: unknown): AutoContinueLocale {\n return typeof locale === 'string' && /^zh(?:-|$)/i.test(locale) ? 'zh' : 'en';\n}\n\nexport type SessionMode = 'default' | 'off' | 'recover' | 'loop';\n\nexport interface SessionPolicy {\n modes: Record<string, SessionMode>;\n defaultMode: 'recover' | 'loop';\n paused: boolean;\n writable: boolean;\n}\n\nexport const isSessionMode = (value: unknown): value is SessionMode =>\n value === 'default' || value === 'off' || value === 'recover' || value === 'loop';\n\nexport function sessionMode(modes: Record<string, SessionMode>, sessionId: string): SessionMode {\n return Object.prototype.hasOwnProperty.call(modes, sessionId) && isSessionMode(modes[sessionId]) ? modes[sessionId]! : 'default';\n}\n\n/** Locale-owned defaults for the user-editable text fields. */\nexport const LOCALIZED_TEXT_DEFAULTS = {\n zh: {\n continueText: '继续',\n continueTextMaxTokens: '继续',\n continueTextSilent:\n '继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。',\n continueTextLoop: '继续',\n continueTextInterrupted:\n '继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。',\n guardPendingText: '(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)',\n guardDoneText: '(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)',\n loopText: '(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)',\n },\n en: {\n continueText: 'Continue',\n continueTextMaxTokens: 'Continue',\n continueTextSilent:\n 'Continue. Your previous turn ended with internal reasoning only, with no message and no tool call, so nothing reached the user. Always finish a turn with a tool call or a visible answer.',\n continueTextLoop: 'Continue',\n continueTextInterrupted:\n 'Continue. The harness was restarted while your previous turn was still running; tool calls pending at the restart are recorded with unknown outcomes. Resume where you left off, verifying external state before retrying anything that may have side effects.',\n guardPendingText:\n '(The previous tool \"{tool}\" may not have completed. Check its state before continuing and do not run it again.)',\n guardDoneText:\n '(The previous tool \"{tool}\" completed successfully. Result: {result}; do not run it again. Continue from there.)',\n loopText:\n '(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)',\n },\n} as const satisfies Record<AutoContinueLocale, Record<string, string>>;\n\n/** The `auto-continue` settings section (all fields optional on the wire; the host schema carries defaults). */\nexport interface AutoContinueSettings {\n /** Active browser/UI locale mirrored by the client. */\n locale?: AutoContinueLocale;\n /** Text automatically sent after an interruption. */\n continueText?: string;\n /** Text sent when the output token ceiling is reached (same placeholders as `continueText`). */\n continueTextMaxTokens?: string;\n /** Resume observed model activity that completes without visible output. */\n resumeSilentTurns?: boolean;\n /** Autonomous mode: hand the thread back to the agent after every completed turn, looping until the user stops it. The consecutive-failure cap only throttles failures, never successful completions. */\n resumeCompletedTurns?: boolean;\n /** Text sent to resume a silent turn (same placeholders as `continueText`). */\n continueTextSilent?: string;\n /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */\n continueTextLoop?: string;\n /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */\n continueTextInterrupted?: string;\n /** Idempotency guard: inspect the last tool call before resuming and steer the model. */\n guardTools?: boolean;\n /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */\n guardPendingText?: string;\n /** Guard text appended when the last tool call completed successfully (don't rerun it). */\n guardDoneText?: string;\n /** Grace period after an interruption before auto-sending (ms). */\n graceMs?: number;\n /** Minimum interval between two auto-continues per session (ms). */\n cooldownMs?: number;\n /** Max consecutive auto-continues per session before stopping. */\n maxConsecutive?: number;\n /** Recover delayed interrupted sessions during the host startup window. */\n scanOnBoot?: boolean;\n /** Max eligible recoveries per scan pass (most recently active first). */\n scanLimit?: number;\n /** Interruption freshness and duration of startup polling (ms). */\n freshMs?: number;\n /** Log `[auto-continue]` lines to the browser console. */\n verbose?: boolean;\n /** Classify failures: auto-continue transient errors only; permanent ones (auth/balance/model) are skipped and notified. */\n classify?: boolean;\n /** Provider-specific message/code/status fragments that explicitly count as retryable, one literal per line. */\n retryableErrorPatterns?: string;\n /** Cooldown multiplier per consecutive failure (adaptive backoff). */\n backoffFactor?: number;\n /** Cap on the effective backoff interval (ms). */\n backoffMaxMs?: number;\n /** Show browser notifications for auto-continue events. */\n notify?: boolean;\n /** Globally pause auto-continue: no live or scan send, queued pending sends cancelled. */\n paused?: boolean;\n /** Persistent per-session overrides; default explicitly inherits the profile default. */\n sessionModes?: Record<string, SessionMode>;\n /** Show the session mode selector in the conversation composer. */\n showComposerToggle?: boolean;\n /** Loop guard: detect a running turn spinning in place (short talk without tools, or the same tool repeating) and restart it. */\n loopGuard?: boolean;\n /** A model message shorter than this many chars counts as a \"short sentence\" (loop signal). */\n loopShortChars?: number;\n /** Consecutive short sentences within this window (ms) with no tool call in between trip the loop guard. */\n loopWindowMs?: number;\n /** Consecutive short sentences trip the loop guard. */\n loopShortCount?: number;\n /** Consecutive identical tool calls with identical arguments AND identical results trip the loop guard. */\n loopToolRepeat?: number;\n /** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */\n loopRepeatText?: number;\n /** Text sent after the loop guard cancels and restarts a turn (supports {tool}). */\n loopText?: string;\n}\n\n/** Fully resolved configuration (built-in defaults + user overrides). */\nexport type AutoContinueConfig = Required<AutoContinueSettings>;\n\n/** Effective built-in defaults; localized text fields use English until a browser locale is mirrored. */\nexport const DEFAULT_CONFIG: AutoContinueConfig = {\n locale: 'en',\n ...LOCALIZED_TEXT_DEFAULTS.en,\n resumeSilentTurns: true,\n resumeCompletedTurns: false,\n continueTextLoop: '',\n guardTools: true,\n graceMs: 3000,\n cooldownMs: 20000,\n maxConsecutive: 3,\n scanOnBoot: true,\n scanLimit: 8,\n freshMs: 15 * 60 * 1000,\n verbose: true,\n classify: true,\n retryableErrorPatterns: '',\n backoffFactor: 2,\n backoffMaxMs: 300000,\n notify: false,\n paused: false,\n sessionModes: {},\n showComposerToggle: true,\n loopGuard: true,\n loopShortChars: 40,\n loopWindowMs: 30000,\n loopShortCount: 12,\n loopRepeatText: 4,\n loopToolRepeat: 5,\n};\n\nfunction numberOr(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;\n}\n\nfunction booleanOr(value: unknown, fallback: boolean): boolean {\n return typeof value === 'boolean' ? value : fallback;\n}\n\n/** Resolve a (possibly partial / not-yet-loaded) settings section to a full config. */\nexport function resolveConfig(section: AutoContinueSettings | undefined): AutoContinueConfig {\n const value = section ?? {};\n const locale = resolveLocale(value.locale);\n const localized = LOCALIZED_TEXT_DEFAULTS[locale];\n const text =\n typeof value.continueText === 'string' && value.continueText.trim() !== ''\n ? value.continueText\n : localized.continueText;\n const maxTokensText =\n typeof value.continueTextMaxTokens === 'string' && value.continueTextMaxTokens.trim() !== ''\n ? value.continueTextMaxTokens\n : localized.continueTextMaxTokens;\n const silentText =\n typeof value.continueTextSilent === 'string' && value.continueTextSilent.trim() !== ''\n ? value.continueTextSilent\n : localized.continueTextSilent;\n const loopText =\n typeof value.continueTextLoop === 'string' && value.continueTextLoop.trim() !== ''\n ? value.continueTextLoop\n : localized.continueTextLoop;\n const interruptedText =\n typeof value.continueTextInterrupted === 'string' && value.continueTextInterrupted.trim() !== ''\n ? value.continueTextInterrupted\n : localized.continueTextInterrupted;\n const guardPendingText =\n typeof value.guardPendingText === 'string' && value.guardPendingText.trim() !== ''\n ? value.guardPendingText\n : localized.guardPendingText;\n const guardDoneText =\n typeof value.guardDoneText === 'string' && value.guardDoneText.trim() !== ''\n ? value.guardDoneText\n : localized.guardDoneText;\n return {\n locale,\n continueText: text,\n continueTextMaxTokens: maxTokensText,\n resumeSilentTurns: booleanOr(value.resumeSilentTurns, DEFAULT_CONFIG.resumeSilentTurns),\n resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),\n continueTextSilent: silentText,\n continueTextLoop: loopText,\n continueTextInterrupted: interruptedText,\n guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),\n guardPendingText,\n guardDoneText,\n graceMs: numberOr(value.graceMs, DEFAULT_CONFIG.graceMs),\n cooldownMs: numberOr(value.cooldownMs, DEFAULT_CONFIG.cooldownMs),\n maxConsecutive: Math.max(1, numberOr(value.maxConsecutive, DEFAULT_CONFIG.maxConsecutive)),\n scanOnBoot: booleanOr(value.scanOnBoot, DEFAULT_CONFIG.scanOnBoot),\n scanLimit: Math.max(1, numberOr(value.scanLimit, DEFAULT_CONFIG.scanLimit)),\n freshMs: numberOr(value.freshMs, DEFAULT_CONFIG.freshMs),\n verbose: booleanOr(value.verbose, DEFAULT_CONFIG.verbose),\n classify: booleanOr(value.classify, DEFAULT_CONFIG.classify),\n retryableErrorPatterns:\n typeof value.retryableErrorPatterns === 'string'\n ? value.retryableErrorPatterns.trim()\n : DEFAULT_CONFIG.retryableErrorPatterns,\n backoffFactor: Math.max(1, numberOr(value.backoffFactor, DEFAULT_CONFIG.backoffFactor)),\n backoffMaxMs: numberOr(value.backoffMaxMs, DEFAULT_CONFIG.backoffMaxMs),\n notify: booleanOr(value.notify, DEFAULT_CONFIG.notify),\n paused: booleanOr(value.paused, DEFAULT_CONFIG.paused),\n sessionModes: value.sessionModes !== null && typeof value.sessionModes === 'object' && !Array.isArray(value.sessionModes)\n ? value.sessionModes : {},\n showComposerToggle: booleanOr(value.showComposerToggle, DEFAULT_CONFIG.showComposerToggle),\n loopGuard: booleanOr(value.loopGuard, DEFAULT_CONFIG.loopGuard),\n loopShortChars: Math.max(1, numberOr(value.loopShortChars, DEFAULT_CONFIG.loopShortChars)),\n loopWindowMs: Math.max(1000, numberOr(value.loopWindowMs, DEFAULT_CONFIG.loopWindowMs)),\n loopShortCount: Math.max(2, numberOr(value.loopShortCount, DEFAULT_CONFIG.loopShortCount)),\n loopRepeatText: Math.max(2, numberOr(value.loopRepeatText, DEFAULT_CONFIG.loopRepeatText)),\n loopToolRepeat: Math.max(2, numberOr(value.loopToolRepeat, DEFAULT_CONFIG.loopToolRepeat)),\n loopText:\n typeof value.loopText === 'string' && value.loopText.trim() !== ''\n ? value.loopText\n : localized.loopText,\n };\n}\n\n/**\n * 视为「非人为中断」的回合结束原因, 用于启动/重连扫描。\n * - `interrupted` 只由崩溃修复在宿主重载时写入(loop 永不实时发出), 因此仅在扫描路径处理;\n * - 实时事件路径只对 `error` / `max-tokens` 自动续跑; 另外续跑没有可见输出的 `completed` / `no-visible-output` 回合(不属于本类型);\n * - `aborted`(用户停止)与 `blocked`(策略拒绝)永不自动继续。\n */\ntype NonHumanReason = 'error' | 'interrupted' | 'max-tokens';\n\nexport function isNonHumanReason(kind: string): kind is NonHumanReason {\n return kind === 'error' || kind === 'interrupted' || kind === 'max-tokens';\n}\n\n/** 一次回合失败的机器可读事实(turn/end error 的 LlmFailure 载荷)。 */\nexport interface FailureFacts {\n /** 稳定机器路由码(如 UPSTREAM、RATE_LIMIT_EXCEEDED、INVALID_API_KEY)。 */\n code: string;\n /** 人类可读的失败描述。 */\n message: string;\n /** 供应商 HTTP 状态码(可用时)。 */\n status?: number;\n}\n\n/**\n * 错误分类: 该失败是否值得自动继续。\n * 用户填写的 provider 专属文本片段优先覆盖内置结果; 未命中时,\n * 永久性失败(认证/余额/模型不存在/上下文超限等)重试也不会成功, 应跳过并通知用户;\n * 其余(网络、超时、5xx、429 等)视为临时性失败, 允许自动恢复。\n */\nexport function isTransientFailure(failure: FailureFacts, retryableErrorPatterns = ''): boolean {\n const haystack = `${failure.code} ${failure.status ?? ''} ${failure.message}`.toLowerCase();\n const explicitlyRetryable = retryableErrorPatterns\n .split(/\\r?\\n/)\n .map((pattern) => pattern.trim().toLowerCase())\n .filter((pattern) => pattern !== '')\n .some((pattern) => haystack.includes(pattern));\n if (explicitlyRetryable) return true;\n const status = failure.status;\n if (status !== undefined && (status === 401 || status === 403)) return false;\n // Malformed model output can echo tool arguments that look like auth/quota errors.\n if (failure.code === 'MALFORMED_RESPONSE') return true;\n const permanent =\n /auth|unauthor|forbidden|credential|api[_-]?key|permission/i.test(haystack) ||\n /insufficient.*(balance|quota)|billing|payment|quota.*exceeded.*(?!retry)/i.test(haystack) ||\n /model.*not[_-]?found|unknown[_-]?model|model[_-]?not[_-]?found|not.*support.*model/i.test(haystack) ||\n /context.*(length|limit|overflow|exceed)|token.*limit|max.*context/i.test(haystack) ||\n /invalid[_-]?request|bad[_-]?request/i.test(haystack) ||\n /prompt variable \"\\{\\{[^\"\\r\\n]+\\}\\}\" has no value for this assembly/i.test(haystack);\n return !permanent;\n}\n\n/**\n * host/agent-error 消息分类: 仅明确属于网络/传输类的临时错误才自动继续。\n * 其余(序列化失败、配置/宿主内部错误等)视为永久性——重试无益, 且用户停止导致的\n * 序列化失败(如 Windows 下 abort 的 DOMException reason)绝不能自动续跑。\n */\nexport function isTransientAgentError(message: string): boolean {\n return /network|timeout|timed ?out|econn|etimedout|socket|5\\d\\d|\\b429\\b|upstream|temporar/i.test(message);\n}\n\n/** 通知上的一个操作按钮(action 标识 + 显示文案)。 */\nexport interface NotifyAction {\n /** 稳定动作标识, 点击时经 onAction 回调传出。 */\n action: string;\n /** 按钮显示文案。 */\n title: string;\n}\n\n/** 通知的可选行为: 操作按钮列表与点击回调。 */\nexport interface NotifyOptions {\n actions?: NotifyAction[];\n onAction?: (action: string) => void;\n}\n\n/** 浏览器通知(不可用时静默跳过); 点击通知聚焦窗口, 操作按钮走 onAction。 */\n/** 把毫秒格式化为人类可读的经过时长(如 65s → 1m5s)。 */\nfunction formatElapsed(ms: number | undefined): string {\n if (ms === undefined || !Number.isFinite(ms) || ms < 0) return '';\n if (ms < 1000) return `${Math.round(ms)}ms`;\n const s = Math.round(ms / 1000);\n if (s < 60) return `${s}s`;\n return `${Math.floor(s / 60)}m${s % 60 > 0 ? `${s % 60}s` : ''}`;\n}\n\n/** 模板填充所需的上下文(全部可选, 缺失的占位符填为空串)。 */\nexport interface TemplateContext {\n /** 失败事实(错误码/消息/HTTP 状态), 对应 {code}/{message}/{status}。 */\n facts?: FailureFacts;\n /** 失败前最后一次工具调用的名称, 对应 {tool}。 */\n tool?: string;\n /** 失败回合的编号, 对应 {turn}。 */\n turn?: number;\n /** 连续失败次数(含本次), 对应 {errorCount}。 */\n errorCount?: number;\n /** 会话标题(来自 session.list 投影, 可用时), 对应 {sessionTitle}。 */\n sessionTitle?: string;\n /** 自失败发生以来的毫秒数, 对应 {elapsed}。 */\n elapsedMs?: number;\n /** 上一步工具结果摘要(截断), 对应 {result}(护栏模板用)。 */\n result?: string;\n}\n\n/** 用失败事实与回合信息填充 continueText 模板占位符({code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed}/{result})。 */\nexport function fillTemplate(template: string, ctx: TemplateContext): string {\n return template\n .replace(/\\{code\\}/g, ctx.facts?.code ?? '')\n .replace(/\\{message\\}/g, ctx.facts?.message ?? '')\n .replace(/\\{status\\}/g, ctx.facts?.status !== undefined ? String(ctx.facts.status) : '')\n .replace(/\\{tool\\}/g, ctx.tool ?? '')\n .replace(/\\{turn\\}/g, ctx.turn !== undefined ? String(ctx.turn) : '')\n .replace(/\\{errorCount\\}/g, ctx.errorCount !== undefined ? String(ctx.errorCount) : '')\n .replace(/\\{sessionTitle\\}/g, ctx.sessionTitle ?? '')\n .replace(/\\{elapsed\\}/g, formatElapsed(ctx.elapsedMs))\n .replace(/\\{result\\}/g, ctx.result ?? '');\n}\n\n// ---------- 幂等护栏: 上一步工具调用的执行状态 ----------\n\n/** 工具结果摘要的最大长度(护栏模板 {result} 用)。 */\nconst TOOL_RESULT_CAP = 160;\n\n/**\n * 给 JSON 值生成定长且键顺序无关的稳定指纹。\n *\n * 这里不保存可能很大的工具输出原文;每个字符都会进入两个独立的\n * 32-bit 累加器,再附上字符数,供 loop guard 比较完整的模型可见结果。\n */\nfunction stableFingerprint(value: unknown): string {\n let first = 0x811c9dc5;\n let second = 0x9e3779b9;\n let length = 0;\n const feed = (text: string): void => {\n length += text.length;\n for (let i = 0; i < text.length; i += 1) {\n const code = text.charCodeAt(i);\n first = Math.imul(first ^ code, 0x01000193) >>> 0;\n second = Math.imul(second ^ code, 0x85ebca6b) >>> 0;\n second = (second ^ (second >>> 13)) >>> 0;\n }\n };\n const walk = (part: unknown): void => {\n if (part === null) {\n feed('null');\n } else if (Array.isArray(part)) {\n feed('[');\n for (const item of part) {\n walk(item);\n feed(',');\n }\n feed(']');\n } else if (typeof part === 'object') {\n feed('{');\n const record = part as Record<string, unknown>;\n for (const key of Object.keys(record).sort()) {\n feed(JSON.stringify(key));\n feed(':');\n walk(record[key]);\n feed(',');\n }\n feed('}');\n } else {\n feed(`${typeof part}:${JSON.stringify(part) ?? String(part)}`);\n }\n };\n walk(value);\n return `${first.toString(16).padStart(8, '0')}${second.toString(16).padStart(8, '0')}:${length}`;\n}\n\n/** 从任意内容块里递归收集文本(结果为模型可见的工具输出)。 */\nfunction extractText(blocks: unknown, cap: number): string {\n let out = '';\n const walk = (value: unknown): void => {\n if (out.length >= cap) return;\n if (Array.isArray(value)) {\n for (const item of value) walk(item);\n return;\n }\n if (typeof value !== 'object' || value === null) return;\n const record = value as Record<string, unknown>;\n if (record['type'] === 'text' && typeof record['text'] === 'string') {\n out += record['text'];\n return;\n }\n for (const child of Object.values(record)) walk(child);\n };\n walk(blocks);\n return out.slice(0, cap);\n}\n\n/** 上一步工具调用的判定结果: 是否已确认完成, 以及文本摘要。 */\nexport interface ToolResultFacts {\n /** 工具是否成功完成(内部失败或 isError 视为未成功)。 */\n ok: boolean;\n /** 工具输出的文本摘要(截断)。 */\n excerpt: string;\n /** 完整模型可见内容 + 错误状态的定长稳定指纹(loop guard 比较用)。 */\n identity: string;\n}\n\ninterface ToolResultData {\n turn?: unknown;\n step?: unknown;\n error?: { name?: string; code?: string };\n message?: {\n source?: { kind?: string; callId?: unknown };\n content?: Array<{ type?: string; toolCallId?: unknown; content?: unknown; isError?: boolean }>;\n };\n}\n\nfunction toolCorrelationKey(\n data: { turn?: unknown; step?: unknown },\n callId: string | undefined,\n): string | undefined {\n if (callId === undefined || typeof data.turn !== 'number' || typeof data.step !== 'number') {\n return undefined;\n }\n return JSON.stringify([data.turn, data.step, callId]);\n}\n\nfunction resultBlock(data: ToolResultData) {\n return data.message?.content?.find((part) => part.type === 'tool-result');\n}\n\n/**\n * 取工具结果的关联 id。新版 DSH 的权威位置是 message.source.callId,\n * 同时接受模型可见 block 上的 toolCallId;两者冲突时宁可忽略,不猜测配对。\n */\nexport function toolResultCallId(data: ToolResultData): string | undefined {\n if (resultBlock(data) === undefined) return undefined;\n const sourceId = data.message?.source?.kind === 'tool' ? data.message.source.callId : undefined;\n const blockId = resultBlock(data)?.toolCallId;\n const source = typeof sourceId === 'string' && sourceId !== '' ? sourceId : undefined;\n const block = typeof blockId === 'string' && blockId !== '' ? blockId : undefined;\n if (source !== undefined && block !== undefined && source !== block) return undefined;\n return source ?? block;\n}\n\n/** 从 tool/result 事件载荷提取成功与否与文本摘要。 */\nexport function toolResultFacts(data: ToolResultData): ToolResultFacts {\n const result = resultBlock(data);\n const failed = data.error !== undefined || result?.isError === true;\n return {\n ok: !failed,\n excerpt: extractText(result?.content, TOOL_RESULT_CAP),\n identity: stableFingerprint({ content: result?.content ?? [], isError: failed }),\n };\n}\n\n/** loop guard 在后续 step 边界确认的连续重复信号。 */\nexport interface ToolRepeatSignal {\n tool: string;\n count: number;\n}\n\nexport type ToolGuardState =\n | { kind: 'none' }\n | { kind: 'pending'; tool: string }\n | { kind: 'done'; tool: string; result: string }\n | { kind: 'failed'; tool: string };\n\ninterface TrackedToolCall {\n id: string | undefined;\n name: string;\n key: string;\n result: ToolResultFacts | undefined;\n resultSeq: number | undefined;\n}\n\nconst MAX_PENDING_TOOL_CALLS = 64;\nconst MAX_SEEN_TOOL_CALL_IDS = 256;\n\n/**\n * 每个会话的工具调用关联器。\n *\n * 集中封装事件关联、step 边界确认、护栏读取与重置。内部按 callId 配对,\n * 乱序结果先缓存、再按调用顺序推进 loop 计数。队列和去重 id 都有硬上限;\n * 超限或载荷无法关联时会打断重复计数,宁可漏报也不误杀健康回合。\n */\nexport class ToolInvocationTracker {\n private readonly pendingById = new Map<string, TrackedToolCall>();\n private readonly pendingInOrder: TrackedToolCall[] = [];\n private readonly seenCalls = new Map<string, TrackedToolCall>();\n private readonly seenInOrder: string[] = [];\n private latest: TrackedToolCall | undefined;\n private run: { key: string; tool: string; identity: string; count: number } | undefined;\n private repeatSignal: ToolRepeatSignal | undefined;\n private lastEventSeq = -1;\n\n reset(): void {\n this.pendingById.clear();\n this.pendingInOrder.length = 0;\n this.seenCalls.clear();\n this.seenInOrder.length = 0;\n this.latest = undefined;\n this.run = undefined;\n this.repeatSignal = undefined;\n this.lastEventSeq = -1;\n }\n\n /** 新回合边界:清空工具态,同时把重放水位推进到 turn/start。 */\n startTurn(seq: number): void {\n if (!Number.isSafeInteger(seq) || seq < 0 || seq <= this.lastEventSeq) return;\n this.reset();\n this.lastEventSeq = seq;\n }\n\n /** 回合已结束:保留最后一次调用的护栏,丢弃不再可用的 loop 关联态。 */\n resetRepeat(): void {\n this.pendingById.clear();\n this.pendingInOrder.length = 0;\n this.seenCalls.clear();\n this.seenInOrder.length = 0;\n this.run = undefined;\n this.repeatSignal = undefined;\n }\n\n recordCall(event: SessionEvent<'tool/call'>): boolean {\n if (!this.acceptEventSeq(event.seq)) return false;\n this.repeatSignal = undefined;\n const data = event.data;\n if (typeof data.name !== 'string') {\n this.breakCorrelation();\n return true;\n }\n const key = `${data.name}\\n${typeof data.arguments === 'string' ? data.arguments : ''}`;\n const callId = typeof data.callId === 'string' && data.callId !== '' ? data.callId : undefined;\n const id = toolCorrelationKey(data, callId);\n if (id === undefined) {\n this.breakCorrelation({\n id: undefined,\n name: data.name,\n key,\n result: undefined,\n resultSeq: undefined,\n });\n return true;\n }\n\n const seen = this.seenCalls.get(id);\n if (seen !== undefined) {\n // 同 seq 重放已被水位拒绝;更高 seq 复用复合 identity 时不猜测。\n this.breakCorrelation({\n id: undefined,\n name: data.name,\n key,\n result: undefined,\n resultSeq: undefined,\n });\n return true;\n }\n\n const call: TrackedToolCall = {\n id,\n name: data.name,\n key,\n result: undefined,\n resultSeq: undefined,\n };\n this.latest = call;\n this.pendingById.set(id, call);\n this.pendingInOrder.push(call);\n this.seenCalls.set(id, call);\n this.seenInOrder.push(id);\n this.trim(call);\n return true;\n }\n\n recordResult(event: SessionEvent<'tool/result'>): ToolRepeatSignal | undefined {\n if (!this.acceptEventSeq(event.seq)) return undefined;\n const data = event.data;\n const id = toolCorrelationKey(data, toolResultCallId(data));\n if (id === undefined) {\n this.breakCorrelation(this.latest);\n return undefined;\n }\n const surfaceOp = event.surfaceOp;\n if (typeof surfaceOp === 'object' && surfaceOp !== null) {\n const call = this.seenCalls.get(id);\n if (\n surfaceOp.start !== surfaceOp.end ||\n call === undefined ||\n call.result === undefined ||\n call.resultSeq !== surfaceOp.start\n ) {\n this.breakCorrelation(this.latest);\n return undefined;\n }\n call.result = toolResultFacts(data);\n call.resultSeq = event.seq;\n // replacement 可由 lossy pruner 产生:更新护栏,但绝不据此创建/增强重复。\n this.breakCorrelation(this.latest);\n return undefined;\n }\n const call = this.pendingById.get(id);\n if (call === undefined) {\n const seen = this.seenCalls.get(id);\n const duplicate = seen?.result;\n const incoming = toolResultFacts(data);\n if (\n seen !== undefined &&\n duplicate !== undefined &&\n seen.resultSeq === event.seq &&\n duplicate.identity === incoming.identity\n ) {\n return undefined;\n }\n if (seen !== undefined && duplicate !== undefined) {\n // 已完成调用又出现非 replacement 冲突时,旧完成事实也不再可信。\n seen.result = undefined;\n seen.resultSeq = undefined;\n }\n this.breakCorrelation(this.latest);\n return undefined;\n }\n if (call.result !== undefined) {\n const incoming = toolResultFacts(data);\n if (call.resultSeq === event.seq && call.result.identity === incoming.identity) {\n return undefined;\n }\n // 没有 surface replacement 语义却出现第二个冲突结果:关联已不可信。\n call.result = undefined;\n call.resultSeq = undefined;\n this.breakCorrelation(this.latest);\n return undefined;\n }\n call.result = toolResultFacts(data);\n call.resultSeq = event.seq;\n return this.drainCompleted();\n }\n\n guard(): ToolGuardState {\n const latest = this.latest;\n if (latest === undefined) return { kind: 'none' };\n if (latest.result === undefined) return { kind: 'pending', tool: latest.name };\n if (latest.result.ok) {\n return { kind: 'done', tool: latest.name, result: latest.result.excerpt };\n }\n return { kind: 'failed', tool: latest.name };\n }\n\n lastTool(): string | undefined {\n return this.latest?.name;\n }\n\n /** 下一模型 step 是稳定边界;此前 replacement/新调用会先清除候选。 */\n confirmRepeatAtStep(seq: number): ToolRepeatSignal | undefined {\n if (!this.acceptEventSeq(seq)) return undefined;\n const signal = this.pendingInOrder.length === 0 ? this.repeatSignal : undefined;\n this.repeatSignal = undefined;\n return signal;\n }\n\n /** 非工具 surface range replacement(如 compaction summary)同样终止旧工具证据。 */\n recordSurfaceReplacement(seq: number): void {\n if (!this.acceptEventSeq(seq)) return;\n this.breakCorrelation(this.latest);\n }\n\n restore(events: readonly SessionEvent[], untilSeq: number): void {\n this.reset();\n for (const event of events) {\n if (event.seq >= untilSeq) continue;\n if (event.type === 'turn/start') this.startTurn(event.seq);\n else if (event.type === 'step/start') this.confirmRepeatAtStep(event.seq);\n else if (event.type === 'tool/call') this.recordCall(event);\n else if (event.type === 'tool/result') this.recordResult(event);\n else if (\n (event.type === 'user/message' || event.type === 'assistant/message') &&\n typeof event.surfaceOp === 'object' &&\n event.surfaceOp !== null\n ) {\n this.recordSurfaceReplacement(event.seq);\n }\n }\n }\n\n private acceptEventSeq(seq: number): boolean {\n if (!Number.isSafeInteger(seq) || seq < 0) {\n this.breakCorrelation(this.latest);\n return false;\n }\n // session/event 与持久日志都按 seq 单调投递;旧 seq 只能是重放帧。\n if (seq <= this.lastEventSeq) return false;\n this.lastEventSeq = seq;\n return true;\n }\n\n private breakCorrelation(latest?: TrackedToolCall, preserve?: TrackedToolCall): void {\n this.pendingById.clear();\n this.pendingInOrder.length = 0;\n this.invalidateRunHistory();\n this.latest = latest;\n if (\n preserve?.id !== undefined &&\n preserve.result === undefined &&\n this.seenCalls.get(preserve.id) === preserve\n ) {\n this.pendingById.set(preserve.id, preserve);\n this.pendingInOrder.push(preserve);\n }\n }\n\n private invalidateRunHistory(): void {\n this.run = undefined;\n this.repeatSignal = undefined;\n }\n\n private trim(current: TrackedToolCall): void {\n while (this.pendingInOrder.length > MAX_PENDING_TOOL_CALLS) {\n // 只淘汰一个 call 会让其后的乱序结果跨过未知缺口重新拼成 streak。\n this.breakCorrelation(current, current);\n }\n while (this.seenInOrder.length > MAX_SEEN_TOOL_CALL_IDS) {\n const id = this.seenInOrder.shift();\n if (id !== undefined) {\n this.seenCalls.delete(id);\n // 丢失去重证据后不保留旧缓存;单调 seq 会拒绝淘汰项的旧帧重放。\n this.breakCorrelation(current, current);\n }\n }\n }\n\n private drainCompleted(): ToolRepeatSignal | undefined {\n let advanced = false;\n while (this.pendingInOrder[0]?.result !== undefined) {\n const call = this.pendingInOrder.shift();\n if (call === undefined || call.result === undefined) break;\n advanced = true;\n if (call.id !== undefined) this.pendingById.delete(call.id);\n this.advanceRun(call);\n }\n // 已知并发批次尚未收齐时不提前发信号;末尾结果可能展示真实进展。\n if (!advanced) return undefined;\n return this.refreshRepeatSignal();\n }\n\n private advanceRun(call: TrackedToolCall): void {\n if (call.result === undefined) return;\n if (this.run?.key === call.key && this.run.identity === call.result.identity) {\n this.run.count += 1;\n } else {\n this.run = { key: call.key, tool: call.name, identity: call.result.identity, count: 1 };\n }\n }\n\n private refreshRepeatSignal(): ToolRepeatSignal | undefined {\n this.repeatSignal =\n this.pendingInOrder.length === 0 && this.run !== undefined\n ? { tool: this.run.tool, count: this.run.count }\n : undefined;\n return this.repeatSignal;\n }\n}\n\n/** 自适应退避: 同一会话连续失败时的有效冷却间隔。 */\nexport function effectiveCooldown(\n consecutive: number,\n base: number,\n factor: number,\n max: number,\n): number {\n // consecutive = 已连续自动继续的次数; 第 1 次后开始按 factor 递增\n const multiplier = Math.pow(factor, consecutive);\n return Math.min(Math.max(base, base * multiplier), Math.max(base, max));\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** 浏览器当前 IANA 时区; 不可用时省略(宿主允许省略)。 */\nfunction clientTimeZone(): string | undefined {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** A sent recovery prompt, not proof that the following turn succeeded. */\nexport interface RecoveryAttempt {\n sessionId: string;\n at: number;\n reason: 'error' | 'max-tokens' | 'silent' | 'interrupted' | 'loop-guard' | 'manual';\n consecutive: number;\n}\n\n/** 一天的自动继续统计(host 单实例内存态)。 */\nexport interface DayStats {\n /** 本地日期 YYYY-MM-DD。 */\n date: string;\n /** 自动发送次数。 */\n sent: number;\n /** 因永久性错误跳过的次数。 */\n skipped: number;\n /** 发送后回合成功完成(恢复成功)的次数。 */\n recovered: number;\n /** 发送后再次失败的次数。 */\n failed: number;\n /** 达到连续上限而停止的次数(按停止事件计)。 */\n gaveUp: number;\n /** loop guard 打断并重启回合的次数。 */\n looped: number;\n /** 按错误码计数的失败分布。 */\n byCode: Record<string, number>;\n}\n\nexport function todayKey(): string {\n const d = new Date();\n const mm = String(d.getMonth() + 1).padStart(2, '0');\n const dd = String(d.getDate()).padStart(2, '0');\n return `${d.getFullYear()}-${mm}-${dd}`;\n}\n\n/** 空统计桶。 */\nexport function emptyDayStats(): DayStats {\n return { date: todayKey(), sent: 0, skipped: 0, recovered: 0, failed: 0, gaveUp: 0, looped: 0, byCode: {} };\n}\n\n/** 每会话运行时状态。 */\nexport interface SessionState {\n /** 连续自动「继续」次数; 成功回合或用户手动介入后归零。 */\n consecutive: number;\n /** 上次自动「继续」尝试(成功或失败)时间戳; 防止失败场景下的快速重试循环。 */\n lastAttemptAt: number;\n /** 尚未回显到会话事件流的自动发送消息 ID。 */\n pendingEchoMessageIds: Map<string, number>;\n /** 宽限期定时器(进行中的待发送)。 */\n pendingTimer: ReturnType<typeof setTimeout> | undefined;\n pendingReason?: string;\n /** 宿主权威 running 位(来自 host/session-status 与回合事件)。 */\n running: boolean | undefined;\n /** 当前排队消息数(来自 session/queue 帧)。 */\n queued: number;\n /** 子代理会话(session header origin is `subagent`). */\n subagent: boolean;\n /** 最近一次回合失败的事实(用于分类与模板填充)。 */\n lastFailure: FailureFacts | undefined;\n /** 最近一次失败的发生时间(模板 {elapsed} 与恢复统计用)。 */\n lastFailureAt: number;\n /** callId 精确配对的工具调用、幂等护栏与 loop 重复态。 */\n tools: ToolInvocationTracker;\n /** 失败回合的编号(模板 {turn})。 */\n lastTurn: number | undefined;\n /** 我们最近一次自动发送的时间戳; 0 = 没有待确认的恢复。 */\n pendingRecoveryAt: number;\n /** unknown: no observed start; empty: no model activity; silent: activity without visible output. */\n turnOutput: 'unknown' | 'empty' | 'silent' | 'visible';\n outputTurn: number | undefined;\n outputStartSeq: number;\n /** message-ops maintenance window, which must not enter model recovery or loop accounting. */\n maintenanceTurn?: number;\n /** 当前连续短句数(loop guard 信号 1: 空转)。 */\n shortRun: number;\n /** 最后一条短句的时间(时间窗判定用)。 */\n lastShortAt: number;\n /** 最后一条模型消息的文本(相同文本重复判定用)。 */\n lastAssistantText: string;\n /** 连续相同文本消息数(最强空转信号, 不限长度)。 */\n sameTextRun: number;\n /** 流式消息尚未闭合的有界尾段(assistant/chunk 增量分段检测用)。 */\n streamTail: string;\n /** 流式消息最近一个长段的归一化文本。 */\n streamLastSegment: string;\n /** 流式消息内连续近似重复长段计数。 */\n streamRepeatRun: number;\n /** 本回合已触发过 loop guard(防重复打断)。 */\n loopFired: boolean;\n /** loop 重启的延迟定时器(冷却结束后再 schedule)。 */\n loopRetryTimer: ReturnType<typeof setTimeout> | undefined;\n /** 冷却期恢复的延迟定时器(等到冷却结束再 schedule, 而不是丢弃这次恢复)。 */\n cooldownRetryTimer: ReturnType<typeof setTimeout> | undefined;\n}\n\nexport const freshState = (): SessionState => ({\n consecutive: 0,\n lastAttemptAt: 0,\n pendingEchoMessageIds: new Map(),\n pendingTimer: undefined,\n running: undefined,\n queued: 0,\n subagent: false,\n lastFailure: undefined,\n lastFailureAt: 0,\n tools: new ToolInvocationTracker(),\n lastTurn: undefined,\n pendingRecoveryAt: 0,\n turnOutput: 'unknown',\n outputTurn: undefined,\n outputStartSeq: 0,\n shortRun: 0,\n lastShortAt: 0,\n lastAssistantText: '',\n sameTextRun: 0,\n streamTail: '',\n streamLastSegment: '',\n streamRepeatRun: 0,\n loopFired: false,\n loopRetryTimer: undefined,\n cooldownRetryTimer: undefined,\n});\n\n\nexport const RECOVERY_WINDOW_MS = 10 * 60 * 1000;\n\nexport const ECHO_WINDOW_MS = 10 * 60 * 1000;\nconst MAX_PENDING_ECHO_MESSAGE_IDS = 64;\n\nfunction prunePendingEchoMessageIds(state: SessionState, now: number): void {\n for (const [messageId, queuedAt] of state.pendingEchoMessageIds) {\n if (now - queuedAt > ECHO_WINDOW_MS) state.pendingEchoMessageIds.delete(messageId);\n }\n}\n\n/** Track an identified plugin message before handing it to the host queue. */\nexport function trackPendingEcho(state: SessionState, messageId: string): void {\n const now = Date.now();\n prunePendingEchoMessageIds(state, now);\n state.pendingEchoMessageIds.set(messageId, now);\n while (state.pendingEchoMessageIds.size > MAX_PENDING_ECHO_MESSAGE_IDS) {\n const oldest = state.pendingEchoMessageIds.keys().next();\n if (oldest.done) break;\n state.pendingEchoMessageIds.delete(oldest.value);\n }\n}\n\n/** Roll back tracking when the host rejects a queued message. */\nexport function forgetPendingEcho(state: SessionState, messageId: string): void {\n state.pendingEchoMessageIds.delete(messageId);\n}\n\n/** Match and consume one plugin-owned `user/message` event by stable message ID. */\nexport function isOurEcho(state: SessionState, event: SessionEvent): boolean {\n if (event.type !== 'user/message') return false;\n const message = event.data;\n if (message.source.kind !== 'user') return false;\n if (state.pendingEchoMessageIds.size === 0) return false;\n const now = Date.now();\n prunePendingEchoMessageIds(state, now);\n return state.pendingEchoMessageIds.delete(message.id);\n}\n", "/**\n * `auto-continue` namespace dictionaries: copy for the plugin settings card\n * registered into the `settings.plugin.item` seat of the plugin-configuration\n * section. Includes the card-chrome keys the card component reads.\n */\nimport { LOCALIZED_TEXT_DEFAULTS } from '../shared/core.ts';\n\n/** 简体中文词典(键集的事实来源)。 */\nexport const zh = {\n 'chrome.saved': '所有更改已保存',\n 'notification.title': '自动继续设置',\n 'notification.enabled': '设置已保存,浏览器通知已开启。',\n 'notification.disabled': '设置已保存,浏览器通知已关闭。',\n 'notification.saved': '自动继续的设置已保存。',\n 'notification.blocked': '设置已保存,但浏览器尚未允许通知。请在此网站的权限设置中允许通知。',\n 'notification.unsupported': '设置已保存,当前浏览器不支持通知。',\n 'notification.failed': '设置已保存,但浏览器通知未能发出。请检查网站和系统的通知权限。',\n 'chrome.categories': '设置类别',\n 'repo.star': '觉得好用的话,点个 Star 吧',\n 'repo.link': 'GitHub 仓库',\n 'repo.aria': '在新标签页打开 HsiangNianian/dsh-auto-continue 的 GitHub 仓库',\n 'category.general.title': '常规',\n 'category.general.description': '控制自动继续的启停、显示和通知。',\n 'category.recovery.title': '重试策略',\n 'category.recovery.description': '设置等待时间、次数上限和错误分类。',\n 'category.startup.title': '启动恢复',\n 'category.startup.description': 'DSH 重启后,找回最近中断的会话。',\n 'category.prompts.title': '继续文本',\n 'category.prompts.description': '留空使用内置文案,跟随 DSH 的界面语言。',\n 'category.safety.title': '安全保护',\n 'category.safety.description': '避免重复执行工具,识别并打断无效循环。',\n 'category.status.title': '状态与日志',\n 'category.status.description': '查看活动记录与暂停的会话。',\n 'field.paused': '全局启用自动继续',\n 'field.showComposerToggle': '在会话区显示自动继续开关',\n 'field.showComposerToggleHint': '默认显示。隐藏控件不会改变会话模式;点击保存后生效。',\n 'composer.label': '自动继续',\n 'composer.mode': '自动继续模式',\n 'composer.scope': '只控制当前会话,立即保存并同步到其他标签页。关闭后也不再自动打断循环。',\n 'composer.default': '跟随默认',\n 'composer.off': '关闭',\n 'composer.recover': '仅故障恢复',\n 'composer.loop': '自主循环',\n 'composer.paused': '全局已暂停',\n 'composer.unavailable': '等待宿主连接',\n 'composer.saving': '正在保存自动继续设置…',\n 'composer.saveFailed': '保存失败,请重试',\n 'field.pausedHint': '恢复意外中断的会话。关闭并保存后,全局暂停恢复并取消已排队的继续。循环守卫独立运行;如需停止自动打断,请同时关闭循环守卫。',\n 'field.continueText': '继续文本',\n 'field.continueTextHint': '中断后自动发送的消息内容。',\n 'default.continueText': LOCALIZED_TEXT_DEFAULTS.zh.continueText,\n 'field.continueTextMaxTokens': '超限时的继续文本',\n 'field.continueTextMaxTokensHint': '达到输出 token 上限时自动发送的文本, 支持与继续文本相同的占位符。',\n 'default.continueTextMaxTokens': LOCALIZED_TEXT_DEFAULTS.zh.continueTextMaxTokens,\n 'field.resumeSilentTurns': '续跑无输出回合',\n 'field.resumeSilentTurnsHint': '已观察到模型活动但没有可见输出时续跑;不把空回合、图片或扩展内容误判为静默,冷却与连续上限照常生效。',\n 'field.resumeCompletedTurns': '默认会话模式',\n 'field.resumeCompletedTurnsHint': '用于没有单独设置模式的会话。仅故障恢复不会接力正常完成的回合;自主循环会在正常完成后继续。无输出和失败回合仍受重试预算约束。',\n 'field.continueTextLoop': '自主循环的继续文本',\n 'field.continueTextLoopHint': '自主循环每次续跑时发送的文本。',\n 'default.continueTextLoop': LOCALIZED_TEXT_DEFAULTS.zh.continueTextLoop,\n 'field.continueTextSilent': '无输出回合的继续文本',\n 'field.continueTextSilentHint': '回合只输出推理就结束时自动发送的文本, 支持与继续文本相同的占位符。',\n 'default.continueTextSilent': LOCALIZED_TEXT_DEFAULTS.zh.continueTextSilent,\n 'field.continueTextInterrupted': '宿主重启后恢复的继续文本',\n 'field.continueTextInterruptedHint': '启动扫描恢复重启中断的会话时发送的文本, 默认说明重启并提醒先核实再重试。',\n 'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.zh.continueTextInterrupted,\n 'field.guardTools': '幂等护栏',\n 'field.guardToolsHint': '续跑前检查上一步工具调用: 结果未确认时提示先确认状态, 已成功时提示不要重复执行, 避免重复 commit/调 API。',\n 'field.guardPendingText': '结果未确认时的护栏文本',\n 'field.guardPendingTextHint': '上一步工具可能已部分执行时附加到继续文本之后, 支持 {tool} 占位符。',\n 'default.guardPendingText': LOCALIZED_TEXT_DEFAULTS.zh.guardPendingText,\n 'field.guardDoneText': '工具已成功时的护栏文本',\n 'field.guardDoneTextHint': '上一步工具已确认成功时附加到继续文本之后, 支持 {tool} 与 {result}(结果摘要)占位符。',\n 'default.guardDoneText': LOCALIZED_TEXT_DEFAULTS.zh.guardDoneText,\n 'field.graceMs': '宽限期 (ms)',\n 'field.graceMsHint': '检测到中断后等待的时长; 期间宿主自行恢复则取消。',\n 'field.cooldownMs': '冷却时间 (ms)',\n 'field.cooldownMsHint': '同一会话恢复尝试的最小间隔;期间出现的失败会等待剩余冷却,再进入宽限期。正常完成后的自主循环接力不受此限制。',\n 'field.maxConsecutive': '最大连续次数',\n 'field.maxConsecutiveHint': '连续恢复尝试上限;用户介入或观察到有可见输出的成功回合后清零。正常完成后的自主循环接力不计入。',\n 'field.scanOnBoot': '启动恢复扫描',\n 'field.scanOnBootHint': '宿主启动后在扫描时间窗内等待延迟加载的中断会话,未重新加载的持久化会话也会被物化一并检查,每个已就绪会话只检查一次。',\n 'field.scanLimit': '扫描会话数',\n 'field.scanLimitHint': '每次扫描最多恢复多少个符合条件的会话,优先最近活动的会话。',\n 'field.freshMs': '扫描时间窗 (ms)',\n 'field.freshMsHint': '只处理该时间窗内的中断;启动轮询也会在这段时间后结束。',\n 'field.verbose': '详细日志',\n 'field.verboseHint': '在 DSH 宿主日志中输出 [auto-continue] 引擎活动;CLI 用户可在运行 DSH 的终端查看。',\n 'field.classify': '错误分类',\n 'field.classifyHint': '仅自动恢复临时性错误(网络/超时/5xx 等); 认证/余额/模型不存在等永久性错误跳过并通知。',\n 'field.retryableErrorPatterns': '自定义可恢复错误',\n 'field.retryableErrorPatternsHint': '每行一个大小写不敏感的普通文本片段; 命中错误码、HTTP 状态或消息时覆盖内置分类。请只填 provider 稳定且足够具体的文案, 过宽会重复请求。',\n 'field.retryableErrorPatternsPlaceholder': '例如:Upstream rejected the request as invalid',\n 'field.backoffFactor': '退避系数',\n 'field.backoffFactorHint': '连续失败时冷却间隔的倍率(如 2 表示 20s→40s→80s 递增)。',\n 'field.backoffMaxMs': '最大退避间隔 (ms)',\n 'field.backoffMaxMsHint': '自适应退避的上限, 防止等待过久。',\n 'field.notify': '浏览器通知',\n 'field.notifyHint': '开启后,自动继续事件和配置保存成功时会通知。切换此选项并保存后也会确认状态;首次开启需允许浏览器通知。',\n 'stats.title': '今日统计',\n 'stats.sent': '自动继续',\n 'stats.skipped': '跳过(永久错误)',\n 'stats.recovered': '恢复成功',\n 'stats.failed': '继续后仍失败',\n 'stats.gaveUp': '停止(达上限)',\n 'stats.looped': '循环打断',\n 'field.loopGuard': '循环守卫',\n 'field.loopGuardHint': '检测运行中的回合空转: 连续短句且无工具调用、流式消息内连续复读, 或连续调用相同工具时, 自动取消并用循环提示文本重启回合。',\n 'field.loopShortChars': '短句长度上限 (字符)',\n 'field.loopShortCharsHint': '模型消息文本短于该值计为一条短句(空转信号)。',\n 'field.loopWindowMs': '短句时间窗 (ms)',\n 'field.loopWindowMsHint': '连续短句必须落在这个时间窗内; 正常思考的短文本散布在长时间里不会被误判。',\n 'field.loopShortCount': '连续短句阈值',\n 'field.loopShortCountHint': '时间窗内连续多少条短句且期间无工具调用时判定空转循环。',\n 'field.loopRepeatText': '相同消息重复次数',\n 'field.loopRepeatTextHint': '连续输出多少条完全相同的消息时判定空转(最强信号, 不限长度, 也用于流式消息内连续复读段落)。',\n 'field.loopToolRepeat': '同工具重复次数',\n 'field.loopToolRepeatHint': '同工具+同参数+同结果的连续调用多少次时判定死循环; 参数或结果有变化视为有进展。',\n 'field.loopText': '循环提示文本',\n 'field.loopTextHint': '打断后重启回合时发送的文本, 支持 {tool} 占位符。',\n 'default.loopText': LOCALIZED_TEXT_DEFAULTS.zh.loopText,\n 'stats.byCode': '按错误码统计',\n 'stats.empty': '今天还没有自动继续记录。',\n 'stats.reset': '清零',\n 'recovery.title': '近期恢复尝试',\n 'recovery.hint': '按会话汇总宿主最近 20 次恢复提示,重启插件后清空。正常自主续跑不计入。提示已发送不代表任务已完成;若反复恢复,请检查会话并考虑交接到新会话。',\n 'recovery.empty': '尚无恢复尝试。',\n 'recovery.count': '窗口内尝试',\n 'recovery.consecutive': '最近发送时连续次数',\n 'recovery.latest': '最近原因',\n 'recovery.reason.error': '请求错误',\n 'recovery.reason.max-tokens': '输出上限',\n 'recovery.reason.silent': '无可见输出',\n 'recovery.reason.interrupted': '宿主重启中断',\n 'recovery.reason.loop-guard': '循环守卫',\n 'recovery.reason.manual': '手动立即续跑',\n 'pause.title': '已暂停会话',\n 'pause.none': '没有暂停中的会话。',\n 'pause.clearAll': '全部解除',\n 'pause.unpause': '解除',\n 'pause.minutes': '分钟',\n 'chrome.collapse': '收起设置',\n 'chrome.expand': '展开设置',\n 'chrome.unsaved': '未保存',\n 'chrome.readOnly': '当前部署的设置只读。',\n 'chrome.unavailable': '设置暂不可用。',\n 'chrome.saveFailed': '部署未接受这些值, 已保留供你修改。',\n 'chrome.discard': '放弃',\n 'chrome.saving': '保存中…',\n 'chrome.save': '保存',\n 'chrome.overridden': '已覆盖',\n 'chrome.reset': '恢复默认',\n 'chrome.invalidNumber': '请输入数字, 留空则使用默认值。',\n 'chrome.inherit': '继承',\n 'chrome.on': '开',\n 'chrome.off': '关',\n} satisfies Record<string, string>;\n\n/** 本插件的键联合。 */\nexport type SettingsCardKey = keyof typeof zh;\n\n/** English dictionary, checked complete against the zh key set. */\nexport const en: Record<SettingsCardKey, string> = {\n 'chrome.saved': 'All changes saved',\n 'notification.title': 'Auto-continue settings',\n 'notification.enabled': 'Settings saved. Browser notifications are on.',\n 'notification.disabled': 'Settings saved. Browser notifications are off.',\n 'notification.saved': 'Your auto-continue settings have been saved.',\n 'notification.blocked': 'Settings saved, but browser notifications are not allowed. Allow notifications in this site’s permissions.',\n 'notification.unsupported': 'Settings saved. This browser does not support notifications.',\n 'notification.failed': 'Settings saved, but the notification could not be sent. Check notification permissions for this site and your system.',\n 'chrome.categories': 'Settings categories',\n 'repo.star': 'Finding it useful? Leave a Star',\n 'repo.link': 'GitHub repo',\n 'repo.aria': 'Open HsiangNianian/dsh-auto-continue on GitHub in a new tab',\n 'category.general.title': 'General',\n 'category.general.description': 'Control automatic recovery, visibility, and notifications.',\n 'category.recovery.title': 'Retry strategy',\n 'category.recovery.description': 'Set wait times, retry limits, and error classification.',\n 'category.startup.title': 'Startup recovery',\n 'category.startup.description': 'Find recently interrupted sessions when DSH restarts.',\n 'category.prompts.title': 'Continue text',\n 'category.prompts.description': 'Leave blank for built-in text in the current DSH language.',\n 'category.safety.title': 'Safety',\n 'category.safety.description': 'Avoid duplicate tool actions and break unproductive loops.',\n 'category.status.title': 'Status and logs',\n 'category.status.description': 'View activity and paused sessions.',\n 'field.paused': 'Enable auto-continue globally',\n 'field.showComposerToggle': 'Show auto-continue switch in the composer',\n 'field.showComposerToggleHint': 'Shown by default. Hiding the control does not change session modes. Click Save to apply.',\n 'composer.label': 'Auto-continue',\n 'composer.mode': 'Auto-continue mode',\n 'composer.scope': 'Only affects this session. Saved immediately and synced across tabs. Off also disables loop-guard interruptions here.',\n 'composer.default': 'Follow default',\n 'composer.off': 'Off',\n 'composer.recover': 'Recovery only',\n 'composer.loop': 'Autonomous loop',\n 'composer.paused': 'Globally paused',\n 'composer.unavailable': 'Waiting for host',\n 'composer.saving': 'Saving auto-continue setting…',\n 'composer.saveFailed': 'Could not save. Try again.',\n 'field.pausedHint': 'Resume interrupted sessions. Turn off and save to pause recovery globally and cancel queued continuations. The loop guard stays active; turn it off separately to stop automatic interruptions.',\n 'field.continueText': 'Continue text',\n 'field.continueTextHint': 'Message automatically sent after an interruption.',\n 'default.continueText': LOCALIZED_TEXT_DEFAULTS.en.continueText,\n 'field.continueTextMaxTokens': 'Continue text (max tokens)',\n 'field.continueTextMaxTokensHint': 'Text sent when the output token ceiling is reached; same placeholders as the continue text.',\n 'default.continueTextMaxTokens': LOCALIZED_TEXT_DEFAULTS.en.continueTextMaxTokens,\n 'field.resumeSilentTurns': 'Resume silent turns',\n 'field.resumeSilentTurnsHint': 'Resume observed model activity without visible output. No-op turns, images and extension blocks are not treated as silent; cooldown and retry limits still apply.',\n 'field.resumeCompletedTurns': 'Default session mode',\n 'field.resumeCompletedTurnsHint': 'Applies to sessions without their own mode. Recovery only leaves normal completions alone; autonomous loop continues after them. Silent and failed turns still consume the retry budget.',\n 'field.continueTextLoop': 'Continue text (autonomous loop)',\n 'field.continueTextLoopHint': 'Text sent on each autonomous-loop continuation.',\n 'default.continueTextLoop': LOCALIZED_TEXT_DEFAULTS.en.continueTextLoop,\n 'field.continueTextSilent': 'Continue text (silent turn)',\n 'field.continueTextSilentHint': 'Text sent when a turn ends with reasoning only; same placeholders as the continue text.',\n 'default.continueTextSilent': LOCALIZED_TEXT_DEFAULTS.en.continueTextSilent,\n 'field.continueTextInterrupted': 'Continue text (after harness restart)',\n 'field.continueTextInterruptedHint': 'Text sent when the boot scan resumes a session interrupted by a restart; the default explains the restart and asks to verify before retrying.',\n 'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.en.continueTextInterrupted,\n 'field.guardTools': 'Idempotency guard',\n 'field.guardToolsHint': 'Before resuming, inspect the last tool call: if its result is unconfirmed, tell the model to check state first; if it succeeded, tell it not to rerun — avoids duplicate commits / API calls.',\n 'field.guardPendingText': 'Guard text (unconfirmed result)',\n 'field.guardPendingTextHint': 'Appended when the last tool may have partially executed; supports the {tool} placeholder.',\n 'default.guardPendingText': LOCALIZED_TEXT_DEFAULTS.en.guardPendingText,\n 'field.guardDoneText': 'Guard text (tool succeeded)',\n 'field.guardDoneTextHint': 'Appended when the last tool is confirmed done; supports {tool} and {result} (result excerpt).',\n 'default.guardDoneText': LOCALIZED_TEXT_DEFAULTS.en.guardDoneText,\n 'field.graceMs': 'Grace period (ms)',\n 'field.graceMsHint': 'Wait after an interruption; cancelled if the host recovers on its own.',\n 'field.cooldownMs': 'Cooldown (ms)',\n 'field.cooldownMsHint': 'Minimum interval between recovery attempts; failures during cooldown wait for the remaining interval, then grace. Normal autonomous-loop handoffs are exempt.',\n 'field.maxConsecutive': 'Max consecutive',\n 'field.maxConsecutiveHint': 'Consecutive recovery-attempt cap; resets on user intervention or an observed completion with visible output. Normal autonomous-loop handoffs are exempt.',\n 'field.scanOnBoot': 'Scan on host startup',\n 'field.scanOnBootHint': 'Wait for delayed interrupted sessions during the startup scan window; persisted sessions the host never reloaded are materialized and inspected too; each settled session is inspected once.',\n 'field.scanLimit': 'Scan limit',\n 'field.scanLimitHint': 'Maximum eligible sessions to recover per pass, most recently active first.',\n 'field.freshMs': 'Scan window (ms)',\n 'field.freshMsHint': 'Only interruptions inside this window are considered; startup polling also ends after this duration.',\n 'field.verbose': 'Verbose logs',\n 'field.verboseHint': 'Write engine activity to DSH host logs with the [auto-continue] prefix; CLI users can read them in the terminal running DSH.',\n 'field.classify': 'Classify errors',\n 'field.classifyHint': 'Auto-resume transient failures only (network/timeout/5xx…); auth, balance and model errors are skipped and notified.',\n 'field.retryableErrorPatterns': 'Custom retryable errors',\n 'field.retryableErrorPatternsHint': 'One case-insensitive literal per line. A match in the error code, HTTP status, or message overrides built-in classification. Use only stable, provider-specific text; broad matches can repeat requests.',\n 'field.retryableErrorPatternsPlaceholder': 'For example: Upstream rejected the request as invalid',\n 'field.backoffFactor': 'Backoff factor',\n 'field.backoffFactorHint': 'Cooldown multiplier per consecutive failure (2 = 20s→40s→80s…).',\n 'field.backoffMaxMs': 'Max backoff (ms)',\n 'field.backoffMaxMsHint': 'Cap on the adaptive backoff interval.',\n 'field.notify': 'Browser notifications',\n 'field.notifyHint': 'Notify about auto-continue events and successful settings saves. Saving a change to this option also confirms its state. Allow browser notifications when first enabling it.',\n 'stats.title': \"Today's stats\",\n 'stats.sent': 'Auto-continued',\n 'stats.skipped': 'Skipped (permanent)',\n 'stats.recovered': 'Recovered',\n 'stats.failed': 'Failed after',\n 'stats.gaveUp': 'Gave up (cap)',\n 'stats.looped': 'Loops broken',\n 'field.loopGuard': 'Loop guard',\n 'field.loopGuardHint': 'Detects a running turn spinning in place — many short sentences with no tool calls, repeated paragraphs inside one streamed assistant message, or the same tool repeating — then cancels and restarts with the loop text.',\n 'field.loopShortChars': 'Short-sentence max (chars)',\n 'field.loopShortCharsHint': 'A model message shorter than this counts as a short sentence (spinning signal).',\n 'field.loopWindowMs': 'Short-sentence window (ms)',\n 'field.loopWindowMsHint': 'Consecutive short sentences must land inside this window; normal thinking spread over time is not misjudged.',\n 'field.loopShortCount': 'Short-sentence threshold',\n 'field.loopShortCountHint': 'How many consecutive short sentences inside the window, with no tool call, trip the loop guard.',\n 'field.loopRepeatText': 'Identical message count',\n 'field.loopRepeatTextHint': 'How many consecutive identical messages trip the guard (strongest signal, any length; also used for repeated paragraphs inside one streamed assistant message).',\n 'field.loopToolRepeat': 'Same-tool repeat count',\n 'field.loopToolRepeatHint': 'How many consecutive calls of the same tool with identical arguments and results trip the loop guard; a changed argument or result counts as progress.',\n 'field.loopText': 'Loop text',\n 'field.loopTextHint': 'Text sent after the loop guard restarts a turn; supports the {tool} placeholder.',\n 'default.loopText': LOCALIZED_TEXT_DEFAULTS.en.loopText,\n 'stats.byCode': 'By error code',\n 'stats.empty': 'No auto-continue activity today.',\n 'stats.reset': 'Reset',\n 'recovery.title': 'Recent recovery attempts',\n 'recovery.hint': 'Per-session counts from the last 20 recovery prompts across this host, cleared when the plugin restarts. Normal autonomous continuations are excluded. A sent prompt does not mean the task finished. If recovery keeps repeating, review the conversation and consider handing off to a fresh session.',\n 'recovery.empty': 'No recovery attempts yet.',\n 'recovery.count': 'Attempts in window',\n 'recovery.consecutive': 'Consecutive at last send',\n 'recovery.latest': 'Latest reason',\n 'recovery.reason.error': 'Request error',\n 'recovery.reason.max-tokens': 'Output limit',\n 'recovery.reason.silent': 'No visible output',\n 'recovery.reason.interrupted': 'Host restart interruption',\n 'recovery.reason.loop-guard': 'Loop guard',\n 'recovery.reason.manual': 'Manual resume',\n 'pause.title': 'Paused sessions',\n 'pause.none': 'No sessions paused.',\n 'pause.clearAll': 'Clear all',\n 'pause.unpause': 'Resume',\n 'pause.minutes': 'min',\n 'chrome.collapse': 'Hide settings',\n 'chrome.expand': 'Show settings',\n 'chrome.unsaved': 'Unsaved',\n 'chrome.readOnly': 'This deployment stores settings read-only.',\n 'chrome.unavailable': 'Settings are unavailable.',\n 'chrome.saveFailed': 'The deployment did not accept these values; they were left for you to correct.',\n 'chrome.discard': 'Discard',\n 'chrome.saving': 'Saving…',\n 'chrome.save': 'Save',\n 'chrome.overridden': 'Overridden',\n 'chrome.reset': 'Reset to default',\n 'chrome.invalidNumber': 'Enter a number, or leave blank to use the default.',\n 'chrome.inherit': 'Inherit',\n 'chrome.on': 'On',\n 'chrome.off': 'Off',\n};\n", "/**\n * The auto-continue settings card: edits the `auto-continue` namespace fields\n * from the legacy settings section or the bundle's plugin-manager page.\n *\n * Self-contained card chrome (disclosure header, staged fields, save/discard\n * footer) following the plugin-card store pattern of the DSH plugin\n * configuration section; styles live in `styles.ts` and use the DSH design\n * tokens so the card follows the active theme.\n */\nimport { useEffect, useId, useState, type ReactNode } from 'react';\nimport type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots';\nimport { DEFAULT_CONFIG, type AutoContinueSettings } from './engine.ts';\nimport type { SessionMode } from '../shared/core.ts';\nimport type { ComposerToggleFace, ComposerToggleState } from './composer-toggle.tsx';\nimport { NativeSwitch } from './native-switch.tsx';\nimport { createSnapshotStore, type SettingsScope, type SnapshotStore } from './dsh-store-compat.ts';\nimport {\n pausedSessions,\n readTodayStats,\n readRecoveryAttempts,\n readSessionPolicy,\n resetTodayStats,\n setSessionMode,\n subscribeBridge,\n unpauseSession,\n} from './bridge.ts';\nimport type { SettingsCardKey } from './locales.ts';\nimport {\n booleanField,\n canWriteSettings,\n CardForm,\n numberField,\n textField,\n type CardActions,\n type CardFieldState,\n type CardShell,\n} from './settings-form.ts';\nimport { injectStyles } from './styles.ts';\nimport { prepareSettingsNotification, showSettingsNotification } from './settings-notifications.ts';\n\n// Styles must land during factory materialization so the module system's\n// style bookkeeping (HMR) owns them.\ninjectStyles();\n\n/**\n * Native plugin-settings primitives. Older hosts (and the unit-test fixture)\n * do not export them; the legacy hand-built card stays as the fallback.\n */\nconst nativeSettings = (() => {\n try {\n return require('@deepseek-ai/dsh-client-ui-primitives') as {\n SettingsForm?: React.ComponentType<{\n labels: { save: string; saving: string; saveFailed: string; readOnly: string; unavailable: string };\n state: CardShell;\n onSave: () => void;\n onDiscard: () => void;\n children: ReactNode;\n }>;\n SettingsValueField?: React.ComponentType<Record<string, unknown>>;\n SegmentedControl?: React.ComponentType<{\n id?: string;\n options: ReadonlyArray<{ value: string; label: string }>;\n value: string;\n onChange: (value: string) => void;\n label: string;\n disabled?: boolean;\n }>;\n };\n } catch {\n return {};\n }\n})();\n\nconst NativeSettingsForm = nativeSettings.SettingsForm;\nconst NativeValueField = nativeSettings.SettingsValueField;\nconst NativeSegmentedControl = nativeSettings.SegmentedControl;\nconst hasNativeSettings = typeof NativeSettingsForm === 'function' && typeof NativeValueField === 'function';\n\n/** What the auto-continue card renders. */\nexport interface AutoContinueSettingsCardState extends CardShell {\n /** Committed global state; a staged edit does not pause the engine yet. */\n enabled: boolean;\n /** Feedback for the last local save, including browser permission problems. */\n notificationFeedback: SettingsCardKey | undefined;\n paused: CardFieldState;\n showComposerToggle: CardFieldState;\n continueText: CardFieldState;\n continueTextMaxTokens: CardFieldState;\n resumeSilentTurns: CardFieldState;\n resumeCompletedTurns: CardFieldState;\n continueTextLoop: CardFieldState;\n continueTextSilent: CardFieldState;\n continueTextInterrupted: CardFieldState;\n guardTools: CardFieldState;\n guardPendingText: CardFieldState;\n guardDoneText: CardFieldState;\n graceMs: CardFieldState;\n cooldownMs: CardFieldState;\n maxConsecutive: CardFieldState;\n scanOnBoot: CardFieldState;\n scanLimit: CardFieldState;\n freshMs: CardFieldState;\n verbose: CardFieldState;\n classify: CardFieldState;\n retryableErrorPatterns: CardFieldState;\n backoffFactor: CardFieldState;\n backoffMaxMs: CardFieldState;\n notify: CardFieldState;\n loopGuard: CardFieldState;\n loopShortChars: CardFieldState;\n loopWindowMs: CardFieldState;\n loopShortCount: CardFieldState;\n loopRepeatText: CardFieldState;\n loopToolRepeat: CardFieldState;\n loopText: CardFieldState;\n}\n\n/** The registration-side face the card's slot entry injects. */\nexport interface AutoContinueSettingsCardFace extends CardActions {\n hooks: {\n /** Card snapshot bound by the renderer as useAutoContinueSettingsCard. */\n autoContinueSettingsCard: SnapshotStore<AutoContinueSettingsCardState>;\n };\n}\n\n/** Bridges the `auto-continue` scope onto the card's staged form. */\nexport class AutoContinueSettingsCardController {\n private readonly form: CardForm<AutoContinueSettings>;\n private readonly store: SnapshotStore<AutoContinueSettingsCardState>;\n private readonly composer: SnapshotStore<ComposerToggleState>;\n private readonly composerSaving = new Set<string>();\n private readonly composerFailed = new Set<string>();\n private readonly stopComposer: () => void;\n private disposed = false;\n private saveSequence = 0;\n private notificationFeedback: SettingsCardKey | undefined;\n\n /**\n * @param scope - the bound settings scope for the `auto-continue` namespace.\n */\n constructor(\n private readonly scope: SettingsScope<AutoContinueSettings>,\n private readonly getLocale: () => string,\n ) {\n this.form = new CardForm(scope, [\n booleanField('paused'),\n booleanField('showComposerToggle'),\n textField('continueText'),\n textField('continueTextMaxTokens'),\n booleanField('resumeSilentTurns'),\n booleanField('resumeCompletedTurns'),\n textField('continueTextLoop'),\n textField('continueTextSilent'),\n textField('continueTextInterrupted'),\n booleanField('guardTools'),\n textField('guardPendingText'),\n textField('guardDoneText'),\n numberField('graceMs', 0),\n numberField('cooldownMs', 0),\n numberField('maxConsecutive', 1),\n booleanField('scanOnBoot'),\n numberField('scanLimit', 1),\n numberField('freshMs', 0),\n booleanField('verbose'),\n booleanField('classify'),\n textField('retryableErrorPatterns'),\n numberField('backoffFactor', 1),\n numberField('backoffMaxMs', 0),\n booleanField('notify'),\n booleanField('loopGuard'),\n numberField('loopShortChars', 1),\n numberField('loopWindowMs', 1000),\n numberField('loopShortCount', 2),\n numberField('loopRepeatText', 2),\n numberField('loopToolRepeat', 2),\n textField('loopText'),\n ]);\n this.store = this.form.bind(() => this.projection(), createSnapshotStore);\n this.composer = this.form.bind(() => this.composerProjection(), createSnapshotStore);\n this.stopComposer = subscribeBridge(() => this.composer.set(this.composerProjection()));\n }\n\n private projection(): AutoContinueSettingsCardState {\n return {\n ...this.form.shell(),\n enabled: !(this.scope.getSnapshot().value?.paused ?? DEFAULT_CONFIG.paused),\n notificationFeedback: this.notificationFeedback,\n paused: this.form.field('paused'),\n showComposerToggle: this.form.field('showComposerToggle'),\n continueText: this.form.field('continueText'),\n continueTextMaxTokens: this.form.field('continueTextMaxTokens'),\n resumeSilentTurns: this.form.field('resumeSilentTurns'),\n resumeCompletedTurns: this.form.field('resumeCompletedTurns'),\n continueTextLoop: this.form.field('continueTextLoop'),\n continueTextSilent: this.form.field('continueTextSilent'),\n continueTextInterrupted: this.form.field('continueTextInterrupted'),\n guardTools: this.form.field('guardTools'),\n guardPendingText: this.form.field('guardPendingText'),\n guardDoneText: this.form.field('guardDoneText'),\n graceMs: this.form.field('graceMs'),\n cooldownMs: this.form.field('cooldownMs'),\n maxConsecutive: this.form.field('maxConsecutive'),\n scanOnBoot: this.form.field('scanOnBoot'),\n scanLimit: this.form.field('scanLimit'),\n freshMs: this.form.field('freshMs'),\n verbose: this.form.field('verbose'),\n classify: this.form.field('classify'),\n retryableErrorPatterns: this.form.field('retryableErrorPatterns'),\n backoffFactor: this.form.field('backoffFactor'),\n backoffMaxMs: this.form.field('backoffMaxMs'),\n notify: this.form.field('notify'),\n loopGuard: this.form.field('loopGuard'),\n loopShortChars: this.form.field('loopShortChars'),\n loopWindowMs: this.form.field('loopWindowMs'),\n loopShortCount: this.form.field('loopShortCount'),\n loopRepeatText: this.form.field('loopRepeatText'),\n loopToolRepeat: this.form.field('loopToolRepeat'),\n loopText: this.form.field('loopText'),\n };\n }\n\n /**\n * Build the face the card's slot registration injects.\n * @returns the card's snapshot and its form actions.\n */\n inject(): AutoContinueSettingsCardFace {\n return { hooks: { autoContinueSettingsCard: this.store }, ...this.form.actions(), save: () => void this.save() };\n }\n\n private async save(): Promise<void> {\n const state = this.form.shell();\n const snapshot = this.scope.getSnapshot();\n if (this.disposed || !state.available || !state.writable || !state.dirty || state.invalid || state.saving) return;\n const sequence = ++this.saveSequence;\n const before = snapshot.value?.notify ?? DEFAULT_CONFIG.notify;\n const target = this.form.field('notify').text;\n // Start the permission prompt in the click handler, but save independently.\n const permission = prepareSettingsNotification(target === '' ? DEFAULT_CONFIG.notify : target === 'true');\n this.notificationFeedback = undefined;\n if (!await this.form.save() || this.disposed) return;\n const after = this.scope.getSnapshot().value?.notify ?? DEFAULT_CONFIG.notify;\n if (!before && !after) return;\n const result = await permission;\n // A later save or a provider teardown makes this pending confirmation stale.\n if (this.disposed || sequence !== this.saveSequence || (this.scope.getSnapshot().value?.notify ?? DEFAULT_CONFIG.notify) !== after) return;\n this.notificationFeedback = showSettingsNotification(before === after ? 'saved' : after ? 'enabled' : 'disabled', this.getLocale(), result);\n this.store.set(this.projection());\n }\n\n injectComposer(sessionId: string): ComposerToggleFace {\n return { hooks: { autoContinueComposer: this.composer }, sessionId, setMode: (mode) => void this.setMode(sessionId, mode) };\n }\n\n private composerProjection(): ComposerToggleState {\n const snapshot = this.scope.getSnapshot();\n const policy = readSessionPolicy();\n return {\n visible: snapshot.status === 'ready' && (snapshot.value?.showComposerToggle ?? DEFAULT_CONFIG.showComposerToggle),\n policy,\n writable: canWriteSettings(snapshot) && policy?.writable === true,\n saving: new Set(this.composerSaving),\n failed: new Set(this.composerFailed),\n };\n }\n\n private async setMode(sessionId: string, mode: SessionMode): Promise<void> {\n if (this.disposed || !sessionId || this.composerSaving.has(sessionId) || !this.composerProjection().writable) return;\n this.composerSaving.add(sessionId);\n this.composerFailed.delete(sessionId);\n this.composer.set(this.composerProjection());\n try {\n await setSessionMode(sessionId, mode);\n } catch {\n this.composerFailed.add(sessionId);\n } finally {\n this.composerSaving.delete(sessionId);\n if (!this.disposed) this.composer.set(this.composerProjection());\n }\n }\n\n /** Release this card's subscription to the provider-owned settings form. */\n dispose(): void {\n this.disposed = true;\n this.stopComposer();\n this.form.dispose();\n }\n}\n\n/** Props the renderer binds for the auto-continue plugin-configuration card. */\nexport type AutoContinueSettingsCardProps =\n PropsLocale<'auto-continue'> & InjectFace<AutoContinueSettingsCardFace>;\n\n/** The bundle page supplies no list container, unlike the legacy settings slot. */\nexport function AutoContinueSettingsPage(props: AutoContinueSettingsCardProps) {\n return (\n <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>\n <AutoContinueSettingsCard {...props} />\n </ul>\n );\n}\n\ntype FieldName = Exclude<keyof AutoContinueSettingsCardState, keyof CardShell | 'enabled' | 'notificationFeedback'>;\nconst groups = [\n { id: 'general', fields: ['paused', 'showComposerToggle', 'resumeSilentTurns', 'resumeCompletedTurns', 'notify'] },\n { id: 'recovery', fields: ['graceMs', 'cooldownMs', 'maxConsecutive', 'classify', 'retryableErrorPatterns', 'backoffFactor', 'backoffMaxMs'] },\n { id: 'startup', fields: ['scanOnBoot', 'scanLimit', 'freshMs'] },\n { id: 'prompts', fields: ['continueText', 'continueTextMaxTokens', 'continueTextSilent', 'continueTextInterrupted', 'continueTextLoop', 'guardPendingText', 'guardDoneText', 'loopText'] },\n { id: 'safety', fields: ['guardTools', 'loopGuard', 'loopShortChars', 'loopWindowMs', 'loopShortCount', 'loopRepeatText', 'loopToolRepeat'] },\n { id: 'status', fields: ['verbose'] },\n] as const satisfies ReadonlyArray<{ id: string; fields: readonly FieldName[] }>;\ntype Category = typeof groups[number]['id'];\nconst textDefaults: Partial<Record<FieldName, SettingsCardKey>> = {\n continueText: 'default.continueText', continueTextMaxTokens: 'default.continueTextMaxTokens',\n continueTextSilent: 'default.continueTextSilent', continueTextLoop: 'default.continueTextLoop',\n continueTextInterrupted: 'default.continueTextInterrupted',\n guardPendingText: 'default.guardPendingText', guardDoneText: 'default.guardDoneText', loopText: 'default.loopText',\n};\n\nconst REPOSITORY_URL = 'https://github.com/HsiangNianian/dsh-auto-continue';\n\nfunction RepositoryInvite({ t }: { t: (key: SettingsCardKey) => string }) {\n return <p className=\"dshAcInvite\">\n <span className=\"dshAcInviteStar\" aria-hidden=\"true\">★</span>\n <span>{t('repo.star')}</span>\n <a className=\"dshAcRepoLink\" href={REPOSITORY_URL} target=\"_blank\" rel=\"noopener noreferrer\" aria-label={t('repo.aria')}>\n <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M12 2.4a9.8 9.8 0 0 0-3.1 19.1c.5.1.7-.2.7-.5v-1.9c-2.8.6-3.4-1.2-3.4-1.2-.5-1.1-1.1-1.4-1.1-1.4-.9-.6.1-.6.1-.6 1 0 1.5 1 1.5 1 .9 1.5 2.3 1.1 2.9.8.1-.6.4-1.1.6-1.3-2.2-.3-4.6-1.1-4.6-4.9 0-1.1.4-2 1-2.7-.1-.3-.4-1.3.1-2.7 0 0 .8-.3 2.8 1a9.5 9.5 0 0 1 5 0c1.9-1.3 2.8-1 2.8-1 .5 1.4.2 2.4.1 2.7.6.7 1 1.6 1 2.7 0 3.8-2.3 4.6-4.6 4.9.4.3.7.9.7 1.8V21c0 .3.2.6.7.5A9.8 9.8 0 0 0 12 2.4Z\" /></svg>\n {t('repo.link')}\n <svg className=\"dshAcExternal\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M6 3h7v7M13 3 7 9M11 9v3a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h3\" /></svg>\n </a>\n </p>;\n}\n\n/** Controls edit the existing staged form; navigation never owns or discards drafts. */\nfunction SettingField({ name, id, state, actions, disabled, t }: {\n name: FieldName; id: string; state: CardFieldState; actions: CardActions; disabled: boolean;\n t: (key: SettingsCardKey) => string;\n}) {\n const boolean = typeof DEFAULT_CONFIG[name] === 'boolean';\n const numeric = typeof DEFAULT_CONFIG[name] === 'number';\n const label = t(`field.${name}` as SettingsCardKey);\n const hint = t(`field.${name}Hint` as SettingsCardKey);\n const value = state.text === '' ? DEFAULT_CONFIG[name] : state.text === 'true';\n const placeholderKey = textDefaults[name];\n const placeholder = placeholderKey ? t(placeholderKey) : name === 'retryableErrorPatterns' ? t('field.retryableErrorPatternsPlaceholder') : String(DEFAULT_CONFIG[name]);\n const common = { id, disabled, 'aria-describedby': `${id}-hint`, 'aria-invalid': state.invalid || undefined, value: state.text, onChange: (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => actions.edit(name, event.target.value) };\n return <div className={`dshAcField${!boolean && !numeric ? ' dshAcFieldText' : ''}`} data-field={name}>\n <div className=\"dshAcFieldCopy\">\n {boolean ? <span className=\"dshAcLabel\">{label}</span> : <label className=\"dshAcLabel\" htmlFor={id}>{label}</label>}\n <p className={state.invalid ? 'dshAcInvalid' : 'dshAcHint'} id={`${id}-hint`}>{state.invalid ? t('chrome.invalidNumber') : hint}</p>\n </div>\n <div className=\"dshAcFieldControl\">\n {state.overridden && <button type=\"button\" className=\"dshAcReset\" disabled={disabled} aria-label={`${t('chrome.reset')}: ${label}`} onClick={() => actions.resetField(name)}>{t('chrome.reset')}</button>}\n {name === 'resumeCompletedTurns' ? <select id={id} className=\"dshAcMode\" aria-label={label} aria-describedby={`${id}-hint`}\n disabled={disabled} value={String(value)} onChange={event => actions.edit(name, event.target.value)}>\n <option value=\"false\">{t('composer.recover')}</option><option value=\"true\">{t('composer.loop')}</option>\n </select> : boolean ? <span className=\"dshAcSwitchTarget\"><NativeSwitch label={label} title={hint} disabled={disabled}\n checked={name === 'paused' ? !value : Boolean(value)} onChange={checked => actions.edit(name, String(name === 'paused' ? !checked : checked))} /></span>\n : numeric ? <input {...common} className=\"dshAcInput dshAcNumber\" type=\"text\" inputMode=\"numeric\" placeholder={placeholder} />\n : <textarea {...common} className=\"dshAcInput dshAcTextArea\" rows={name === 'retryableErrorPatterns' ? 3 : 2} placeholder={placeholder} />}\n </div>\n </div>;\n}\n\n\n/** One field rendered with the host's own settings primitives. */\nfunction NativeSettingField({ name, id, state, actions, disabled, t }: {\n name: FieldName; id: string; state: CardFieldState; actions: CardActions; disabled: boolean;\n t: (key: SettingsCardKey) => string;\n}) {\n const boolean = typeof DEFAULT_CONFIG[name] === 'boolean';\n const numeric = typeof DEFAULT_CONFIG[name] === 'number';\n const label = t(`field.${name}` as SettingsCardKey);\n const hint = t(`field.${name}Hint` as SettingsCardKey);\n const value = state.text === '' ? DEFAULT_CONFIG[name] : state.text === 'true';\n const placeholderKey = textDefaults[name];\n const placeholder = placeholderKey ? t(placeholderKey) : name === 'retryableErrorPatterns' ? t('field.retryableErrorPatternsPlaceholder') : String(DEFAULT_CONFIG[name]);\n const reset = state.overridden\n ? <button type=\"button\" className=\"dshAcNativeReset\" disabled={disabled} aria-label={`${t('chrome.reset')}: ${label}`} onClick={() => actions.resetField(name)}>{t('chrome.reset')}</button>\n : null;\n\n if (name === 'resumeCompletedTurns') {\n const items = [{ value: 'false', label: t('composer.recover') }, { value: 'true', label: t('composer.loop') }];\n return <div className=\"dshAcNativeField\" data-field={name}>\n <div className=\"dshAcNativeHead\"><label className=\"dshAcNativeLabel\" htmlFor={id}>{label}</label>{reset}</div>\n {NativeSegmentedControl\n ? <NativeSegmentedControl id={id} options={items} value={value ? 'true' : 'false'} onChange={next => actions.edit(name, next)} label={label} disabled={disabled} />\n : <select id={id} className=\"dshAcMode\" aria-label={label} disabled={disabled} value={String(value)} onChange={event => actions.edit(name, event.target.value)}>\n <option value=\"false\">{t('composer.recover')}</option><option value=\"true\">{t('composer.loop')}</option>\n </select>}\n <p className=\"dshAcNativeHint\" id={`${id}-hint`}>{hint}</p>\n </div>;\n }\n\n if (boolean) {\n return <div className=\"dshAcNativeField\" data-field={name}>\n <div className=\"dshAcNativeToggleRow\">\n <label className=\"dshAcNativeLabel\" htmlFor={id}>{label}</label>\n <span className=\"dshAcNativeActions\">\n {reset}\n <NativeSwitch label={label} title={hint} disabled={disabled}\n checked={name === 'paused' ? !value : Boolean(value)}\n onChange={checked => actions.edit(name, String(name === 'paused' ? !checked : checked))} />\n </span>\n </div>\n <p className=\"dshAcNativeHint\" id={`${id}-hint`}>{hint}</p>\n </div>;\n }\n\n if (numeric) {\n const ValueField = NativeValueField!;\n return <ValueField id={id} label={label} hint={hint} overriddenLabel={t('chrome.overridden')}\n resetLabel={t('chrome.reset')} invalidLabel={t('chrome.invalidNumber')} disabled={disabled}\n numeric {...state} placeholder={placeholder}\n onEdit={(text: string) => actions.edit(name, text)} onReset={() => actions.resetField(name)} />;\n }\n\n return <div className=\"dshAcNativeField\" data-field={name}>\n <div className=\"dshAcNativeHead\"><label className=\"dshAcNativeLabel\" htmlFor={id}>{label}</label>{reset}</div>\n <textarea id={id} className=\"dshAcNativeTextarea\" rows={name === 'retryableErrorPatterns' ? 3 : 2}\n disabled={disabled} value={state.text} placeholder={placeholder} aria-invalid={state.invalid || undefined}\n aria-describedby={`${id}-hint`} onChange={event => actions.edit(name, event.target.value)} />\n <p className=\"dshAcNativeHint\" id={`${id}-hint`}>{state.invalid ? t('chrome.invalidNumber') : hint}</p>\n </div>;\n}\n\n/** 实时面板: 今日统计 + 已暂停会话。浏览器本地状态, 每 5 秒刷新一次。 */\nfunction LivePanels(props: { t: (key: SettingsCardKey) => string }) {\n const { t } = props;\n const [, refresh] = useState(0);\n useEffect(() => {\n // host 状态桥推送时刷新; 5 秒轮询兜底(桥短暂断线时)\n const unsubscribe = subscribeBridge(() => refresh((value) => value + 1));\n const timer = setInterval(() => refresh((value) => value + 1), 5000);\n return () => {\n unsubscribe();\n clearInterval(timer);\n };\n }, []);\n const stats = readTodayStats();\n const hasStats = stats.sent + stats.skipped + stats.recovered + stats.failed + stats.gaveUp + stats.looped > 0;\n const codes = Object.entries(stats.byCode)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5);\n const paused = pausedSessions();\n const attempts = readRecoveryAttempts();\n const sessions = [...new Set(attempts.map(attempt => attempt.sessionId))];\n return (\n <>\n <section className=\"dshAcPanel\">\n <div className=\"dshAcPanelHead\">\n <span className=\"dshAcPanelTitle\">{t('stats.title')}</span>\n {hasStats ? (\n <button\n type=\"button\"\n className=\"dshAcReset\"\n onClick={() => {\n resetTodayStats();\n refresh((value) => value + 1);\n }}\n >\n {t('stats.reset')}\n </button>\n ) : null}\n </div>\n {!hasStats ? (\n <p className=\"dshAcHint\">{t('stats.empty')}</p>\n ) : (\n <>\n <dl className=\"dshAcStats\">\n <div><dt>{t('stats.sent')}</dt><dd>{stats.sent}</dd></div>\n <div><dt>{t('stats.recovered')}</dt><dd>{stats.recovered}</dd></div>\n <div><dt>{t('stats.failed')}</dt><dd>{stats.failed}</dd></div>\n <div><dt>{t('stats.skipped')}</dt><dd>{stats.skipped}</dd></div>\n <div><dt>{t('stats.gaveUp')}</dt><dd>{stats.gaveUp}</dd></div>\n <div><dt>{t('stats.looped')}</dt><dd>{stats.looped}</dd></div>\n </dl>\n {codes.length > 0 ? (\n <div className=\"dshAcCodes\">\n <span className=\"dshAcHint\">{t('stats.byCode')}:</span>\n {codes.map(([code, count]) => (\n <span key={code} className=\"dshAcCode\">\n {code} ×{count}\n </span>\n ))}\n </div>\n ) : null}\n </>\n )}\n </section>\n <section className=\"dshAcPanel\">\n <div className=\"dshAcPanelHead\">\n <span className=\"dshAcPanelTitle\">{t('recovery.title')}</span>\n </div>\n <p className=\"dshAcHint\">{t('recovery.hint')}</p>\n {sessions.length === 0 ? <p className=\"dshAcHint\">{t('recovery.empty')}</p> : (\n <ul className=\"dshAcPauseList\">\n {sessions.map(sessionId => {\n const recent = attempts.filter(attempt => attempt.sessionId === sessionId);\n const latest = recent[0]!;\n return (\n <li key={sessionId}>\n <div className=\"dshAcRecovery\">\n <span className=\"dshAcPauseId\">{sessionId}</span>\n <span>{t('recovery.count')}: {recent.length} · {t('recovery.consecutive')}: {latest.consecutive}</span>\n <span>{t('recovery.latest')}: {t(`recovery.reason.${latest.reason}`)}</span>\n <time className=\"dshAcHint\" dateTime={new Date(latest.at).toISOString()}>{new Date(latest.at).toLocaleString()}</time>\n </div>\n </li>\n );\n })}\n </ul>\n )}\n </section>\n <section className=\"dshAcPanel\">\n <div className=\"dshAcPanelHead\">\n <span className=\"dshAcPanelTitle\">{t('pause.title')}</span>\n {paused.length > 0 ? (\n <button\n type=\"button\"\n className=\"dshAcReset\"\n onClick={() => {\n for (const item of paused) unpauseSession(item.sessionId);\n refresh((value) => value + 1);\n }}\n >\n {t('pause.clearAll')}\n </button>\n ) : null}\n </div>\n {paused.length === 0 ? (\n <p className=\"dshAcHint\">{t('pause.none')}</p>\n ) : (\n <ul className=\"dshAcPauseList\">\n {paused.map((item) => (\n <li key={item.sessionId}>\n <span className=\"dshAcPauseId\">{item.sessionId.slice(0, 8)}…</span>\n <span className=\"dshAcHint\">\n {Math.max(1, Math.ceil((item.until - Date.now()) / 60000))} {t('pause.minutes')}\n </span>\n <button\n type=\"button\"\n className=\"dshAcReset\"\n onClick={() => {\n unpauseSession(item.sessionId);\n refresh((value) => value + 1);\n }}\n >\n {t('pause.unpause')}\n </button>\n </li>\n ))}\n </ul>\n )}\n </section>\n </>\n );\n}\n\n/** Native category layout; the plugin manager above already owns the title, version and status. */\nexport function AutoContinueSettingsCard(props: AutoContinueSettingsCardProps) {\n const { t } = props;\n const state = props.useAutoContinueSettingsCard(snapshot => snapshot);\n const [active, setActive] = useState<Category>('general');\n const prefix = useId();\n const group = groups.find(item => item.id === active)!;\n const native = hasNativeSettings;\n if (!state.available) return null;\n return <li className=\"dshAcCard\">\n <RepositoryInvite t={t} />\n {!native && !state.writable && <p className=\"dshAcReadOnly\" role=\"status\">{t('chrome.readOnly')}</p>}\n <div className=\"dshAcLayout\">\n <div className=\"dshAcNav\" role=\"tablist\" aria-label={t('chrome.categories')}>\n {groups.map((item, index) => {\n const invalid = item.fields.some(name => state[name].invalid);\n const title = t(`category.${item.id}.title`);\n return <button type=\"button\" role=\"tab\" key={item.id} id={`${prefix}-tab-${item.id}`} data-category={item.id}\n aria-controls={`${prefix}-panel-${item.id}`} aria-selected={active === item.id} tabIndex={active === item.id ? 0 : -1}\n aria-label={invalid ? `${title}: ${t('chrome.invalidNumber')}` : title}\n onClick={() => setActive(item.id)} onKeyDown={event => {\n const offset = ['ArrowRight', 'ArrowDown'].includes(event.key) ? 1 : ['ArrowLeft', 'ArrowUp'].includes(event.key) ? -1 : 0;\n if (!offset && event.key !== 'Home' && event.key !== 'End') return;\n event.preventDefault();\n const next = event.key === 'Home' ? 0 : event.key === 'End' ? groups.length - 1 : (index + offset + groups.length) % groups.length;\n setActive(groups[next]!.id);\n const button = event.currentTarget.parentElement?.querySelectorAll<HTMLButtonElement>('[role=\"tab\"]')[next];\n button?.focus();\n button?.scrollIntoView({ block: 'nearest', inline: 'nearest' });\n }}>{title}{invalid && <span className=\"dshAcInvalidMark\" aria-hidden=\"true\">!</span>}</button>;\n })}\n </div>\n <section className=\"dshAcCategory\" role=\"tabpanel\" id={`${prefix}-panel-${active}`} aria-labelledby={`${prefix}-tab-${active}`}>\n <div className=\"dshAcCategoryHeading\"><h3>{t(`category.${active}.title`)}</h3><p>{t(`category.${active}.description`)}</p></div>\n {native ? (\n <NativeSettingsForm labels={{\n save: t('chrome.save'), saving: t('chrome.saving'), saveFailed: t('chrome.saveFailed'),\n readOnly: t('chrome.readOnly'), unavailable: t('chrome.unavailable'),\n }} state={state} onSave={props.save} onDiscard={props.discard}>\n <div className=\"dshAcNativeFields\">\n {group.fields.map(name => <NativeSettingField key={name} name={name} id={`${prefix}-${name}`} state={state[name]} actions={props} disabled={!state.writable} t={t} />)}\n {active === 'status' && <LivePanels t={t} />}\n </div>\n </NativeSettingsForm>\n ) : (\n <>\n {group.fields.map(name => <SettingField key={name} name={name} id={`${prefix}-${name}`} state={state[name]} actions={props} disabled={!state.writable} t={t} />)}\n {active === 'status' && <LivePanels t={t} />}\n <footer className=\"dshAcFooter\" data-dirty={state.dirty}>\n <p className={state.failed || state.invalid ? 'dshAcInvalid' : 'dshAcHint'} role=\"status\">{t(state.failed ? 'chrome.saveFailed' : state.invalid ? 'chrome.invalidNumber' : state.saving ? 'chrome.saving' : state.dirty ? 'chrome.unsaved' : state.notificationFeedback ?? 'chrome.saved')}</p>\n <div><button type=\"button\" className=\"dshAcDiscard\" disabled={!state.dirty || state.saving} onClick={props.discard}>{t('chrome.discard')}</button><button type=\"button\" className=\"dshAcSave\" disabled={!state.dirty || state.invalid || state.saving || !state.writable} onClick={props.save}>{t(state.saving ? 'chrome.saving' : 'chrome.save')}</button></div>\n </footer>\n </>\n )}\n </section>\n </div>\n </li>;\n}\n", "import type { ComponentType } from 'react';\n\ninterface SwitchProps {\n checked: boolean;\n onChange: (checked: boolean) => void;\n label: string;\n disabled?: boolean;\n title?: string;\n}\n\n// DSH 0.1.0-rc.7 predates this export. Keep its settings page usable while\n// current hosts render their own Switch, including the active theme's styles.\nfunction legacySwitch(props: SwitchProps) {\n return (\n <button type=\"button\" role=\"switch\" className=\"dshAcSwitch\"\n aria-checked={props.checked} aria-label={props.label} disabled={props.disabled}\n title={props.title} onClick={() => props.onChange(!props.checked)}>\n <span />\n </button>\n );\n}\n\nfunction resolveSwitch(): ComponentType<SwitchProps> {\n try {\n const { Switch } = require('@deepseek-ai/dsh-client-ui-primitives') as { Switch?: ComponentType<SwitchProps> };\n if (typeof Switch === 'function') return Switch;\n } catch {\n // Legacy hosts can omit the primitives module from their client graph.\n }\n return legacySwitch;\n}\n\nexport const NativeSwitch = resolveSwitch();\n", "/**\n * Snapshot-store bridge across the two public DSH client module layouts.\n *\n * DSH 0.1.2 moved the store engine from the dynamic\n * `@deepseek-ai/dsh-client-runtime/client` row into the shell-seeded\n * `@deepseek-ai/dsh-client-store` platform module. Keep the probe dynamic so\n * esbuild does not turn both candidates into eager top-level requires: the\n * loader must only resolve the module that exists in the running DSH cohort.\n */\n\n/** Writable observable snapshot used by the settings card. */\nexport interface SnapshotStore<T> {\n getSnapshot(): T;\n subscribe(listener: () => void): () => void;\n update(mutator: (draft: T) => void): void;\n set(next: T): void;\n}\n\n/** Settings state consumed by the staged form. */\nexport interface SettingsScopeSnapshot<T> {\n status: 'loading' | 'ready' | 'unavailable';\n value: T | undefined;\n base: unknown;\n user: unknown;\n revision: number | undefined;\n writable: boolean;\n mode?: 'host' | 'memory';\n}\n\n/** Stable subset shared by settings scopes and DSH 0.1.7 configuration forms. */\nexport interface SettingsScope<T> {\n getSnapshot(): SettingsScopeSnapshot<T>;\n subscribe(listener: () => void): () => void;\n set(field: string, value: unknown): Promise<void | boolean>;\n unset(field: string): Promise<void | boolean>;\n}\n\ninterface SnapshotStoreModule {\n createSnapshotStore<T>(\n init: T,\n options?: { flush?: 'raf' | 'sync'; persist?: { name: string } },\n ): SnapshotStore<T>;\n}\n\nfunction resolveSnapshotStore(): SnapshotStoreModule {\n // String assembly is intentional: it preserves the lazy try/fallback in the\n // emitted client bundle instead of letting the bundler resolve both names.\n const current = ['@deepseek-ai/dsh-client', '-store'].join('');\n const legacy = ['@deepseek-ai/dsh-client-runtime', '/client'].join('');\n try {\n return require(current) as SnapshotStoreModule;\n } catch {\n return require(legacy) as SnapshotStoreModule;\n }\n}\n\nexport const { createSnapshotStore } = resolveSnapshotStore();\n", "/**\n * Host status bridge, browser side.\n *\n * Subscribes to the host engine's `/api/auto-continue-bridge` SSE stream:\n * notifications (shown via the browser Notification API, action buttons POST\n * to `/api/auto-continue-action`) and runtime state (today's stats and the\n * paused-sessions list) consumed by the settings card's live panels.\n */\n\nimport type { RecoveryAttempt, SessionMode, SessionPolicy } from '../shared/core.ts';\n\n/** 今日统计视图(与 host 引擎的 DayStats 对应)。 */\nexport interface DayStatsView {\n date: string;\n sent: number;\n skipped: number;\n recovered: number;\n failed: number;\n gaveUp: number;\n looped: number;\n byCode: Record<string, number>;\n}\n\n/** 已暂停会话视图。 */\nexport interface PausedSessionView {\n sessionId: string;\n until: number;\n}\n\ninterface BridgeState {\n stats: DayStatsView;\n paused: PausedSessionView[];\n recoveryAttempts: RecoveryAttempt[];\n sessionPolicy?: SessionPolicy;\n}\n\ninterface BridgeNotice {\n id: string;\n title: string;\n body: string;\n sessionId?: string;\n actions: { action: string; title: string }[];\n at: number;\n}\n\nconst EMPTY_STATS: DayStatsView = {\n date: '',\n sent: 0,\n skipped: 0,\n recovered: 0,\n failed: 0,\n gaveUp: 0,\n looped: 0,\n byCode: {},\n};\n\nlet state: BridgeState = { stats: EMPTY_STATS, paused: [], recoveryAttempts: [] };\nconst listeners = new Set<() => void>();\n\n/** 当前桥状态里的已暂停会话(卡片面板用)。 */\nexport function pausedSessions(): PausedSessionView[] {\n return state.paused;\n}\n\n/** 当前桥状态里的今日统计(卡片面板用)。 */\nexport function readTodayStats(): DayStatsView {\n return state.stats;\n}\n\nexport function readRecoveryAttempts(): RecoveryAttempt[] {\n return state.recoveryAttempts;\n}\n\nexport function readSessionPolicy(): SessionPolicy | undefined {\n return state.sessionPolicy;\n}\n\nexport async function setSessionMode(sessionId: string, mode: SessionMode): Promise<void> {\n if (!state.sessionPolicy?.writable) throw new Error('Session settings are unavailable');\n const response = await fetch('/api/auto-continue-action', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ action: 'set-session-mode', sessionId, mode }),\n });\n const result = await response.json();\n if (!response.ok || result?.ok !== true || result.sessionId !== sessionId || result.mode !== mode) {\n throw new Error('Session mode was not saved');\n }\n}\n\n/** 清零今日统计(经动作端点交给 host 引擎执行)。 */\nexport function resetTodayStats(): void {\n void postAction({ action: 'reset-stats' });\n}\n\n/** 解除某个会话的暂停(经动作端点交给 host 引擎执行)。 */\nexport function unpauseSession(sessionId: string): void {\n void postAction({ action: 'unpause', sessionId });\n}\n\n/** 订阅桥状态变化(卡片面板刷新用)。 */\nexport function subscribeBridge(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/** 通知按钮动作回传 host(立即续跑 / 暂停该会话 1 小时 / 解除暂停 / 清零统计)。 */\nasync function postAction(payload: { action: string; sessionId?: string }): Promise<void> {\n try {\n await fetch('/api/auto-continue-action', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n });\n } catch {\n /* host 不可达时静默 */\n }\n}\n\nfunction handleEvent(event: { type: string; notice?: BridgeNotice; stats?: DayStatsView; paused?: PausedSessionView[]; recoveryAttempts?: RecoveryAttempt[]; sessionPolicy?: SessionPolicy }): void {\n if (event.type === 'state') {\n const policy = event.sessionPolicy;\n state = {\n stats: event.stats ?? EMPTY_STATS,\n paused: event.paused ?? [],\n recoveryAttempts: event.recoveryAttempts ?? [],\n sessionPolicy: policy && typeof policy.modes === 'object' && policy.modes !== null && !Array.isArray(policy.modes) &&\n (policy.defaultMode === 'recover' || policy.defaultMode === 'loop') && typeof policy.paused === 'boolean' && typeof policy.writable === 'boolean'\n ? policy : undefined,\n };\n for (const listener of listeners) listener();\n } else if (event.type === 'notice' && event.notice !== undefined) {\n showNotification(event.notice);\n }\n}\n\n/** 浏览器通知: 展示 host 通知并挂动作按钮。 */\nfunction showNotification(notice: BridgeNotice): void {\n try {\n const N = (globalThis as { Notification?: unknown }).Notification as\n | (new (t: string, o: { body: string; actions?: { action: string; title: string }[] }) => unknown)\n | undefined;\n if (typeof N === 'undefined') return;\n const permission = (N as unknown as { permission?: string }).permission;\n const create = (): void => {\n const instance = new N(notice.title, {\n body: notice.body,\n ...(notice.actions.length > 0 ? { actions: notice.actions } : {}),\n });\n const target = instance as {\n onclick?: (() => void) | null;\n onaction?: ((event: { action: string }) => void) | null;\n };\n target.onclick = () => {\n try {\n (globalThis as { focus?: () => void }).focus?.();\n } catch {\n /* ignore */\n }\n };\n target.onaction = (event) => {\n if (notice.sessionId !== undefined) {\n void postAction({ action: event.action, sessionId: notice.sessionId });\n }\n };\n };\n if (permission === 'granted') {\n create();\n } else if (permission === 'default') {\n void (N as unknown as { requestPermission?: () => Promise<string> }).requestPermission?.()\n .then((result) => {\n if (result === 'granted') create();\n })\n .catch(() => {});\n }\n } catch {\n /* 通知失败不影响核心逻辑 */\n }\n}\n\n/**\n * 启动桥订阅(带断线重连), 返回停止函数。\n * 由 client apply 的 ctx.effect 持有。\n */\nexport function startBridge(): () => void {\n let stopped = false;\n let controller: AbortController | undefined;\n const disconnected = () => {\n state = { ...state, sessionPolicy: undefined };\n for (const listener of listeners) listener();\n };\n disconnected();\n\n const loop = async (): Promise<void> => {\n while (!stopped) {\n controller = new AbortController();\n try {\n const response = await fetch('/api/auto-continue-bridge', { signal: controller.signal });\n if (!response.ok || response.body === null) throw new Error(`bridge HTTP ${response.status}`);\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n if (done || stopped) break;\n buffer += decoder.decode(value, { stream: true });\n let idx = buffer.indexOf('\\n\\n');\n while (idx !== -1) {\n const chunk = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n for (const line of chunk.split('\\n')) {\n if (line.startsWith('data: ')) {\n try {\n handleEvent(JSON.parse(line.slice(6)) as Parameters<typeof handleEvent>[0]);\n } catch {\n /* 忽略坏帧 */\n }\n }\n }\n idx = buffer.indexOf('\\n\\n');\n }\n }\n } catch {\n /* 断线: 退避重连 */\n }\n if (!stopped) {\n disconnected();\n await new Promise((resolve) => setTimeout(resolve, 3000));\n }\n }\n };\n void loop();\n\n return () => {\n stopped = true;\n controller?.abort();\n disconnected();\n };\n}\n", "/**\n * Staged form model behind the plugin settings card — a self-contained\n * implementation of the plugin-card store pattern used by the DSH plugin\n * configuration section.\n *\n * A card stages what the user types and writes it only when they save. Each\n * settings write is a durable, revision-fenced document mutation, so staging\n * keeps what is on screen exactly what a save would store. A field shows its\n * effective value — the user layer over the composition layer over the schema\n * default — and whether the user layer carries it (presence, not value\n * equality, marks an override).\n */\nimport type { SettingsScope, SettingsScopeSnapshot, SnapshotStore } from './dsh-store-compat.ts';\n\n/** Current forms omit mode; legacy memory scopes still cannot persist settings. */\nexport function canWriteSettings(snapshot: SettingsScopeSnapshot<unknown>): boolean {\n return snapshot.status === 'ready' && snapshot.writable && (snapshot.mode === undefined || snapshot.mode === 'host');\n}\n\n/** The write one field's staged text performs when the card is saved. */\nexport type FieldWrite = { kind: 'set'; value: unknown } | { kind: 'clear' };\n\n/** How one field converts between its stored value and its draft text. */\nexport interface CardFieldSpec {\n /** Field name inside the namespace section. */\n field: string;\n /** Render a stored value as draft text; the empty string when the section carries none. */\n format: (value: unknown) => string;\n /**\n * The write this draft text stages, or undefined when the text is not a\n * value this field accepts — which blocks the save rather than discarding it.\n */\n parse: (text: string) => FieldWrite | undefined;\n}\n\n/** One field as the card's control renders it. */\nexport interface CardFieldState {\n /** Draft text the control renders. */\n text: string;\n /** Whether saving would leave a user-layer entry for this field. */\n overridden: boolean;\n /** Whether the draft is not a value this field accepts, which blocks saving. */\n invalid: boolean;\n}\n\n/** Form state every plugin card shares. */\nexport interface CardShell {\n /** False while the namespace is not served to this client; the card renders nothing. */\n available: boolean;\n /** Whether the Host document accepts writes. */\n writable: boolean;\n /** Whether the form holds edits that a save would write. */\n dirty: boolean;\n /** Whether any staged draft is invalid, which blocks the save. */\n invalid: boolean;\n /** Whether a save is crossing the wire. */\n saving: boolean;\n /** Whether the last save did not land as staged; cleared by the next edit or save. */\n failed: boolean;\n}\n\n/** The write actions the card's slot entry injects. */\nexport interface CardActions {\n /** Stage draft text for one field. */\n edit: (field: string, text: string) => void;\n /** Stage a clear, so saving lets the field re-inherit the composition layer. */\n resetField: (field: string) => void;\n /** Write every staged edit, then re-seed from what the Host accepted. */\n save: () => void;\n /** Drop every staged edit. */\n discard: () => void;\n}\n\n/** A whole-number field. An empty draft clears the field; a non-number or out-of-range draft blocks the save. */\nexport function numberField(field: string, min = 0): CardFieldSpec {\n return {\n field,\n format: (value) => (typeof value === 'number' ? String(value) : ''),\n parse: (text) => {\n const trimmed = text.trim();\n if (trimmed === '') return { kind: 'clear' };\n const parsed = Number(trimmed);\n if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < min) return undefined;\n return { kind: 'set', value: parsed };\n },\n };\n}\n\n/** A free-text field. An empty draft clears the field, so emptying the control and saving is the same gesture as resetting it. */\nexport function textField(field: string): CardFieldSpec {\n return {\n field,\n format: (value) => (typeof value === 'string' ? value : ''),\n parse: (text) => {\n const trimmed = text.trim();\n return trimmed === '' ? { kind: 'clear' } : { kind: 'set', value: trimmed };\n },\n };\n}\n\n/** A boolean field, edited through true/false draft text; an empty draft inherits. */\nexport function booleanField(field: string): CardFieldSpec {\n return {\n field,\n format: (value) => (typeof value === 'boolean' ? String(value) : ''),\n parse: (text) => {\n const trimmed = text.trim();\n if (trimmed === '') return { kind: 'clear' };\n if (trimmed === 'true') return { kind: 'set', value: true };\n if (trimmed === 'false') return { kind: 'set', value: false };\n return undefined;\n },\n };\n}\n\n/** One field's staged edit. */\ninterface StagedEdit {\n /** Draft text the control renders. */\n text: string;\n /** True when this edit clears the field whatever text it shows. */\n clear: boolean;\n}\n\n/**\n * Stages one card's edits over one settings namespace and writes them on save.\n *\n * The Host is the only authority on whether a value was accepted, so the\n * outcome is read back from the section rather than predicted here. A save\n * that did not land keeps its drafts, so the user can correct them instead of\n * retyping.\n */\nexport class CardForm<T> {\n private readonly specs: Map<string, CardFieldSpec>;\n private readonly staged = new Map<string, StagedEdit>();\n private readonly listeners = new Set<() => void>();\n private readonly unsubscribe: () => void;\n private saving = false;\n private failed = false;\n\n /**\n * @param scope - the bound settings scope for this card's namespace.\n * @param specs - the section fields this card edits.\n */\n constructor(\n private readonly scope: SettingsScope<T>,\n specs: CardFieldSpec[],\n ) {\n this.specs = new Map(specs.map((spec) => [spec.field, spec]));\n this.unsubscribe = this.scope.subscribe(() => this.publish());\n }\n\n /** Release this editor's listeners without disposing the provider's shared form. */\n dispose(): void {\n this.unsubscribe();\n this.listeners.clear();\n }\n\n /** Publish a projection of this form, rebuilt whenever the scope or a draft changes. */\n bind<S>(project: () => S, createStore: (init: S) => SnapshotStore<S>): SnapshotStore<S> {\n const store = createStore(project());\n this.listeners.add(() => store.set(project()));\n return store;\n }\n\n /** Read the card-level state: what the Host serves, and what a save would do. */\n shell(): CardShell {\n const snapshot = this.scope.getSnapshot();\n return {\n available: snapshot.status === 'ready',\n writable: canWriteSettings(snapshot),\n dirty: this.plan().length > 0,\n invalid: this.plan().some((item) => item.run === undefined),\n saving: this.saving,\n failed: this.failed,\n };\n }\n\n /** Read one field's state from the effective section and its staged draft. */\n field(field: string): CardFieldState {\n const spec = this.specOf(field);\n const staged = this.staged.get(field);\n if (staged === undefined) {\n return {\n text: spec.format(this.sectionValue(field)),\n overridden: this.stored(field),\n invalid: false,\n };\n }\n const write = staged.clear ? { kind: 'clear' as const } : spec.parse(staged.text);\n return {\n text: staged.text,\n overridden: write?.kind === 'set',\n invalid: write === undefined,\n };\n }\n\n /** The actions the card's slot registration injects. */\n actions(): CardActions {\n return {\n edit: (field, text) => this.stage(field, { text, clear: false }),\n resetField: (field) => {\n this.stage(field, { text: this.specOf(field).format(this.baseValue(field)), clear: true });\n },\n save: () => void this.save(),\n discard: () => {\n if (this.staged.size === 0 && !this.failed) return;\n this.staged.clear();\n this.failed = false;\n this.publish();\n },\n };\n }\n\n /**\n * Write every staged edit, then re-seed from what the Host accepted.\n * @returns true only when a non-empty save was accepted and read back.\n */\n async save(): Promise<boolean> {\n const plan = this.plan();\n const writes = plan.flatMap((item) => (item.run === undefined ? [] : [item.run]));\n const snapshot = this.scope.getSnapshot();\n if (plan.length === 0 || this.saving || writes.length !== plan.length || !canWriteSettings(snapshot)) return false;\n // Keep the staged edits this save writes. A field can be staged again\n // while a write is pending, so clear it only if that exact edit remains.\n const edits = plan.map(({ field, staged }) => ({ field, staged }));\n this.saving = true;\n this.failed = false;\n this.publish();\n let landed = true;\n try {\n for (const write of writes) {\n landed = (await write()) && landed;\n }\n } catch {\n landed = false;\n }\n if (landed) {\n for (const { field, staged } of edits) {\n if (this.staged.get(field) === staged) this.staged.delete(field);\n }\n }\n this.saving = false;\n this.failed = !landed;\n this.publish();\n return landed;\n }\n\n /**\n * Every staged edit a save would write. An entry whose draft is not a value\n * its field accepts carries no write: the form is still dirty, and the save\n * refuses rather than dropping the edit. A staged edit that matches the\n * effective section is not a write at all.\n */\n private plan(): { field: string; staged: StagedEdit; run: (() => Promise<boolean>) | undefined }[] {\n const plan: { field: string; staged: StagedEdit; run: (() => Promise<boolean>) | undefined }[] = [];\n for (const [field, staged] of this.staged) {\n const spec = this.specOf(field);\n if (staged.clear) {\n if (this.stored(field)) plan.push({ field, staged, run: () => this.clear(field) });\n continue;\n }\n if (staged.text === spec.format(this.sectionValue(field))) continue;\n const write = spec.parse(staged.text);\n if (write === undefined) plan.push({ field, staged, run: undefined });\n else if (write.kind === 'clear') plan.push({ field, staged, run: () => this.clear(field) });\n else plan.push({ field, staged, run: () => this.store(field, write.value) });\n }\n return plan;\n }\n\n private async clear(field: string): Promise<boolean> {\n const accepted = await this.scope.unset(field);\n return accepted !== false && !this.stored(field);\n }\n\n private async store(field: string, value: unknown): Promise<boolean> {\n const accepted = await this.scope.set(field, value);\n return accepted !== false && this.userLayer()?.[field] === value;\n }\n\n private stage(field: string, edit: StagedEdit): void {\n this.staged.set(field, edit);\n this.failed = false;\n this.publish();\n }\n\n private specOf(field: string): CardFieldSpec {\n const spec = this.specs.get(field);\n if (spec === undefined) throw new Error(`settings card has no field ${field}`);\n return spec;\n }\n\n private sectionValue(field: string): unknown {\n return (this.scope.getSnapshot().value as Record<string, unknown> | undefined)?.[field];\n }\n\n private baseValue(field: string): unknown {\n return (this.scope.getSnapshot().base as Record<string, unknown> | undefined)?.[field];\n }\n\n private userLayer(): Record<string, unknown> | undefined {\n return this.scope.getSnapshot().user as Record<string, unknown> | undefined;\n }\n\n private stored(field: string): boolean {\n const user = this.userLayer();\n return user !== undefined && Object.prototype.hasOwnProperty.call(user, field);\n }\n\n private publish(): void {\n for (const listener of this.listeners) listener();\n }\n}\n", "/**\n * Styles for the auto-continue settings card, injected at factory\n * materialization so the client module system's style bookkeeping (HMR) owns\n * them. Uses the DSH design tokens (`--dsw-alias-*`) so the card follows the\n * active theme.\n */\n\nconst css = `\n.dshAcComposer { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 6px; min-width: 0; min-height: 32px; max-width: 100%; font: inherit; }\n.dshAcComposerCore { display: inline-flex; align-items: center; gap: 6px; min-width: 0; max-width: 100%; }\n.dshAcComposerCore > span { min-width: 0; }\n.dshAcModeTrigger { display: inline-flex; align-items: center; gap: 3px; min-width: 0; max-width: 132px; height: 28px; margin-left: -1px; padding: 0 4px 0 7px; border: 0; border-radius: var(--dsw-radius-sm, 6px); background: none; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 13px; font-weight: 500; line-height: 20px; cursor: pointer; }\n.dshAcModeTrigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }\n.dshAcModeTrigger:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }\n.dshAcModeTrigger:disabled { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-tertiary)); cursor: default; }\n.dshAcModeTriggerLabel { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.dshAcModeChevron { display: inline-flex; flex: none; color: var(--dsw-alias-label-caption, var(--dsw-alias-label-tertiary)); transition: transform .12s ease; }\n.dshAcModeChevron > svg { display: block; width: 14px; height: 14px; }\n.dshAcModeChevronFallback { fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }\n.dshAcModeChevron[data-open=true] { transform: rotate(180deg); }\n.dshAcModeMenu { position: relative; display: inline-flex; align-items: center; gap: 3px; min-width: 0; max-width: 132px; height: 28px; margin-left: -1px; padding: 0 4px 0 7px; border-radius: var(--dsw-radius-sm, 6px); color: var(--dsw-alias-label-secondary); font-size: 13px; font-weight: 500; line-height: 20px; }\n.dshAcModeMenu:hover:not([data-disabled=true]) { color: var(--dsw-alias-label-primary); background: var(--dsw-alias-interactive-bg-hover); }\n.dshAcModeMenu[data-disabled=true] { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-tertiary)); }\n.dshAcComposerSelect { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; }\n.dshAcComposerSelect:disabled { cursor: default; }\n/* Settings-card select (default session mode); kept scoped so the composer's\n invisible overlay cannot stretch it over the whole app. */\n.dshAcCard .dshAcMode { min-height: 32px; max-width: 100%; padding: 4px 6px; border: 1px solid var(--dsh-ac-line); border-radius: 6px; background: var(--dsh-ac-bg); color: var(--dsh-ac-text); font: inherit; font-size: 12px; }\n.dshAcCard .dshAcMode:disabled { opacity: .5; }\n.dshAcCard .dshAcMode:focus-visible { outline: 2px solid var(--dsh-ac-text); outline-offset: 3px; }\n.dshAcComposerLabel { display: inline-flex; align-items: center; gap: 5px; flex: none; color: var(--dsw-alias-label-secondary); font-size: 12px; white-space: nowrap; }\n.dshAcComposerText { display: inline; }\n.dshAcComposerIcon { display: inline-flex; flex: none; color: var(--dsw-alias-label-secondary); }\n.dshAcComposerIcon > svg { display: block; width: 14px; height: 14px; }\n.dshAcComposerIconFallback { fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }\n.dshAcSwitchTarget { display: inline-flex; align-items: center; flex: none; min-height: 32px; }\n.dshAcSwitchTarget > button { position: relative; }\n.dshAcSwitchTarget > button::before { content: ''; position: absolute; inset: -6px -3px; }\n.dshAcComposerError { color: var(--dsw-alias-state-error-primary, var(--dsw-alias-label-secondary)); font-size: 12px; max-width: 160px; }\n.dshAcComposerError:empty { display: none; }\n.dshAcToastIcon { display: block; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }\n.dshAcSwitch { position: relative; box-sizing: border-box; flex: none; width: 36px; height: 20px; padding: 2px; border: 0; border-radius: 999px; background: var(--dsw-alias-border-l3); cursor: pointer; }\n.dshAcSwitch[aria-checked='true'] { background: var(--dsw-alias-brand-primary); }\n.dshAcSwitch > span { display: block; width: 16px; height: 16px; border-radius: 50%; background: var(--dsw-alias-label-primary-foreground); }\n.dshAcSwitch[aria-checked='true'] > span { transform: translateX(16px); }\n.dshAcSwitch[aria-checked='false'] > span { background: var(--dsw-alias-switch-thumb, var(--dsw-alias-label-primary-foreground)); }\n.dshAcSwitch:disabled { opacity: .5; cursor: default; }\n.dshAcSwitch:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }\n.dshAcCard {\n --dsh-ac-bg: var(--dsw-alias-bg-base, var(--dsw-alias-bg-layer-2));\n --dsh-ac-line: var(--dsw-alias-border-l2);\n --dsh-ac-text: var(--dsw-alias-label-primary);\n --dsh-ac-muted: var(--dsw-alias-label-tertiary);\n container: auto-continue-settings / inline-size;\n color: var(--dsh-ac-text);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n list-style: none;\n padding: 0;\n}\n.dshAcCard *, .dshAcCard *::before, .dshAcCard *::after { box-sizing: border-box; }\n.dshAcCard :is(h2,h3,p) { margin: 0; }\n.dshAcCard :is(button,input,textarea) { font: inherit; }\n.dshAcCard button { cursor: pointer; }\n.dshAcCard button:disabled { opacity: .4; cursor: default; }\n.dshAcCard :is(a,button,input,textarea):focus-visible { outline: 2px solid var(--dsh-ac-text); outline-offset: 3px; }\n.dshAcInvite { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 10px; margin: 0 0 18px; color: var(--dsh-ac-muted); font-size: 12px; line-height: 1.6; }\n.dshAcInviteStar { color: #e9be6d; font-size: 13px; line-height: 1; }\n.dshAcRepoLink { display: inline-flex; align-items: center; gap: 5px; color: var(--dsh-ac-text); text-decoration: none; }\n.dshAcRepoLink:hover { text-decoration: underline; }\n.dshAcRepoLink > svg:first-child { width: 14px; height: 14px; fill: currentColor; }\n.dshAcRepoLink > svg.dshAcExternal { width: 11px; height: 11px; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }\n.dshAcNativeFields { display: flex; flex-direction: column; min-width: 0; }\n.dshAcNativeField { display: flex; flex-direction: column; gap: 6px; min-width: 0; padding: 12px 0; }\n.dshAcNativeHead { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-width: 0; }\n.dshAcNativeLabel { color: var(--dsh-ac-text); font-size: 13px; font-weight: 500; line-height: 19.5px; }\n.dshAcNativeHint { color: var(--dsh-ac-muted); font-size: 12px; line-height: 18px; }\n.dshAcNativeToggleRow { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-width: 0; }\n.dshAcNativeActions { display: inline-flex; align-items: center; flex: none; gap: 10px; }\n.dshAcNativeReset { padding: 0; border: 0; background: none; color: var(--dsh-ac-muted); font-size: 11px; white-space: nowrap; }\n.dshAcNativeReset:hover:not(:disabled) { color: var(--dsh-ac-text); text-decoration: underline; }\n.dshAcNativeSegment { display: block; min-width: 0; }\n.dshAcNativeSegment[data-disabled=true] { opacity: .5; pointer-events: none; }\n.dshAcNativeTextarea { box-sizing: border-box; width: 100%; min-height: 66px; resize: vertical; padding: 8px 12px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 12px; background: var(--dsw-alias-bg-layer-2, #353638); color: var(--dsh-ac-text); font: inherit; font-size: 13px; line-height: 19.5px; }\n.dshAcNativeTextarea::placeholder { color: var(--dsh-ac-muted); opacity: .7; }\n.dshAcNativeTextarea[aria-invalid=true] { border-color: var(--dsw-alias-state-error-primary); }\n.dshAcReadOnly { padding: 10px 0; color: var(--dsh-ac-muted); }\n.dshAcLayout { display: grid; grid-template-columns: 164px minmax(0, 1fr); min-height: 462px; }\n.dshAcNav { display: flex; flex-direction: column; gap: 4px; padding: 16px 18px 16px 0; position: sticky; top: 16px; align-self: start; }\n.dshAcNav > button { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 37px; padding: 8px 11px; border: 0; border-radius: 6px; text-align: left; background: none; color: var(--dsw-alias-label-secondary); }\n.dshAcNav > button:hover, .dshAcNav > button[aria-selected=true] { color: var(--dsh-ac-text); background: var(--dsw-alias-interactive-bg-hover); }\n.dshAcNav > button[aria-selected=true] { font-weight: 600; }\n.dshAcInvalidMark { color: var(--dsw-alias-state-error-primary); font-weight: 600; }\n.dshAcCategory { min-width: 0; padding: 20px 0 16px 26px; border-left: 1px solid var(--dsh-ac-line); }\n.dshAcCategoryHeading { padding-bottom: 14px; }\n.dshAcCategoryHeading h3 { font-size: 15px; font-weight: 620; }\n.dshAcCategoryHeading p { color: var(--dsh-ac-muted); font-size: 12px; margin-top: 3px; }\n.dshAcField { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 10px 24px; padding: 18px 0; border-bottom: 1px solid var(--dsh-ac-line); }\n.dshAcField:last-child { border-bottom: 0; }\n.dshAcFieldCopy { min-width: 0; }\n.dshAcLabel { display: block; font-size: 14px; font-weight: 480; color: var(--dsh-ac-text); }\n.dshAcHint { color: var(--dsh-ac-muted); font-size: 12px; line-height: 1.6; }\n.dshAcFieldCopy p { margin-top: 4px; }\n.dshAcFieldControl { display: flex; align-items: center; justify-content: flex-end; gap: 14px; }\n.dshAcReset { padding: 0; border: 0; background: none; color: var(--dsh-ac-muted); font-size: 11px !important; white-space: nowrap; }\n.dshAcReset:hover:not(:disabled) { color: var(--dsh-ac-text); text-decoration: underline; }\n.dshAcInput { border: 1px solid var(--dsh-ac-line); border-radius: 6px; background: var(--dsh-ac-bg); color: var(--dsh-ac-text); padding: 8px 11px; }\n.dshAcInput::placeholder { color: var(--dsh-ac-muted); opacity: .7; }\n.dshAcInput[aria-invalid=true] { border-color: var(--dsw-alias-state-error-primary); }\n.dshAcNumber { width: 132px; min-width: 0; font-variant-numeric: tabular-nums; }\n.dshAcFieldText { display: block; }\n.dshAcFieldText .dshAcFieldControl { margin-top: 10px; flex-direction: column-reverse; align-items: flex-end; gap: 6px; }\n.dshAcTextArea { display: block; width: 100%; min-height: 66px; resize: vertical; line-height: 1.6; }\n.dshAcInvalid, .dshAcFailed { color: var(--dsw-alias-state-error-primary); font-size: 12px; }\n.dshAcFooter { display: flex; justify-content: space-between; align-items: center; gap: 14px; margin-top: 24px; padding: 13px 0; border-top: 1px solid var(--dsh-ac-line); background: var(--dsh-ac-bg); }\n.dshAcFooter[data-dirty=true] { position: sticky; z-index: 8; bottom: 0; }\n.dshAcFooter > div { display: flex; align-items: center; gap: 8px; }\n.dshAcDiscard, .dshAcSave { padding: 7px 13px; border: 1px solid var(--dsh-ac-line); border-radius: 6px; font-size: 12px !important; background: var(--dsh-ac-bg); color: var(--dsh-ac-text); white-space: nowrap; }\n.dshAcSave { background: var(--dsh-ac-text); color: var(--dsh-ac-bg); border-color: var(--dsh-ac-text); }\n.dshAcDiscard:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }\n.dshAcSave:hover:not(:disabled) { opacity: .85; }\n.dshAcPanel { padding: 20px 0; border-top: 1px solid var(--dsh-ac-line); }\n.dshAcPanelHead { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 10px; }\n.dshAcPanelTitle { font-weight: 550; }\n.dshAcStats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin: 18px 0; }\n.dshAcStats dt { font-size: 11px; color: var(--dsh-ac-muted); }\n.dshAcStats dd { margin: 4px 0 0; font-size: 19px; font-weight: 550; font-variant-numeric: tabular-nums; }\n.dshAcCodes { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }\n.dshAcCode { font: 11px ui-monospace, SFMono-Regular, monospace; border: 1px solid var(--dsh-ac-line); border-radius: 4px; padding: 3px 6px; }\n.dshAcPauseList { list-style: none; margin: 0; padding: 0; }\n.dshAcPauseList li { display: flex; align-items: center; gap: 12px; padding: 10px 0; }\n.dshAcPauseId { flex: 1; font: 12px ui-monospace, SFMono-Regular, monospace; }\n.dshAcRecovery { display: grid; gap: 4px; min-width: 0; overflow-wrap: anywhere; }\n@container auto-continue-settings (max-width: 760px) {\n .dshAcLayout { grid-template-columns: 136px minmax(0, 1fr); }\n .dshAcCategory { padding-left: 20px; }\n .dshAcFieldControl { flex-direction: column-reverse; align-items: flex-end; gap: 6px; }\n}\n@container auto-continue-settings (max-width: 560px) {\n .dshAcLayout { display: block; min-height: 0; }\n .dshAcNav { flex-direction: row; overflow-x: auto; position: static; padding: 12px 0; border-bottom: 1px solid var(--dsh-ac-line); }\n .dshAcNav > button { flex: none; font-size: 12px; min-height: 34px; padding: 7px 10px; }\n .dshAcCategory { border-left: 0; padding: 20px 0; }\n .dshAcField { gap: 8px 14px; }\n .dshAcLabel { font-size: 13px; }\n .dshAcNumber { width: 98px; }\n .dshAcFooter { align-items: flex-start; flex-direction: column; gap: 10px; }\n .dshAcFooter > div { width: 100%; justify-content: flex-end; }\n}\n/* Match the native picker breakpoints when the composer provides a query container. */\n@container (width <= 640px) {\n .dshAcComposerCore { gap: 5px; }\n .dshAcModeTrigger, .dshAcModeMenu { max-width: 104px; padding: 0 3px 0 6px; }\n}\n@container (width <= 460px) {\n .dshAcComposerText { display: none; }\n .dshAcModeTrigger, .dshAcModeMenu { max-width: 28px; padding: 0 2px; }\n .dshAcModeTriggerLabel { display: none; }\n}\n/* DS-Bot can remove the query container with display: contents. */\n@media (max-width: 640px) {\n .dshAcComposer { flex-direction: column; align-items: flex-start; width: min-content; }\n .dshAcComposer > .dshAcComposerLabel { white-space: normal; }\n .dshAcComposerCore { gap: 5px; }\n .dshAcComposerText, .dshAcModeTriggerLabel { display: none; }\n .dshAcModeTrigger, .dshAcModeMenu { max-width: 28px; padding: 0 2px; }\n}\n\n`;\n\n/** Inject the stylesheet once; a no-op outside a browser environment. */\nexport function injectStyles(): void {\n if (typeof document === 'undefined') return;\n if (document.querySelector('style[data-plugin-css=\"auto-continue/card\"]') !== null) return;\n const tag = document.createElement('style');\n tag.dataset.plugin = 'dsh-client-auto-continue';\n tag.dataset.pluginCss = 'auto-continue/card';\n tag.textContent = css;\n document.head.appendChild(tag);\n}\n", "import { en, zh, type SettingsCardKey } from './locales.ts';\nimport { resolveLocale } from '../shared/core.ts';\n\ntype Permission = NotificationPermission | 'unsupported' | 'failed';\nexport type SettingsNotice = 'enabled' | 'disabled' | 'saved';\nlet pendingPermission: Promise<Permission> | undefined;\n\n/** Called directly by Save, before a network await can consume user activation. */\nexport function prepareSettingsNotification(enabled: boolean): Promise<Permission> {\n try {\n if (typeof Notification === 'undefined') return Promise.resolve('unsupported');\n if (!enabled || Notification.permission !== 'default') return Promise.resolve(Notification.permission);\n if (!pendingPermission) {\n pendingPermission = Notification.requestPermission()\n .catch((): Permission => 'failed')\n .finally(() => { pendingPermission = undefined; });\n }\n return pendingPermission;\n } catch {\n return Promise.resolve('failed');\n }\n}\n\n/** The save is already committed. Notification failures must never undo it. */\nexport function showSettingsNotification(notice: SettingsNotice, locale: string, permission: Permission): SettingsCardKey {\n const message: SettingsCardKey = `notification.${notice}`;\n if (permission !== 'granted') {\n // Turning alerts off must not ask for permission just to confirm the change.\n if (notice === 'disabled') return message;\n return permission === 'unsupported' ? 'notification.unsupported'\n : permission === 'failed' ? 'notification.failed' : 'notification.blocked';\n }\n try {\n const copy = resolveLocale(locale) === 'zh' ? zh : en;\n const notification = new Notification(copy['notification.title'], { body: copy[message] });\n notification.onclick = () => {\n try { globalThis.focus?.(); } catch { /* Focusing is best effort. */ }\n };\n return message;\n } catch {\n return notice === 'disabled' ? message : 'notification.failed';\n }\n}\n", "import { useEffect, useState } from 'react';\nimport type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots';\nimport type { SnapshotStore } from './dsh-store-compat.ts';\nimport { sessionMode, type SessionMode, type SessionPolicy } from '../shared/core.ts';\nimport { NativeSwitch } from './native-switch.tsx';\nimport { ModeMenu, type ModeMenuOption } from './mode-menu.tsx';\nimport { AutoContinueIcon } from './auto-continue-icon.tsx';\nimport { NativeToast, WarningIcon, hasNativeToast } from './native-toast.tsx';\n\nexport interface ComposerToggleState {\n visible: boolean;\n policy: SessionPolicy | undefined;\n writable: boolean;\n saving: ReadonlySet<string>;\n failed: ReadonlySet<string>;\n}\n\nconst HOST_UNAVAILABLE_DELAY_MS = 3000;\n\nfunction HostUnavailableToast({ text }: { text: string }) {\n const [visible, setVisible] = useState(false);\n useEffect(() => {\n const timer = setTimeout(() => setVisible(true), HOST_UNAVAILABLE_DELAY_MS);\n return () => clearTimeout(timer);\n }, []);\n if (!hasNativeToast || !visible) return null;\n const Toast = NativeToast!;\n return <Toast text={text} icon={<WarningIcon />} onDone={() => setVisible(false)} />;\n}\n\nfunction SaveFailureToast({ text }: { text: string }) {\n const [visible, setVisible] = useState(true);\n if (!hasNativeToast || !visible) return null;\n const Toast = NativeToast!;\n return <Toast text={text} icon={<WarningIcon />} onDone={() => setVisible(false)} />;\n}\n\nexport interface ComposerToggleFace {\n hooks: { autoContinueComposer: SnapshotStore<ComposerToggleState> };\n sessionId: string;\n setMode: (mode: SessionMode) => void;\n}\n\nexport function AutoContinueComposerToggle(props: PropsLocale<'auto-continue'> & InjectFace<ComposerToggleFace>) {\n const state = props.useAutoContinueComposer((snapshot) => snapshot);\n if (!state.visible || !props.sessionId) return null;\n const failed = state.failed.has(props.sessionId);\n const saving = state.saving.has(props.sessionId);\n const policy = state.policy;\n const mode = sessionMode(policy?.modes ?? {}, props.sessionId);\n const disabled = !policy || !state.writable || saving;\n const title = props.t(!policy ? 'composer.unavailable' : !state.writable ? 'chrome.readOnly' : saving ? 'composer.saving' : 'composer.scope');\n const modeName = props.t(`composer.${mode}`);\n const defaultName = policy\n ? `${props.t('composer.default')} (${props.t(`composer.${policy.defaultMode}`)})`\n : props.t('composer.default');\n const fullModeLabel = mode === 'default' ? defaultName : modeName;\n const modeTitle = `${props.t('composer.mode')}: ${fullModeLabel}`;\n const options: readonly ModeMenuOption[] = [\n { id: 'default', label: defaultName },\n { id: 'off', label: props.t('composer.off') },\n { id: 'recover', label: props.t('composer.recover') },\n { id: 'loop', label: props.t('composer.loop') },\n ];\n return (\n <div className=\"dshAcComposer\" title={title} aria-busy={saving || undefined}>\n <span className=\"dshAcComposerCore\">\n <span className=\"dshAcComposerLabel\">\n <span className=\"dshAcComposerIcon\" aria-hidden=\"true\"><AutoContinueIcon /></span>\n <span className=\"dshAcComposerText\">{props.t('composer.label')}</span>\n </span>\n <span className=\"dshAcSwitchTarget\">\n <NativeSwitch checked={!!policy && mode !== 'off'} onChange={enabled => props.setMode(enabled ? 'default' : 'off')}\n disabled={disabled} label={props.t('composer.label')} title={title} />\n </span>\n <ModeMenu mode={mode} options={options} label={modeName}\n ariaLabel={modeTitle} selectLabel={props.t('composer.mode')} title={modeTitle}\n disabled={disabled} onChange={props.setMode} />\n </span>\n {policy?.paused && <span className=\"dshAcComposerLabel\">{props.t('composer.paused')}</span>}\n {!policy && hasNativeToast && <HostUnavailableToast text={props.t('composer.unavailable')} />}\n {failed && hasNativeToast && <SaveFailureToast text={props.t('composer.saveFailed')} />}\n {failed && !hasNativeToast && <span className=\"dshAcComposerError\" role=\"status\">{props.t('composer.saveFailed')}</span>}\n </div>\n );\n}\n", "/**\n * Composer mode menu.\n *\n * Uses the host's own `Menu` and chevron primitives whenever the running DSH\n * exposes them, so the control looks and behaves like the composer's other\n * dropdowns (workspace permission, model picker). Legacy hosts, and the unit\n * tests' minimal module fixture, fall back to a native `<select>` over the\n * same compact label.\n */\nimport { useEffect, useState, type ComponentType, type ReactNode } from 'react';\nimport { isSessionMode, type SessionMode } from '../shared/core.ts';\n\nexport interface ModeMenuOption {\n id: SessionMode;\n label: string;\n}\n\ninterface MenuProps {\n open: boolean;\n anchor: ReactNode;\n items: readonly ModeMenuOption[];\n selectedId?: string;\n onSelect?: (id: string) => void;\n onClose?: () => void;\n side?: 'top' | 'bottom';\n portal?: boolean;\n}\n\ninterface ChevronProps {\n className?: string;\n}\n\nconst primitives = (() => {\n try {\n return require('@deepseek-ai/dsh-client-ui-primitives') as {\n Menu?: ComponentType<MenuProps>;\n IconChevronDownOutlineRegular?: ComponentType<ChevronProps>;\n };\n } catch {\n return {};\n }\n})();\n\nconst HostMenu = primitives.Menu;\nconst HostChevron = primitives.IconChevronDownOutlineRegular;\n\nfunction ChevronDown() {\n if (HostChevron) return <HostChevron />;\n return (\n <svg className=\"dshAcModeChevronFallback\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"m4.5 6.25 3.5 3.5 3.5-3.5\" />\n </svg>\n );\n}\n\nexport interface ModeMenuProps {\n mode: SessionMode;\n options: readonly ModeMenuOption[];\n /** Short label shown on the trigger, e.g. 跟随默认. */\n label: string;\n /** Accessible name including the resolved mode, e.g. 自动继续模式: 跟随默认 (仅故障恢复). */\n ariaLabel: string;\n /** Plain menu name used by the legacy select fallback. */\n selectLabel: string;\n title: string;\n disabled: boolean;\n onChange: (mode: SessionMode) => void;\n}\n\nexport function ModeMenu(props: ModeMenuProps) {\n const [open, setOpen] = useState(false);\n const expanded = open && !props.disabled;\n\n useEffect(() => {\n if (props.disabled) setOpen(false);\n }, [props.disabled]);\n\n const choose = (id: string) => {\n setOpen(false);\n if (isSessionMode(id) && id !== props.mode) props.onChange(id);\n };\n\n if (HostMenu) {\n return (\n <HostMenu open={expanded} side=\"top\" portal\n items={props.options} selectedId={props.mode}\n onSelect={choose} onClose={() => setOpen(false)}\n anchor={\n <button type=\"button\" className=\"dshAcModeTrigger\" disabled={props.disabled}\n aria-label={props.ariaLabel} aria-haspopup=\"menu\" aria-expanded={expanded}\n title={props.title} onClick={() => setOpen(value => !value)}>\n <span className=\"dshAcModeTriggerLabel\">{props.label}</span>\n <span className=\"dshAcModeChevron\" data-open={expanded} aria-hidden=\"true\"><ChevronDown /></span>\n </button>\n } />\n );\n }\n\n return (\n <span className=\"dshAcModeMenu\" data-disabled={props.disabled} title={props.title}>\n <span className=\"dshAcModeTriggerLabel\">{props.label}</span>\n <span className=\"dshAcModeChevron\" aria-hidden=\"true\"><ChevronDown /></span>\n <select className=\"dshAcComposerSelect\" aria-label={props.selectLabel} disabled={props.disabled}\n value={props.mode}\n onChange={event => { if (isSessionMode(event.target.value)) props.onChange(event.target.value); }}>\n {props.options.map(option => <option key={option.id} value={option.id}>{option.label}</option>)}\n </select>\n </span>\n );\n}\n", "/**\n * Auto-continue glyph.\n *\n * Prefers the host's own icon so the composer label matches the surrounding\n * DSH chrome; older hosts without the primitives module get an equivalent\n * inline stroke icon. The icon stays visible when the label text is hidden at\n * narrow widths.\n */\nimport type { ComponentType } from 'react';\n\ninterface IconProps {\n className?: string;\n}\n\nconst primitives = (() => {\n try {\n return require('@deepseek-ai/dsh-client-ui-primitives') as {\n IconRefreshOutlineRegular?: ComponentType<IconProps>;\n };\n } catch {\n return {};\n }\n})();\n\nconst HostRefresh = primitives.IconRefreshOutlineRegular;\n\nexport function AutoContinueIcon() {\n if (HostRefresh) return <HostRefresh />;\n return (\n <svg className=\"dshAcComposerIconFallback\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M13.25 8a5.25 5.25 0 1 1-1.54-3.71\" />\n <path d=\"M13.25 3.1v3.3h-3.3\" />\n </svg>\n );\n}\n", "/**\n * DSH toast bridge.\n *\n * The composer reports a failed session-mode save with the host's own toast\n * instead of inline red text that shifts the input row. Hosts without the\n * primitive (older DSH, or the unit-test fixture) keep the inline fallback.\n */\nimport type { ComponentType, ReactNode } from 'react';\n\nexport interface ToastProps {\n text: string;\n icon?: ReactNode;\n tone?: 'success';\n onDone?: () => void;\n}\n\ninterface IconProps {\n className?: string;\n}\n\nconst primitives = (() => {\n try {\n return require('@deepseek-ai/dsh-client-ui-primitives') as {\n Toast?: ComponentType<ToastProps>;\n IconWarningOutlineRegular?: ComponentType<IconProps>;\n };\n } catch {\n return {};\n }\n})();\n\nexport const NativeToast = primitives.Toast;\nexport const hasNativeToast = typeof NativeToast === 'function';\n\nexport function WarningIcon() {\n const Icon = primitives.IconWarningOutlineRegular;\n if (Icon) return <Icon />;\n return (\n <svg className=\"dshAcToastIcon\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M8 2.3 14.3 13H1.7L8 2.3Z\" />\n <path d=\"M8 6.2v3.1M8 11.8v.1\" />\n </svg>\n );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,SAAS,cAAc,QAAqC;AACjE,SAAO,OAAO,WAAW,YAA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AAI,MAAM;AAAA,MACR;AAAA,QACE,MAAM;AAAA,QACN,KAAK;AAAA,QACL,QAAQ;AAAA,QACR,QAAQ,MAAM,WAAW,OAAO;AAAA,MAClC;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,MAAM;AAAA,IAAO;AAAA,IAAyB,MACxC,IAAI,MAAM;AAAA,MACR;AAAA,QACE,MAAM;AAAA,QACN,KAAK;AAAA,QACL,QAAQ;AAAA,QACR,QAAQ,MAAM,WAAW,OAAO;AAAA,MAClC;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;",
6
- "names": ["import_jsx_runtime", "state", "import_react", "import_react", "import_jsx_runtime", "import_jsx_runtime", "primitives", "import_jsx_runtime", "primitives", "import_jsx_runtime", "state"]
4
+ "sourcesContent": ["/**\n * Auto-continue plugin, browser half (thin shell).\n *\n * Since 0.8.0 the auto-continue ENGINE runs inside the host process (single\n * instance — see src/host/engine.ts), so this half only:\n * - registers the `auto-continue` settings card in the available plugin UI,\n * - adds a per-session composer switch and mode menu backed by host settings,\n * - subscribes to the host status bridge (SSE) and shows browser\n * notifications with action buttons (Resume now / Pause 1h) via the bridge\n * action endpoint,\n * - feeds the card's stats / paused-sessions panels from the bridge state.\n */\nimport type { Context as ClientContext } from '@deepseek-ai/cordis';\n// Type-only: the slot service is declared by the renderer in newer DSH SDKs.\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client';\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client';\n// Type-only: pulls the settings-surface SlotMap merge and ctx.settingsScope.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client';\n// Type-only: pulls the `settings.plugin.item` SlotMap merge.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings-plugins/client';\nimport { resolveLocale, type AutoContinueSettings } from '../shared/core.ts';\nimport { en, ru, zh, type SettingsCardKey } from './locales.ts';\nimport {\n AutoContinueSettingsCard,\n AutoContinueSettingsCardController,\n AutoContinueSettingsPage,\n} from './settings-card.tsx';\nimport { startBridge } from './bridge.ts';\nimport { AutoContinueComposerToggle } from './composer-toggle.tsx';\nimport type { SettingsScope } from './dsh-store-compat.ts';\nimport { canWriteSettings } from './settings-form.ts';\n\n/** Dictionary namespace owned by this plugin. */\nconst NS = 'auto-continue';\n\n/** Settings namespace the settings card edits (the host engine reads it). */\nconst SETTINGS_NS = 'auto-continue';\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface SlotMap {\n /** Official compact composer tools; never occupy the resident single slot. */\n 'conversation.input.left': {\n kind: 'list';\n scope: 'session';\n };\n /** DSH 0.1.7's bundle configuration seat; only the owner props we consume. */\n 'plugins.bundle.config': {\n kind: 'keyed';\n scope: 'root';\n owner: { readonly view: 'summary' | 'page' };\n };\n }\n interface LocaleNamespaceMap {\n /** auto-continue settings-card copy. */\n 'auto-continue': SettingsCardKey;\n }\n}\n\n/** Shared subset of DSH 0.1.7's provider, without a new runtime dependency. */\ntype ConfigFormsContext = ClientContext & {\n configForms: { get<T>(entryId: string): SettingsScope<T> };\n};\n\n/** Settings services are injected separately: neither exists in every DSH cohort. */\nexport const inject = ['slots', 'locale'];\n\n// 浏览器侧辅助(设置卡片用): 桥状态读取与暂停解除。\nexport {\n pausedSessions,\n readTodayStats,\n readRecoveryAttempts,\n resetTodayStats,\n unpauseSession,\n} from './bridge.ts';\n\n/**\n * Plugin body: settings card + host status bridge (notifications, stats,\n * paused sessions).\n * @param ctx - client root context.\n */\nexport function apply(ctx: ClientContext): void {\n // The base package types `register()` dictionaries as the built-in `zh`/`en`\n // pair only; further languages (here `ru`, added by a locale plugin at\n // runtime) register one locale at a time, exactly as `addLanguage` allows.\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'auto-continue: dictionaries');\n ctx.effect(() => ctx.locale.register(NS, 'ru', ru), 'auto-continue: russian dictionary');\n ctx.effect(() => startBridge(), 'auto-continue: host bridge');\n\n // Cordis waits for ALL top-level dependencies. Requiring settingsScope here\n // would leave DSH 0.1.7 pending forever; requiring configForms breaks older\n // hosts. Separate child fibers also follow late providers and their teardown.\n ctx.inject(['settingsScope'], (settingsCtx) => {\n mountSettings(settingsCtx, settingsCtx.settingsScope.bind<AutoContinueSettings>({ namespace: SETTINGS_NS }));\n });\n ctx.inject(['configForms'], (settingsCtx) => {\n const forms = (settingsCtx as ConfigFormsContext).configForms;\n mountSettings(settingsCtx, forms.get<AutoContinueSettings>(SETTINGS_NS));\n });\n}\n\n/** Attach this consumer's subscriptions and card to the provider's lifecycle. */\nfunction mountSettings(ctx: ClientContext, scope: SettingsScope<AutoContinueSettings>): void {\n /**\n * Mirror the browser locale into the host config, with a hard per-page budget.\n *\n * The write is only needed while the stored value disagrees with the page, so\n * every notification re-checks the snapshot — but two unbounded writers hid in\n * that check, and both of them hammer `settings.yaml` until the host settings\n * write queue backs up (observed: ~1 write / 400 ms when a completed write does\n * not fold back before the next document tick, and a two-page ping-pong when\n * two pages with different UI languages keep overwriting each other).\n *\n * So: keep the subscription and the `locale/change` hook (a scope that is not\n * `ready` yet still mirrors once it is, and a real language switch still wins),\n * but cap this page at {@link MAX_MIRROR_ATTEMPTS} writes per active locale.\n *\n * The budget must NOT be reset by a matching snapshot. In the real\n * `SettingsScopeController`, a successful `set()` folds the mutation response\n * into the WRITING page's own mirror (`mirror.acceptView` -> scope `derive()` ->\n * subscriber), so under the two-page ping-pong each page first sees its own\n * accepted value — matching its active locale — and would hand itself a fresh\n * budget before the other page writes back. That is an unbounded loop again\n * (probed: 400+ host writes). Reset only when the browser's active locale\n * genuinely changes; a matching snapshot then simply needs no write.\n */\n const MAX_MIRROR_ATTEMPTS = 3;\n let mirroredLocale: string | undefined;\n let mirrorAttempts = 0;\n const syncLocale = (): void => {\n const active = ctx.locale.getLocale().active;\n const target = resolveLocale(active);\n const snapshot = scope.getSnapshot();\n if (!canWriteSettings(snapshot)) return;\n // A genuine language switch is the only thing that earns a fresh budget: the\n // attempt count must survive matching snapshots, because the writing page's\n // own acknowledgement arrives as a match (see above). Tracking `mirroredLocale`\n // on every pass is what lets a later real switch be recognised.\n if (mirroredLocale !== active) {\n mirroredLocale = active;\n mirrorAttempts = 0;\n }\n // Converged: nothing to write.\n if (snapshot.value?.locale === target) return;\n if (mirrorAttempts >= MAX_MIRROR_ATTEMPTS) return;\n mirrorAttempts += 1;\n void scope.set('locale', target);\n };\n ctx.effect(() => scope.subscribe(syncLocale), 'auto-continue: locale settings sync');\n ctx.on('locale/change', syncLocale);\n syncLocale();\n\n const controller = new AutoContinueSettingsCardController(scope, () => ctx.locale.getLocale().active);\n ctx.effect(() => () => controller.dispose(), 'auto-continue: settings form');\n\n ctx.slots.inject('conversation.input.left', () =>\n ctx.slots.register(\n {\n name: 'conversation.input.left',\n id: 'auto-continue',\n locale: NS,\n inject: (sessionId) => controller.injectComposer(sessionId),\n },\n AutoContinueComposerToggle,\n ),\n );\n\n // Slot injection waits for the matching UI declaration. Keep the old\n // settings card and the new bundle page independent of service migration.\n ctx.slots.inject('settings.plugin.item', () =>\n ctx.slots.register(\n {\n name: 'settings.plugin.item',\n key: SETTINGS_NS,\n locale: NS,\n inject: () => controller.inject(),\n },\n AutoContinueSettingsCard,\n ),\n );\n ctx.slots.inject('plugins.bundle.config', () =>\n ctx.slots.register(\n {\n name: 'plugins.bundle.config',\n key: 'dsh-client-auto-continue',\n locale: NS,\n inject: () => controller.inject(),\n },\n AutoContinueSettingsPage,\n ),\n );\n}\n", "/** 共享核心: 平台无关的纯逻辑与类型。\n *\n * 被 host 引擎(src/host/engine.ts)与浏览器半侧共用: 配置解析、错误分类、\n * 模板填充、自适应退避、幂等护栏的工具结果提取、循环守卫的会话状态机,\n * 以及回显识别。引擎迁入 host 后(0.8.0), 浏览器半侧只 re-export 本模块。\n */\nimport type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';\n\nexport const AUTO_CONTINUE_SOURCE_KIND = 'plugin:dsh-client-auto-continue';\n\ndeclare module '@deepseek-ai/dsh-llm' {\n interface MessageSourceMap {\n 'plugin:dsh-client-auto-continue': { kind: typeof AUTO_CONTINUE_SOURCE_KIND };\n }\n}\n\n/** Supported UI/config locales; missing and unsupported values use English. */\nexport type AutoContinueLocale = 'en' | 'zh' | 'ru';\n\nexport function resolveLocale(locale: unknown): AutoContinueLocale {\n if (typeof locale !== 'string') return 'en';\n if (/^zh(?:-|$)/i.test(locale)) return 'zh';\n if (/^ru(?:-|$)/i.test(locale)) return 'ru';\n return 'en';\n}\n\nexport type SessionMode = 'default' | 'off' | 'recover' | 'loop';\n\nexport interface SessionPolicy {\n modes: Record<string, SessionMode>;\n /** Modes a child inherits from its main conversation, keyed by child id. */\n inheritedModes?: Record<string, SessionMode>;\n defaultMode: 'recover' | 'loop';\n paused: boolean;\n writable: boolean;\n}\n\nexport const isSessionMode = (value: unknown): value is SessionMode =>\n value === 'default' || value === 'off' || value === 'recover' || value === 'loop';\n\nexport function sessionMode(modes: Record<string, SessionMode>, sessionId: string): SessionMode {\n return Object.prototype.hasOwnProperty.call(modes, sessionId) && isSessionMode(modes[sessionId]) ? modes[sessionId]! : 'default';\n}\n\n/** Locale-owned defaults for the user-editable text fields. */\nexport const LOCALIZED_TEXT_DEFAULTS = {\n zh: {\n continueText: '继续',\n continueTextMaxTokens: '继续',\n continueTextSilent:\n '继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。',\n continueTextLoop: '继续',\n continueTextInterrupted:\n '继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。',\n guardPendingText: '(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)',\n guardDoneText: '(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)',\n loopText: '(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)',\n },\n en: {\n continueText: 'Continue',\n continueTextMaxTokens: 'Continue',\n continueTextSilent:\n 'Continue. Your previous turn ended with internal reasoning only, with no message and no tool call, so nothing reached the user. Always finish a turn with a tool call or a visible answer.',\n continueTextLoop: 'Continue',\n continueTextInterrupted:\n 'Continue. The harness was restarted while your previous turn was still running; tool calls pending at the restart are recorded with unknown outcomes. Resume where you left off, verifying external state before retrying anything that may have side effects.',\n guardPendingText:\n '(The previous tool \"{tool}\" may not have completed. Check its state before continuing and do not run it again.)',\n guardDoneText:\n '(The previous tool \"{tool}\" completed successfully. Result: {result}; do not run it again. Continue from there.)',\n loopText:\n '(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)',\n },\n ru: {\n continueText: 'Продолжай',\n continueTextMaxTokens: 'Продолжай',\n continueTextSilent:\n 'Продолжай. Предыдущий ход закончился только внутренним рассуждением: ни ответа, ни вызова инструмента, поэтому пользователь ничего не увидел. Каждый ход должен заканчиваться вызовом инструмента или видимым ответом.',\n continueTextLoop: 'Продолжай',\n continueTextInterrupted:\n 'Продолжай. Хост перезапустился, пока предыдущий ход ещё выполнялся; вызовы инструментов, незавершённые на момент перезапуска, записаны с неизвестным результатом. Продолжай с места остановки, проверяя внешнее состояние перед повтором действий с возможными побочными эффектами.',\n guardPendingText:\n '(Предыдущий инструмент «{tool}», возможно, не завершился. Проверь его состояние перед продолжением и не запускай его повторно.)',\n guardDoneText:\n '(Предыдущий инструмент «{tool}» завершился успешно. Результат: {result}; не запускай его повторно, продолжай с этого места.)',\n loopText:\n '(Похоже, ты застрял в цикле. Перестань повторять последнее действие и продолжай другим способом.)',\n },\n} as const satisfies Record<AutoContinueLocale, Record<string, string>>;\n\n/** The `auto-continue` settings section (all fields optional on the wire; the host schema carries defaults). */\nexport interface AutoContinueSettings {\n /** Active browser/UI locale mirrored by the client. */\n locale?: AutoContinueLocale;\n /** Send continue messages with the plugin source instead of the legacy user source. */\n usePluginSource?: boolean;\n /** Text automatically sent after an interruption. */\n continueText?: string;\n /** Text sent when the output token ceiling is reached (same placeholders as `continueText`). */\n continueTextMaxTokens?: string;\n /** Resume observed model activity that completes without visible output. */\n resumeSilentTurns?: boolean;\n /** Resume interrupted subagent sessions when their main conversation has auto-continue enabled. Subagents never enter the autonomous loop. */\n resumeSubagentSessions?: boolean;\n /** Autonomous mode: hand the thread back to the agent after every completed turn, looping until the user stops it. The consecutive-failure cap only throttles failures, never successful completions. */\n resumeCompletedTurns?: boolean;\n /** Text sent to resume a silent turn (same placeholders as `continueText`). */\n continueTextSilent?: string;\n /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */\n continueTextLoop?: string;\n /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */\n continueTextInterrupted?: string;\n /** Idempotency guard: inspect the last tool call before resuming and steer the model. */\n guardTools?: boolean;\n /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */\n guardPendingText?: string;\n /** Guard text appended when the last tool call completed successfully (don't rerun it). */\n guardDoneText?: string;\n /** Grace period after an interruption before auto-sending (ms). */\n graceMs?: number;\n /** Minimum interval between two auto-continues per session (ms). */\n cooldownMs?: number;\n /** Max consecutive auto-continues per session before stopping. */\n maxConsecutive?: number;\n /** Recover delayed interrupted sessions during the host startup window. */\n scanOnBoot?: boolean;\n /** Max eligible recoveries per scan pass (most recently active first). */\n scanLimit?: number;\n /** Interruption freshness and duration of startup polling (ms). */\n freshMs?: number;\n /** Log `[auto-continue]` lines to the browser console. */\n verbose?: boolean;\n /** Classify failures: auto-continue transient errors only; permanent ones (auth/balance/model) are skipped and notified. */\n classify?: boolean;\n /** Provider-specific message/code/status fragments that explicitly count as retryable, one literal per line. */\n retryableErrorPatterns?: string;\n /** Cooldown multiplier per consecutive failure (adaptive backoff). */\n backoffFactor?: number;\n /** Cap on the effective backoff interval (ms). */\n backoffMaxMs?: number;\n /** Show browser notifications for auto-continue events. */\n notify?: boolean;\n /** Globally pause auto-continue: no live or scan send, queued pending sends cancelled. */\n paused?: boolean;\n /** Persistent per-session overrides; default explicitly inherits the profile default. */\n sessionModes?: Record<string, SessionMode>;\n /** Show the session mode selector in the conversation composer. */\n showComposerToggle?: boolean;\n /** Loop guard: detect a running turn spinning in place (short talk without tools, or the same tool repeating) and restart it. */\n loopGuard?: boolean;\n /** A model message shorter than this many chars counts as a \"short sentence\" (loop signal). */\n loopShortChars?: number;\n /** Consecutive short sentences within this window (ms) with no tool call in between trip the loop guard. */\n loopWindowMs?: number;\n /** Consecutive short sentences trip the loop guard. */\n loopShortCount?: number;\n /** Consecutive identical tool calls with identical arguments AND identical results trip the loop guard. */\n loopToolRepeat?: number;\n /** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */\n loopRepeatText?: number;\n /** Text sent after the loop guard cancels and restarts a turn (supports {tool}). */\n loopText?: string;\n /** Recover child (subagent / Agent Teams) sessions that a restart interrupted by waking their root session once. */\n resumeInterruptedChildren?: boolean;\n /** Re-arm a goal that a restart left `active` but `disarmed`, when its own session is resumed. */\n resumeGoals?: boolean;\n /** Also resume goals the user explicitly paused. Off by default: pausing is a human decision. */\n resumePausedGoals?: boolean;\n /** Hold network-error recoveries while the host is offline; waiting does not consume the retry budget. */\n pauseWhenOffline?: boolean;\n /** How often (ms) a held recovery re-checks connectivity. */\n offlineCheckMs?: number;\n /** Autonomous-loop round cap per session; 0 means unlimited. Resets when the user sends a message or turns the loop back on. */\n loopMaxIterations?: number;\n}\n\n/** Fully resolved configuration (built-in defaults + user overrides). */\nexport type AutoContinueConfig = Required<AutoContinueSettings>;\n\n/** Effective built-in defaults; localized text fields use English until a browser locale is mirrored. */\nexport const DEFAULT_CONFIG: AutoContinueConfig = {\n locale: 'en',\n ...LOCALIZED_TEXT_DEFAULTS.en,\n usePluginSource: false,\n resumeSilentTurns: true,\n resumeSubagentSessions: false,\n resumeCompletedTurns: false,\n continueTextLoop: '',\n guardTools: true,\n graceMs: 3000,\n cooldownMs: 20000,\n maxConsecutive: 3,\n scanOnBoot: true,\n scanLimit: 8,\n freshMs: 15 * 60 * 1000,\n verbose: true,\n classify: true,\n retryableErrorPatterns: '',\n backoffFactor: 2,\n backoffMaxMs: 300000,\n notify: false,\n paused: false,\n sessionModes: {},\n showComposerToggle: true,\n loopGuard: true,\n loopShortChars: 40,\n loopWindowMs: 30000,\n loopShortCount: 12,\n loopRepeatText: 4,\n loopToolRepeat: 5,\n resumeInterruptedChildren: false,\n resumeGoals: false,\n resumePausedGoals: false,\n pauseWhenOffline: true,\n offlineCheckMs: 15000,\n loopMaxIterations: 0,\n};\n\nfunction numberOr(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;\n}\n\nfunction booleanOr(value: unknown, fallback: boolean): boolean {\n return typeof value === 'boolean' ? value : fallback;\n}\n\n/** Resolve a (possibly partial / not-yet-loaded) settings section to a full config. */\nexport function resolveConfig(section: AutoContinueSettings | undefined): AutoContinueConfig {\n const value = section ?? {};\n const locale = resolveLocale(value.locale);\n const localized = LOCALIZED_TEXT_DEFAULTS[locale];\n const text =\n typeof value.continueText === 'string' && value.continueText.trim() !== ''\n ? value.continueText\n : localized.continueText;\n const maxTokensText =\n typeof value.continueTextMaxTokens === 'string' && value.continueTextMaxTokens.trim() !== ''\n ? value.continueTextMaxTokens\n : localized.continueTextMaxTokens;\n const silentText =\n typeof value.continueTextSilent === 'string' && value.continueTextSilent.trim() !== ''\n ? value.continueTextSilent\n : localized.continueTextSilent;\n const loopText =\n typeof value.continueTextLoop === 'string' && value.continueTextLoop.trim() !== ''\n ? value.continueTextLoop\n : localized.continueTextLoop;\n const interruptedText =\n typeof value.continueTextInterrupted === 'string' && value.continueTextInterrupted.trim() !== ''\n ? value.continueTextInterrupted\n : localized.continueTextInterrupted;\n const guardPendingText =\n typeof value.guardPendingText === 'string' && value.guardPendingText.trim() !== ''\n ? value.guardPendingText\n : localized.guardPendingText;\n const guardDoneText =\n typeof value.guardDoneText === 'string' && value.guardDoneText.trim() !== ''\n ? value.guardDoneText\n : localized.guardDoneText;\n return {\n locale,\n usePluginSource: booleanOr(value.usePluginSource, DEFAULT_CONFIG.usePluginSource),\n continueText: text,\n continueTextMaxTokens: maxTokensText,\n resumeSilentTurns: booleanOr(value.resumeSilentTurns, DEFAULT_CONFIG.resumeSilentTurns),\n resumeSubagentSessions: booleanOr(value.resumeSubagentSessions, DEFAULT_CONFIG.resumeSubagentSessions),\n resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),\n continueTextSilent: silentText,\n continueTextLoop: loopText,\n continueTextInterrupted: interruptedText,\n guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),\n guardPendingText,\n guardDoneText,\n graceMs: numberOr(value.graceMs, DEFAULT_CONFIG.graceMs),\n cooldownMs: numberOr(value.cooldownMs, DEFAULT_CONFIG.cooldownMs),\n maxConsecutive: Math.max(1, numberOr(value.maxConsecutive, DEFAULT_CONFIG.maxConsecutive)),\n scanOnBoot: booleanOr(value.scanOnBoot, DEFAULT_CONFIG.scanOnBoot),\n scanLimit: Math.max(1, numberOr(value.scanLimit, DEFAULT_CONFIG.scanLimit)),\n freshMs: numberOr(value.freshMs, DEFAULT_CONFIG.freshMs),\n verbose: booleanOr(value.verbose, DEFAULT_CONFIG.verbose),\n classify: booleanOr(value.classify, DEFAULT_CONFIG.classify),\n retryableErrorPatterns:\n typeof value.retryableErrorPatterns === 'string'\n ? value.retryableErrorPatterns.trim()\n : DEFAULT_CONFIG.retryableErrorPatterns,\n backoffFactor: Math.max(1, numberOr(value.backoffFactor, DEFAULT_CONFIG.backoffFactor)),\n backoffMaxMs: numberOr(value.backoffMaxMs, DEFAULT_CONFIG.backoffMaxMs),\n notify: booleanOr(value.notify, DEFAULT_CONFIG.notify),\n paused: booleanOr(value.paused, DEFAULT_CONFIG.paused),\n sessionModes: value.sessionModes !== null && typeof value.sessionModes === 'object' && !Array.isArray(value.sessionModes)\n ? value.sessionModes : {},\n showComposerToggle: booleanOr(value.showComposerToggle, DEFAULT_CONFIG.showComposerToggle),\n loopGuard: booleanOr(value.loopGuard, DEFAULT_CONFIG.loopGuard),\n loopShortChars: Math.max(1, numberOr(value.loopShortChars, DEFAULT_CONFIG.loopShortChars)),\n loopWindowMs: Math.max(1000, numberOr(value.loopWindowMs, DEFAULT_CONFIG.loopWindowMs)),\n loopShortCount: Math.max(2, numberOr(value.loopShortCount, DEFAULT_CONFIG.loopShortCount)),\n loopRepeatText: Math.max(2, numberOr(value.loopRepeatText, DEFAULT_CONFIG.loopRepeatText)),\n loopToolRepeat: Math.max(2, numberOr(value.loopToolRepeat, DEFAULT_CONFIG.loopToolRepeat)),\n loopText:\n typeof value.loopText === 'string' && value.loopText.trim() !== ''\n ? value.loopText\n : localized.loopText,\n resumeInterruptedChildren: booleanOr(\n value.resumeInterruptedChildren,\n DEFAULT_CONFIG.resumeInterruptedChildren,\n ),\n resumeGoals: booleanOr(value.resumeGoals, DEFAULT_CONFIG.resumeGoals),\n resumePausedGoals: booleanOr(value.resumePausedGoals, DEFAULT_CONFIG.resumePausedGoals),\n pauseWhenOffline: booleanOr(value.pauseWhenOffline, DEFAULT_CONFIG.pauseWhenOffline),\n offlineCheckMs: Math.max(1000, numberOr(value.offlineCheckMs, DEFAULT_CONFIG.offlineCheckMs)),\n loopMaxIterations: Math.floor(numberOr(value.loopMaxIterations, DEFAULT_CONFIG.loopMaxIterations)),\n };\n}\n\n/**\n * 视为「非人为中断」的回合结束原因, 用于启动/重连扫描。\n * - `interrupted` 只由崩溃修复在宿主重载时写入(loop 永不实时发出), 因此仅在扫描路径处理;\n * - 实时事件路径只对 `error` / `max-tokens` 自动续跑; 另外续跑没有可见输出的 `completed` / `no-visible-output` 回合(不属于本类型);\n * - `aborted`(用户停止)与 `blocked`(策略拒绝)永不自动继续。\n */\ntype NonHumanReason = 'error' | 'interrupted' | 'max-tokens';\n\nexport function isNonHumanReason(kind: string): kind is NonHumanReason {\n return kind === 'error' || kind === 'interrupted' || kind === 'max-tokens';\n}\n\n/** 一次回合失败的机器可读事实(turn/end error 的 LlmFailure 载荷)。 */\nexport interface FailureFacts {\n /** 稳定机器路由码(如 UPSTREAM、RATE_LIMIT_EXCEEDED、INVALID_API_KEY)。 */\n code: string;\n /** 人类可读的失败描述。 */\n message: string;\n /** 供应商 HTTP 状态码(可用时)。 */\n status?: number;\n}\n\n/**\n * 错误分类: 该失败是否值得自动继续。\n * 用户填写的 provider 专属文本片段优先覆盖内置结果; 未命中时,\n * 永久性失败(认证/余额/模型不存在/上下文超限等)重试也不会成功, 应跳过并通知用户;\n * 其余(网络、超时、5xx、429 等)视为临时性失败, 允许自动恢复。\n */\nexport function isTransientFailure(failure: FailureFacts, retryableErrorPatterns = ''): boolean {\n const haystack = `${failure.code} ${failure.status ?? ''} ${failure.message}`.toLowerCase();\n const explicitlyRetryable = retryableErrorPatterns\n .split(/\\r?\\n/)\n .map((pattern) => pattern.trim().toLowerCase())\n .filter((pattern) => pattern !== '')\n .some((pattern) => haystack.includes(pattern));\n if (explicitlyRetryable) return true;\n const status = failure.status;\n if (status !== undefined && (status === 401 || status === 403)) return false;\n // Malformed model output can echo tool arguments that look like auth/quota errors.\n if (failure.code === 'MALFORMED_RESPONSE') return true;\n const permanent =\n /auth|unauthor|forbidden|credential|api[_-]?key|permission/i.test(haystack) ||\n /insufficient.*(balance|quota)|billing|payment|quota.*exceeded.*(?!retry)/i.test(haystack) ||\n /model.*not[_-]?found|unknown[_-]?model|model[_-]?not[_-]?found|not.*support.*model/i.test(haystack) ||\n /context.*(length|limit|overflow|exceed)|token.*limit|max.*context/i.test(haystack) ||\n /invalid[_-]?request|bad[_-]?request/i.test(haystack) ||\n /prompt variable \"\\{\\{[^\"\\r\\n]+\\}\\}\" has no value for this assembly/i.test(haystack);\n return !permanent;\n}\n\n/**\n * host/agent-error 消息分类: 仅明确属于网络/传输类的临时错误才自动继续。\n * 其余(序列化失败、配置/宿主内部错误等)视为永久性——重试无益, 且用户停止导致的\n * 序列化失败(如 Windows 下 abort 的 DOMException reason)绝不能自动续跑。\n */\nexport function isTransientAgentError(message: string): boolean {\n return /network|timeout|timed ?out|econn|etimedout|socket|5\\d\\d|\\b429\\b|upstream|temporar/i.test(message);\n}\n\n/**\n * 失败是否属于连接层(断网/DNS/连接被拒/传输超时)。只有这类失败值得先做连通性\n * 检测: 断网时续跑必然再失败一次, 白白消耗连续上限。5xx/429 等服务端错误不在此列。\n */\nexport function isNetworkFailure(failure: FailureFacts): boolean {\n if (/^(TRANSPORT|TIMEOUT|NETWORK|E(CONN|NET|HOST|AI_|NOTFOUND|TIMEDOUT|PIPE))/i.test(failure.code)) return true;\n return /network|fetch failed|econn|enotfound|eai_again|etimedout|enetunreach|ehostunreach|enetdown|getaddrinfo|socket hang up|offline|could not reach|connection (reset|refused|closed)|timed? ?out/i\n .test(failure.message);\n}\n\n/** 通知上的一个操作按钮(action 标识 + 显示文案)。 */\nexport interface NotifyAction {\n /** 稳定动作标识, 点击时经 onAction 回调传出。 */\n action: string;\n /** 按钮显示文案。 */\n title: string;\n}\n\n/** 通知的可选行为: 操作按钮列表与点击回调。 */\nexport interface NotifyOptions {\n actions?: NotifyAction[];\n onAction?: (action: string) => void;\n}\n\n/** 浏览器通知(不可用时静默跳过); 点击通知聚焦窗口, 操作按钮走 onAction。 */\n/** 把毫秒格式化为人类可读的经过时长(如 65s → 1m5s)。 */\nfunction formatElapsed(ms: number | undefined): string {\n if (ms === undefined || !Number.isFinite(ms) || ms < 0) return '';\n if (ms < 1000) return `${Math.round(ms)}ms`;\n const s = Math.round(ms / 1000);\n if (s < 60) return `${s}s`;\n return `${Math.floor(s / 60)}m${s % 60 > 0 ? `${s % 60}s` : ''}`;\n}\n\n/** 模板填充所需的上下文(全部可选, 缺失的占位符填为空串)。 */\nexport interface TemplateContext {\n /** 失败事实(错误码/消息/HTTP 状态), 对应 {code}/{message}/{status}。 */\n facts?: FailureFacts;\n /** 失败前最后一次工具调用的名称, 对应 {tool}。 */\n tool?: string;\n /** 失败回合的编号, 对应 {turn}。 */\n turn?: number;\n /** 连续失败次数(含本次), 对应 {errorCount}。 */\n errorCount?: number;\n /** 会话标题(来自 session.list 投影, 可用时), 对应 {sessionTitle}。 */\n sessionTitle?: string;\n /** 自失败发生以来的毫秒数, 对应 {elapsed}。 */\n elapsedMs?: number;\n /** 上一步工具结果摘要(截断), 对应 {result}(护栏模板用)。 */\n result?: string;\n}\n\n/** 用失败事实与回合信息填充 continueText 模板占位符({code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed}/{result})。 */\nexport function fillTemplate(template: string, ctx: TemplateContext): string {\n return template\n .replace(/\\{code\\}/g, ctx.facts?.code ?? '')\n .replace(/\\{message\\}/g, ctx.facts?.message ?? '')\n .replace(/\\{status\\}/g, ctx.facts?.status !== undefined ? String(ctx.facts.status) : '')\n .replace(/\\{tool\\}/g, ctx.tool ?? '')\n .replace(/\\{turn\\}/g, ctx.turn !== undefined ? String(ctx.turn) : '')\n .replace(/\\{errorCount\\}/g, ctx.errorCount !== undefined ? String(ctx.errorCount) : '')\n .replace(/\\{sessionTitle\\}/g, ctx.sessionTitle ?? '')\n .replace(/\\{elapsed\\}/g, formatElapsed(ctx.elapsedMs))\n .replace(/\\{result\\}/g, ctx.result ?? '');\n}\n\n// ---------- 幂等护栏: 上一步工具调用的执行状态 ----------\n\n/** 工具结果摘要的最大长度(护栏模板 {result} 用)。 */\nconst TOOL_RESULT_CAP = 160;\n\n/**\n * 给 JSON 值生成定长且键顺序无关的稳定指纹。\n *\n * 这里不保存可能很大的工具输出原文;每个字符都会进入两个独立的\n * 32-bit 累加器,再附上字符数,供 loop guard 比较完整的模型可见结果。\n */\nfunction stableFingerprint(value: unknown): string {\n let first = 0x811c9dc5;\n let second = 0x9e3779b9;\n let length = 0;\n const feed = (text: string): void => {\n length += text.length;\n for (let i = 0; i < text.length; i += 1) {\n const code = text.charCodeAt(i);\n first = Math.imul(first ^ code, 0x01000193) >>> 0;\n second = Math.imul(second ^ code, 0x85ebca6b) >>> 0;\n second = (second ^ (second >>> 13)) >>> 0;\n }\n };\n const walk = (part: unknown): void => {\n if (part === null) {\n feed('null');\n } else if (Array.isArray(part)) {\n feed('[');\n for (const item of part) {\n walk(item);\n feed(',');\n }\n feed(']');\n } else if (typeof part === 'object') {\n feed('{');\n const record = part as Record<string, unknown>;\n for (const key of Object.keys(record).sort()) {\n feed(JSON.stringify(key));\n feed(':');\n walk(record[key]);\n feed(',');\n }\n feed('}');\n } else {\n feed(`${typeof part}:${JSON.stringify(part) ?? String(part)}`);\n }\n };\n walk(value);\n return `${first.toString(16).padStart(8, '0')}${second.toString(16).padStart(8, '0')}:${length}`;\n}\n\n/** 从任意内容块里递归收集文本(结果为模型可见的工具输出)。 */\nfunction extractText(blocks: unknown, cap: number): string {\n let out = '';\n const walk = (value: unknown): void => {\n if (out.length >= cap) return;\n if (Array.isArray(value)) {\n for (const item of value) walk(item);\n return;\n }\n if (typeof value !== 'object' || value === null) return;\n const record = value as Record<string, unknown>;\n if (record['type'] === 'text' && typeof record['text'] === 'string') {\n out += record['text'];\n return;\n }\n for (const child of Object.values(record)) walk(child);\n };\n walk(blocks);\n return out.slice(0, cap);\n}\n\n/** 上一步工具调用的判定结果: 是否已确认完成, 以及文本摘要。 */\nexport interface ToolResultFacts {\n /** 工具是否成功完成(内部失败或 isError 视为未成功)。 */\n ok: boolean;\n /** 工具输出的文本摘要(截断)。 */\n excerpt: string;\n /** 完整模型可见内容 + 错误状态的定长稳定指纹(loop guard 比较用)。 */\n identity: string;\n}\n\ninterface ToolResultData {\n turn?: unknown;\n step?: unknown;\n error?: { name?: string; code?: string };\n message?: {\n source?: { kind?: string; callId?: unknown };\n content?: Array<{ type?: string; toolCallId?: unknown; content?: unknown; isError?: boolean }>;\n };\n}\n\nfunction toolCorrelationKey(\n data: { turn?: unknown; step?: unknown },\n callId: string | undefined,\n): string | undefined {\n if (callId === undefined || typeof data.turn !== 'number' || typeof data.step !== 'number') {\n return undefined;\n }\n return JSON.stringify([data.turn, data.step, callId]);\n}\n\nfunction resultBlock(data: ToolResultData) {\n return data.message?.content?.find((part) => part.type === 'tool-result');\n}\n\n/**\n * 取工具结果的关联 id。新版 DSH 的权威位置是 message.source.callId,\n * 同时接受模型可见 block 上的 toolCallId;两者冲突时宁可忽略,不猜测配对。\n */\nexport function toolResultCallId(data: ToolResultData): string | undefined {\n if (resultBlock(data) === undefined) return undefined;\n const sourceId = data.message?.source?.kind === 'tool' ? data.message.source.callId : undefined;\n const blockId = resultBlock(data)?.toolCallId;\n const source = typeof sourceId === 'string' && sourceId !== '' ? sourceId : undefined;\n const block = typeof blockId === 'string' && blockId !== '' ? blockId : undefined;\n if (source !== undefined && block !== undefined && source !== block) return undefined;\n return source ?? block;\n}\n\n/** 从 tool/result 事件载荷提取成功与否与文本摘要。 */\nexport function toolResultFacts(data: ToolResultData): ToolResultFacts {\n const result = resultBlock(data);\n const failed = data.error !== undefined || result?.isError === true;\n return {\n ok: !failed,\n excerpt: extractText(result?.content, TOOL_RESULT_CAP),\n identity: stableFingerprint({ content: result?.content ?? [], isError: failed }),\n };\n}\n\n/** loop guard 在后续 step 边界确认的连续重复信号。 */\nexport interface ToolRepeatSignal {\n tool: string;\n count: number;\n}\n\nexport type ToolGuardState =\n | { kind: 'none' }\n | { kind: 'pending'; tool: string }\n | { kind: 'done'; tool: string; result: string }\n | { kind: 'failed'; tool: string };\n\ninterface TrackedToolCall {\n id: string | undefined;\n name: string;\n key: string;\n result: ToolResultFacts | undefined;\n resultSeq: number | undefined;\n}\n\nconst MAX_PENDING_TOOL_CALLS = 64;\nconst MAX_SEEN_TOOL_CALL_IDS = 256;\n\n/**\n * 每个会话的工具调用关联器。\n *\n * 集中封装事件关联、step 边界确认、护栏读取与重置。内部按 callId 配对,\n * 乱序结果先缓存、再按调用顺序推进 loop 计数。队列和去重 id 都有硬上限;\n * 超限或载荷无法关联时会打断重复计数,宁可漏报也不误杀健康回合。\n */\nexport class ToolInvocationTracker {\n private readonly pendingById = new Map<string, TrackedToolCall>();\n private readonly pendingInOrder: TrackedToolCall[] = [];\n private readonly seenCalls = new Map<string, TrackedToolCall>();\n private readonly seenInOrder: string[] = [];\n private latest: TrackedToolCall | undefined;\n private run: { key: string; tool: string; identity: string; count: number } | undefined;\n private repeatSignal: ToolRepeatSignal | undefined;\n private lastEventSeq = -1;\n\n reset(): void {\n this.pendingById.clear();\n this.pendingInOrder.length = 0;\n this.seenCalls.clear();\n this.seenInOrder.length = 0;\n this.latest = undefined;\n this.run = undefined;\n this.repeatSignal = undefined;\n this.lastEventSeq = -1;\n }\n\n /** 新回合边界:清空工具态,同时把重放水位推进到 turn/start。 */\n startTurn(seq: number): void {\n if (!Number.isSafeInteger(seq) || seq < 0 || seq <= this.lastEventSeq) return;\n this.reset();\n this.lastEventSeq = seq;\n }\n\n /** 回合已结束:保留最后一次调用的护栏,丢弃不再可用的 loop 关联态。 */\n resetRepeat(): void {\n this.pendingById.clear();\n this.pendingInOrder.length = 0;\n this.seenCalls.clear();\n this.seenInOrder.length = 0;\n this.run = undefined;\n this.repeatSignal = undefined;\n }\n\n recordCall(event: SessionEvent<'tool/call'>): boolean {\n if (!this.acceptEventSeq(event.seq)) return false;\n this.repeatSignal = undefined;\n const data = event.data;\n if (typeof data.name !== 'string') {\n this.breakCorrelation();\n return true;\n }\n const key = `${data.name}\\n${typeof data.arguments === 'string' ? data.arguments : ''}`;\n const callId = typeof data.callId === 'string' && data.callId !== '' ? data.callId : undefined;\n const id = toolCorrelationKey(data, callId);\n if (id === undefined) {\n this.breakCorrelation({\n id: undefined,\n name: data.name,\n key,\n result: undefined,\n resultSeq: undefined,\n });\n return true;\n }\n\n const seen = this.seenCalls.get(id);\n if (seen !== undefined) {\n // 同 seq 重放已被水位拒绝;更高 seq 复用复合 identity 时不猜测。\n this.breakCorrelation({\n id: undefined,\n name: data.name,\n key,\n result: undefined,\n resultSeq: undefined,\n });\n return true;\n }\n\n const call: TrackedToolCall = {\n id,\n name: data.name,\n key,\n result: undefined,\n resultSeq: undefined,\n };\n this.latest = call;\n this.pendingById.set(id, call);\n this.pendingInOrder.push(call);\n this.seenCalls.set(id, call);\n this.seenInOrder.push(id);\n this.trim(call);\n return true;\n }\n\n recordResult(event: SessionEvent<'tool/result'>): ToolRepeatSignal | undefined {\n if (!this.acceptEventSeq(event.seq)) return undefined;\n const data = event.data;\n const id = toolCorrelationKey(data, toolResultCallId(data));\n if (id === undefined) {\n this.breakCorrelation(this.latest);\n return undefined;\n }\n const surfaceOp = event.surfaceOp;\n if (typeof surfaceOp === 'object' && surfaceOp !== null) {\n const call = this.seenCalls.get(id);\n if (\n surfaceOp.start !== surfaceOp.end ||\n call === undefined ||\n call.result === undefined ||\n call.resultSeq !== surfaceOp.start\n ) {\n this.breakCorrelation(this.latest);\n return undefined;\n }\n call.result = toolResultFacts(data);\n call.resultSeq = event.seq;\n // replacement 可由 lossy pruner 产生:更新护栏,但绝不据此创建/增强重复。\n this.breakCorrelation(this.latest);\n return undefined;\n }\n const call = this.pendingById.get(id);\n if (call === undefined) {\n const seen = this.seenCalls.get(id);\n const duplicate = seen?.result;\n const incoming = toolResultFacts(data);\n if (\n seen !== undefined &&\n duplicate !== undefined &&\n seen.resultSeq === event.seq &&\n duplicate.identity === incoming.identity\n ) {\n return undefined;\n }\n if (seen !== undefined && duplicate !== undefined) {\n // 已完成调用又出现非 replacement 冲突时,旧完成事实也不再可信。\n seen.result = undefined;\n seen.resultSeq = undefined;\n }\n this.breakCorrelation(this.latest);\n return undefined;\n }\n if (call.result !== undefined) {\n const incoming = toolResultFacts(data);\n if (call.resultSeq === event.seq && call.result.identity === incoming.identity) {\n return undefined;\n }\n // 没有 surface replacement 语义却出现第二个冲突结果:关联已不可信。\n call.result = undefined;\n call.resultSeq = undefined;\n this.breakCorrelation(this.latest);\n return undefined;\n }\n call.result = toolResultFacts(data);\n call.resultSeq = event.seq;\n return this.drainCompleted();\n }\n\n guard(): ToolGuardState {\n const latest = this.latest;\n if (latest === undefined) return { kind: 'none' };\n if (latest.result === undefined) return { kind: 'pending', tool: latest.name };\n if (latest.result.ok) {\n return { kind: 'done', tool: latest.name, result: latest.result.excerpt };\n }\n return { kind: 'failed', tool: latest.name };\n }\n\n lastTool(): string | undefined {\n return this.latest?.name;\n }\n\n /** 下一模型 step 是稳定边界;此前 replacement/新调用会先清除候选。 */\n confirmRepeatAtStep(seq: number): ToolRepeatSignal | undefined {\n if (!this.acceptEventSeq(seq)) return undefined;\n const signal = this.pendingInOrder.length === 0 ? this.repeatSignal : undefined;\n this.repeatSignal = undefined;\n return signal;\n }\n\n /** 非工具 surface range replacement(如 compaction summary)同样终止旧工具证据。 */\n recordSurfaceReplacement(seq: number): void {\n if (!this.acceptEventSeq(seq)) return;\n this.breakCorrelation(this.latest);\n }\n\n restore(events: readonly SessionEvent[], untilSeq: number): void {\n this.reset();\n for (const event of events) {\n if (event.seq >= untilSeq) continue;\n if (event.type === 'turn/start') this.startTurn(event.seq);\n else if (event.type === 'step/start') this.confirmRepeatAtStep(event.seq);\n else if (event.type === 'tool/call') this.recordCall(event);\n else if (event.type === 'tool/result') this.recordResult(event);\n else if (\n (event.type === 'user/message' || event.type === 'assistant/message') &&\n typeof event.surfaceOp === 'object' &&\n event.surfaceOp !== null\n ) {\n this.recordSurfaceReplacement(event.seq);\n }\n }\n }\n\n private acceptEventSeq(seq: number): boolean {\n if (!Number.isSafeInteger(seq) || seq < 0) {\n this.breakCorrelation(this.latest);\n return false;\n }\n // session/event 与持久日志都按 seq 单调投递;旧 seq 只能是重放帧。\n if (seq <= this.lastEventSeq) return false;\n this.lastEventSeq = seq;\n return true;\n }\n\n private breakCorrelation(latest?: TrackedToolCall, preserve?: TrackedToolCall): void {\n this.pendingById.clear();\n this.pendingInOrder.length = 0;\n this.invalidateRunHistory();\n this.latest = latest;\n if (\n preserve?.id !== undefined &&\n preserve.result === undefined &&\n this.seenCalls.get(preserve.id) === preserve\n ) {\n this.pendingById.set(preserve.id, preserve);\n this.pendingInOrder.push(preserve);\n }\n }\n\n private invalidateRunHistory(): void {\n this.run = undefined;\n this.repeatSignal = undefined;\n }\n\n private trim(current: TrackedToolCall): void {\n while (this.pendingInOrder.length > MAX_PENDING_TOOL_CALLS) {\n // 只淘汰一个 call 会让其后的乱序结果跨过未知缺口重新拼成 streak。\n this.breakCorrelation(current, current);\n }\n while (this.seenInOrder.length > MAX_SEEN_TOOL_CALL_IDS) {\n const id = this.seenInOrder.shift();\n if (id !== undefined) {\n this.seenCalls.delete(id);\n // 丢失去重证据后不保留旧缓存;单调 seq 会拒绝淘汰项的旧帧重放。\n this.breakCorrelation(current, current);\n }\n }\n }\n\n private drainCompleted(): ToolRepeatSignal | undefined {\n let advanced = false;\n while (this.pendingInOrder[0]?.result !== undefined) {\n const call = this.pendingInOrder.shift();\n if (call === undefined || call.result === undefined) break;\n advanced = true;\n if (call.id !== undefined) this.pendingById.delete(call.id);\n this.advanceRun(call);\n }\n // 已知并发批次尚未收齐时不提前发信号;末尾结果可能展示真实进展。\n if (!advanced) return undefined;\n return this.refreshRepeatSignal();\n }\n\n private advanceRun(call: TrackedToolCall): void {\n if (call.result === undefined) return;\n if (this.run?.key === call.key && this.run.identity === call.result.identity) {\n this.run.count += 1;\n } else {\n this.run = { key: call.key, tool: call.name, identity: call.result.identity, count: 1 };\n }\n }\n\n private refreshRepeatSignal(): ToolRepeatSignal | undefined {\n this.repeatSignal =\n this.pendingInOrder.length === 0 && this.run !== undefined\n ? { tool: this.run.tool, count: this.run.count }\n : undefined;\n return this.repeatSignal;\n }\n}\n\n/** 自适应退避: 同一会话连续失败时的有效冷却间隔。 */\nexport function effectiveCooldown(\n consecutive: number,\n base: number,\n factor: number,\n max: number,\n): number {\n // consecutive = 已连续自动继续的次数; 第 1 次后开始按 factor 递增\n const multiplier = Math.pow(factor, consecutive);\n return Math.min(Math.max(base, base * multiplier), Math.max(base, max));\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** 浏览器当前 IANA 时区; 不可用时省略(宿主允许省略)。 */\nfunction clientTimeZone(): string | undefined {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** A sent recovery prompt, not proof that the following turn succeeded. */\nexport interface RecoveryAttempt {\n sessionId: string;\n at: number;\n reason: 'error' | 'max-tokens' | 'silent' | 'interrupted' | 'loop-guard' | 'manual';\n consecutive: number;\n}\n\n/** 一天的自动继续统计(host 单实例内存态)。 */\nexport interface DayStats {\n /** 本地日期 YYYY-MM-DD。 */\n date: string;\n /** 自动发送次数。 */\n sent: number;\n /** 因永久性错误跳过的次数。 */\n skipped: number;\n /** 发送后回合成功完成(恢复成功)的次数。 */\n recovered: number;\n /** 发送后再次失败的次数。 */\n failed: number;\n /** 达到连续上限而停止的次数(按停止事件计)。 */\n gaveUp: number;\n /** loop guard 打断并重启回合的次数。 */\n looped: number;\n /** 按错误码计数的失败分布。 */\n byCode: Record<string, number>;\n}\n\nexport function todayKey(): string {\n const d = new Date();\n const mm = String(d.getMonth() + 1).padStart(2, '0');\n const dd = String(d.getDate()).padStart(2, '0');\n return `${d.getFullYear()}-${mm}-${dd}`;\n}\n\n/** 空统计桶。 */\nexport function emptyDayStats(): DayStats {\n return { date: todayKey(), sent: 0, skipped: 0, recovered: 0, failed: 0, gaveUp: 0, looped: 0, byCode: {} };\n}\n\n/** 每会话运行时状态。 */\nexport interface SessionState {\n /** 连续自动「继续」次数; 成功回合或用户手动介入后归零。 */\n consecutive: number;\n /** 上次自动「继续」尝试(成功或失败)时间戳; 防止失败场景下的快速重试循环。 */\n lastAttemptAt: number;\n /** 尚未回显到会话事件流的自动发送消息 ID。 */\n pendingEchoMessageIds: Map<string, number>;\n /** 宽限期定时器(进行中的待发送)。 */\n pendingTimer: ReturnType<typeof setTimeout> | undefined;\n pendingReason?: string;\n /** 宿主权威 running 位(来自 host/session-status 与回合事件)。 */\n running: boolean | undefined;\n /** 当前排队消息数(来自 session/queue 帧)。 */\n queued: number;\n /** 子代理会话(session header origin is `subagent`). */\n subagent: boolean;\n /** 最近一次回合失败的事实(用于分类与模板填充)。 */\n lastFailure: FailureFacts | undefined;\n /** 最近一次失败的发生时间(模板 {elapsed} 与恢复统计用)。 */\n lastFailureAt: number;\n /** callId 精确配对的工具调用、幂等护栏与 loop 重复态。 */\n tools: ToolInvocationTracker;\n /** 失败回合的编号(模板 {turn})。 */\n lastTurn: number | undefined;\n /** 我们最近一次自动发送的时间戳; 0 = 没有待确认的恢复。 */\n pendingRecoveryAt: number;\n /** unknown: no observed start; empty: no model activity; silent: activity without visible output. */\n turnOutput: 'unknown' | 'empty' | 'silent' | 'visible';\n outputTurn: number | undefined;\n outputStartSeq: number;\n /** message-ops maintenance window, which must not enter model recovery or loop accounting. */\n maintenanceTurn?: number;\n /** 当前连续短句数(loop guard 信号 1: 空转)。 */\n shortRun: number;\n /** 最后一条短句的时间(时间窗判定用)。 */\n lastShortAt: number;\n /** 最后一条模型消息的文本(相同文本重复判定用)。 */\n lastAssistantText: string;\n /** 连续相同文本消息数(最强空转信号, 不限长度)。 */\n sameTextRun: number;\n /** 流式消息尚未闭合的有界尾段(assistant/chunk 增量分段检测用)。 */\n streamTail: string;\n /** 流式消息最近一个长段的归一化文本。 */\n streamLastSegment: string;\n /** 流式消息内连续近似重复长段计数。 */\n streamRepeatRun: number;\n /** 本回合已触发过 loop guard(防重复打断)。 */\n loopFired: boolean;\n /** loop 重启的延迟定时器(冷却结束后再 schedule)。 */\n loopRetryTimer: ReturnType<typeof setTimeout> | undefined;\n /** 冷却期恢复的延迟定时器(等到冷却结束再 schedule, 而不是丢弃这次恢复)。 */\n cooldownRetryTimer: ReturnType<typeof setTimeout> | undefined;\n /** 断网挂起: 进行中的连通性检测令牌(取消时置空, 迟到的检测结果据此作废)。 */\n offlineWait: object | undefined;\n /** 断网挂起: 下一次连通性复检的定时器。 */\n offlineTimer: ReturnType<typeof setTimeout> | undefined;\n /** 本次断网挂起开始的时间; 0 = 未挂起(只在挂起开始/结束时各记一次日志)。 */\n offlineSince: number;\n /** 自主循环已续跑的轮数(用户发消息或重新开启循环时清零)。 */\n loopIterations: number;\n /** 本轮循环上限提示已发出(每次触顶只提示一次)。 */\n loopCapNotified: boolean;\n /** 上次观察到的循环开关; 由关到开时清零轮数。 */\n loopEnabled: boolean | undefined;\n}\n\nexport const freshState = (): SessionState => ({\n consecutive: 0,\n lastAttemptAt: 0,\n pendingEchoMessageIds: new Map(),\n pendingTimer: undefined,\n running: undefined,\n queued: 0,\n subagent: false,\n lastFailure: undefined,\n lastFailureAt: 0,\n tools: new ToolInvocationTracker(),\n lastTurn: undefined,\n pendingRecoveryAt: 0,\n turnOutput: 'unknown',\n outputTurn: undefined,\n outputStartSeq: 0,\n shortRun: 0,\n lastShortAt: 0,\n lastAssistantText: '',\n sameTextRun: 0,\n streamTail: '',\n streamLastSegment: '',\n streamRepeatRun: 0,\n loopFired: false,\n loopRetryTimer: undefined,\n cooldownRetryTimer: undefined,\n offlineWait: undefined,\n offlineTimer: undefined,\n offlineSince: 0,\n loopIterations: 0,\n loopCapNotified: false,\n loopEnabled: undefined,\n});\n\n\nexport const RECOVERY_WINDOW_MS = 10 * 60 * 1000;\n\nexport const ECHO_WINDOW_MS = 10 * 60 * 1000;\nconst MAX_PENDING_ECHO_MESSAGE_IDS = 64;\n\nfunction prunePendingEchoMessageIds(state: SessionState, now: number): void {\n for (const [messageId, queuedAt] of state.pendingEchoMessageIds) {\n if (now - queuedAt > ECHO_WINDOW_MS) state.pendingEchoMessageIds.delete(messageId);\n }\n}\n\n/** Track an identified plugin message before handing it to the host queue. */\nexport function trackPendingEcho(state: SessionState, messageId: string): void {\n const now = Date.now();\n prunePendingEchoMessageIds(state, now);\n state.pendingEchoMessageIds.set(messageId, now);\n while (state.pendingEchoMessageIds.size > MAX_PENDING_ECHO_MESSAGE_IDS) {\n const oldest = state.pendingEchoMessageIds.keys().next();\n if (oldest.done) break;\n state.pendingEchoMessageIds.delete(oldest.value);\n }\n}\n\n/** Roll back tracking when the host rejects a queued message. */\nexport function forgetPendingEcho(state: SessionState, messageId: string): void {\n state.pendingEchoMessageIds.delete(messageId);\n}\n\n/** Match and consume one plugin-owned `user/message` event by stable message ID. */\nexport function isOurEcho(state: SessionState, event: SessionEvent): boolean {\n if (event.type !== 'user/message') return false;\n const message = event.data;\n if (message.source.kind !== 'user' && message.source.kind !== AUTO_CONTINUE_SOURCE_KIND) return false;\n if (state.pendingEchoMessageIds.size === 0) return false;\n const now = Date.now();\n prunePendingEchoMessageIds(state, now);\n return state.pendingEchoMessageIds.delete(message.id);\n}\n", "/**\n * `auto-continue` namespace dictionaries: copy for the plugin settings card\n * registered into the `settings.plugin.item` seat of the plugin-configuration\n * section. Includes the card-chrome keys the card component reads.\n */\nimport { LOCALIZED_TEXT_DEFAULTS } from '../shared/core.ts';\n\n/** 简体中文词典(键集的事实来源)。 */\nexport const zh = {\n 'chrome.saved': '所有更改已保存',\n 'notification.title': '自动继续设置',\n 'notification.enabled': '设置已保存,浏览器通知已开启。',\n 'notification.disabled': '设置已保存,浏览器通知已关闭。',\n 'notification.saved': '自动继续的设置已保存。',\n 'notification.blocked': '设置已保存,但浏览器尚未允许通知。请在此网站的权限设置中允许通知。',\n 'notification.unsupported': '设置已保存,当前浏览器不支持通知。',\n 'notification.failed': '设置已保存,但浏览器通知未能发出。请检查网站和系统的通知权限。',\n 'chrome.categories': '设置类别',\n 'repo.star': '觉得好用的话,点个 Star 吧',\n 'repo.link': 'GitHub 仓库',\n 'repo.aria': '在新标签页打开 HsiangNianian/dsh-auto-continue 的 GitHub 仓库',\n 'category.general.title': '常规',\n 'category.general.description': '控制自动继续的启停、显示和通知。',\n 'category.recovery.title': '重试策略',\n 'category.recovery.description': '设置等待时间、次数上限和错误分类。',\n 'category.startup.title': '启动恢复',\n 'category.startup.description': 'DSH 重启后,找回最近中断的会话。',\n 'category.prompts.title': '继续文本',\n 'category.prompts.description': '留空使用内置文案,跟随 DSH 的界面语言。',\n 'category.safety.title': '安全保护',\n 'category.safety.description': '避免重复执行工具,识别并打断无效循环。',\n 'category.status.title': '状态与日志',\n 'category.status.description': '查看活动记录与暂停的会话。',\n 'field.paused': '全局启用自动继续',\n 'field.showComposerToggle': '在会话区显示自动继续开关',\n 'field.showComposerToggleHint': '默认显示。隐藏控件不会改变会话模式;点击保存后生效。',\n 'field.usePluginSource': '以插件来源发送继续消息',\n 'field.usePluginSourceHint': '默认关闭,沿用旧版用户消息来源;开启后标记为本插件来源。点击保存后生效。',\n 'composer.label': '自动继续',\n 'composer.mode': '自动继续模式',\n 'composer.scope': '只控制当前会话,立即保存并同步到其他标签页。关闭后也不再自动打断循环。',\n 'composer.default': '跟随默认',\n 'composer.off': '关闭',\n 'composer.recover': '仅故障恢复',\n 'composer.loop': '自主循环',\n 'composer.paused': '全局已暂停',\n 'composer.unavailable': '等待宿主连接',\n 'composer.reconnecting': '正在重新连接状态桥…当前显示的是上次的设置,重连后才能修改。',\n 'composer.saving': '正在保存自动继续设置…',\n 'composer.saveFailed': '保存失败,请重试',\n 'field.pausedHint': '恢复意外中断的会话。关闭并保存后,全局暂停恢复并取消已排队的继续。循环守卫独立运行;如需停止自动打断,请同时关闭循环守卫。',\n 'field.continueText': '继续文本',\n 'field.continueTextHint': '中断后自动发送的消息内容。',\n 'default.continueText': LOCALIZED_TEXT_DEFAULTS.zh.continueText,\n 'field.continueTextMaxTokens': '超限时的继续文本',\n 'field.continueTextMaxTokensHint': '达到输出 token 上限时自动发送的文本, 支持与继续文本相同的占位符。',\n 'default.continueTextMaxTokens': LOCALIZED_TEXT_DEFAULTS.zh.continueTextMaxTokens,\n 'field.resumeSilentTurns': '续跑无输出回合',\n 'field.resumeSilentTurnsHint': '已观察到模型活动但没有可见输出时续跑;不把空回合、图片或扩展内容误判为静默,冷却与连续上限照常生效。',\n 'field.resumeSubagentSessions': '续跑子代理会话',\n 'field.resumeSubagentSessionsHint': '当子代理所属主会话启用自动继续时,自动续跑其中断的子代理会话。子代理不会进入自主循环、不会被循环守卫重启,也不会由启动扫描恢复。默认关闭。只对仍处于加载状态的子代理生效:DSH 通常会在后台子代理失败后立即关闭它,并把失败结果交给父会话。',\n 'field.resumeCompletedTurns': '默认会话模式',\n 'field.resumeCompletedTurnsHint': '用于未单独设置模式的会话。仅故障恢复继续中断和无输出回合;自主循环还会在正常完成后继续。无输出和失败回合仍计入连续重试次数。',\n 'field.resumeInterruptedChildren': '重启后唤醒子代理会话',\n 'field.resumeInterruptedChildrenHint': 'DSH 重启后,将中断的子代理或团队成员会话清单发送给根会话,由其决定继续或收尾。默认关闭;你手动停止的根会话保持停止。',\n 'field.resumeGoals': '重新武装被重启失活的 goal',\n 'field.resumeGoalsHint': '会话被自动续跑时,把被宿主 disarm 的 active goal 重新 arm,让 goal 的自动继续轮能转起来。注意:这等于代替你做了授权,所以默认关闭。',\n 'field.resumePausedGoals': '恢复被暂停的 goal',\n 'field.resumePausedGoalsHint': '连你手动 pause 的 goal 也一并恢复(需同时开启「重新武装被重启失活的 goal」)。暂停通常是人的明确决定,非必要别开。',\n 'field.pauseWhenOffline': '断网时暂停续跑',\n 'field.pauseWhenOfflineHint': '网络类错误(连不上、DNS 失败、传输超时)续跑前先检测宿主是否联网;断网时挂起,不消耗连续次数,联网后自动继续。设了 HTTP(S)_PROXY 时只检查网卡。',\n 'field.offlineCheckMs': '断网复检间隔 (ms)',\n 'field.offlineCheckMsHint': '挂起期间多久重新检测一次网络,最小 1000。',\n 'field.loopMaxIterations': '自主循环轮数上限',\n 'field.loopMaxIterationsHint': '每个会话自主续跑的最多轮数,0 为不限制。到达上限后停下并提示一次;你发消息或重新开启循环后重新计数。',\n 'field.continueTextLoop': '自主循环的继续文本',\n 'field.continueTextLoopHint': '自主循环每次续跑时发送的文本。',\n 'default.continueTextLoop': LOCALIZED_TEXT_DEFAULTS.zh.continueTextLoop,\n 'field.continueTextSilent': '无输出回合的继续文本',\n 'field.continueTextSilentHint': '回合只输出推理就结束时自动发送的文本, 支持与继续文本相同的占位符。',\n 'default.continueTextSilent': LOCALIZED_TEXT_DEFAULTS.zh.continueTextSilent,\n 'field.continueTextInterrupted': '宿主重启后恢复的继续文本',\n 'field.continueTextInterruptedHint': 'DSH 重启后恢复中断会话时发送的文本。',\n 'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.zh.continueTextInterrupted,\n 'field.guardTools': '幂等护栏',\n 'field.guardToolsHint': '继续前,工具结果未确认时提醒模型核实状态,已成功时提醒跳过该操作。',\n 'field.guardPendingText': '结果未确认时的护栏文本',\n 'field.guardPendingTextHint': '上一步工具可能已部分执行时附加到继续文本之后, 支持 {tool} 占位符。',\n 'default.guardPendingText': LOCALIZED_TEXT_DEFAULTS.zh.guardPendingText,\n 'field.guardDoneText': '工具已成功时的护栏文本',\n 'field.guardDoneTextHint': '上一步工具已确认成功时附加到继续文本之后, 支持 {tool} 与 {result}(结果摘要)占位符。',\n 'default.guardDoneText': LOCALIZED_TEXT_DEFAULTS.zh.guardDoneText,\n 'field.graceMs': '宽限期 (ms)',\n 'field.graceMsHint': '检测到中断后等待的时长; 期间宿主自行恢复则取消。',\n 'field.cooldownMs': '冷却时间 (ms)',\n 'field.cooldownMsHint': '同一会话两次恢复尝试的最小间隔。冷却期间失败会先等待冷却结束,再进入宽限期;正常完成后的自主循环不受此限制。',\n 'field.maxConsecutive': '最大连续次数',\n 'field.maxConsecutiveHint': '连续恢复尝试的上限;用户介入或回合成功且有可见输出后清零。正常完成后的自主循环不计入。',\n 'field.scanOnBoot': '启动恢复扫描',\n 'field.scanOnBootHint': 'DSH 启动后,在扫描时间窗内查找并恢复近期中断的会话,包括当前未打开的会话。',\n 'field.scanLimit': '扫描会话数',\n 'field.scanLimitHint': '每次扫描最多恢复多少个符合条件的会话,优先最近活动的会话。',\n 'field.freshMs': '扫描时间窗 (ms)',\n 'field.freshMsHint': '恢复此时长内中断的会话;启动扫描也在此时长后结束。',\n 'field.verbose': '详细日志',\n 'field.verboseHint': '在 DSH 日志中记录自动继续活动,前缀为 [auto-continue];使用 CLI 时可在运行 DSH 的终端查看。',\n 'field.classify': '错误分类',\n 'field.classifyHint': '仅自动恢复临时性错误(网络/超时/5xx 等); 认证/余额/模型不存在等永久性错误跳过并通知。',\n 'field.retryableErrorPatterns': '自定义可恢复错误',\n 'field.retryableErrorPatternsHint': '每行填写一个具体文本片段,忽略大小写。匹配错误码、HTTP 状态或消息后允许重试;宽泛片段也会重试认证、余额等原本跳过的错误。',\n 'field.retryableErrorPatternsPlaceholder': '例如:Upstream rejected the request as invalid',\n 'field.backoffFactor': '退避系数',\n 'field.backoffFactorHint': '连续失败时冷却间隔的倍率(如 2 表示 20s→40s→80s 递增)。',\n 'field.backoffMaxMs': '最大退避间隔 (ms)',\n 'field.backoffMaxMsHint': '连续失败时,冷却间隔增长到此值后不再增加。',\n 'field.notify': '浏览器通知',\n 'field.notifyHint': '开启后,自动继续活动和设置保存成功时会通知;关闭并保存时也会收到确认。首次开启需允许浏览器通知。',\n 'stats.title': '今日统计',\n 'stats.sent': '自动继续',\n 'stats.skipped': '跳过(永久错误)',\n 'stats.recovered': '恢复成功',\n 'stats.failed': '继续后仍失败',\n 'stats.gaveUp': '停止(达上限)',\n 'stats.looped': '循环打断',\n 'field.loopGuard': '循环守卫',\n 'field.loopGuardHint': '回合连续输出短句且无工具调用、重复文本或重复相同工具调用时,按以下阈值自动打断,并用循环提示文本重启。',\n 'field.loopShortChars': '短句长度上限 (字符)',\n 'field.loopShortCharsHint': '模型消息文本短于此值时计为一条短句。',\n 'field.loopWindowMs': '短句时间窗 (ms)',\n 'field.loopWindowMsHint': '仅统计此时间窗内的连续短句。',\n 'field.loopShortCount': '连续短句阈值',\n 'field.loopShortCountHint': '时间窗内连续多少条短句且期间无工具调用时判定空转循环。',\n 'field.loopRepeatText': '相同消息重复次数',\n 'field.loopRepeatTextHint': '连续输出相同消息达到此次数时打断,不限消息长度;也适用于单条流式消息内的重复段落。',\n 'field.loopToolRepeat': '同工具重复次数',\n 'field.loopToolRepeatHint': '工具、参数和结果均相同的连续调用达到此次数时打断。',\n 'field.loopText': '循环提示文本',\n 'field.loopTextHint': '打断后重启回合时发送的文本, 支持 {tool} 占位符。',\n 'default.loopText': LOCALIZED_TEXT_DEFAULTS.zh.loopText,\n 'stats.byCode': '按错误码统计',\n 'stats.empty': '今天还没有自动继续记录。',\n 'stats.reset': '清零',\n 'recovery.title': '近期恢复尝试',\n 'recovery.hint': '按会话汇总当前 DSH 最近 20 次恢复尝试,插件重启后清空,不含正常自主续跑。',\n 'recovery.empty': '尚无恢复尝试。',\n 'recovery.count': '窗口内尝试',\n 'recovery.consecutive': '最近发送时连续次数',\n 'recovery.latest': '最近原因',\n 'recovery.reason.error': '请求错误',\n 'recovery.reason.max-tokens': '输出上限',\n 'recovery.reason.silent': '无可见输出',\n 'recovery.reason.interrupted': '宿主重启中断',\n 'recovery.reason.loop-guard': '循环守卫',\n 'recovery.reason.manual': '手动立即续跑',\n 'pause.title': '已暂停会话',\n 'pause.none': '没有暂停中的会话。',\n 'pause.clearAll': '全部解除',\n 'pause.unpause': '解除',\n 'pause.minutes': '分钟',\n 'chrome.collapse': '收起设置',\n 'chrome.expand': '展开设置',\n 'chrome.unsaved': '未保存',\n 'chrome.readOnly': '设置为只读,无法修改。',\n 'chrome.unavailable': '设置暂不可用。',\n 'chrome.saveFailed': '保存失败,修改已保留。请检查后重试。',\n 'chrome.discard': '放弃',\n 'chrome.saving': '保存中…',\n 'chrome.save': '保存',\n 'chrome.overridden': '已覆盖',\n 'chrome.reset': '恢复默认',\n 'chrome.invalidNumber': '请输入数字, 留空则使用默认值。',\n 'chrome.inherit': '继承',\n 'chrome.on': '开',\n 'chrome.off': '关',\n} satisfies Record<string, string>;\n\n/** 本插件的键联合。 */\nexport type SettingsCardKey = keyof typeof zh;\n\n/** English dictionary, checked complete against the zh key set. */\nexport const en: Record<SettingsCardKey, string> = {\n 'chrome.saved': 'All changes saved',\n 'notification.title': 'Auto-continue settings',\n 'notification.enabled': 'Settings saved. Browser notifications are on.',\n 'notification.disabled': 'Settings saved. Browser notifications are off.',\n 'notification.saved': 'Your auto-continue settings have been saved.',\n 'notification.blocked': 'Settings saved, but browser notifications are not allowed. Allow notifications in this site’s permissions.',\n 'notification.unsupported': 'Settings saved. This browser does not support notifications.',\n 'notification.failed': 'Settings saved, but the notification could not be sent. Check notification permissions for this site and your system.',\n 'chrome.categories': 'Settings categories',\n 'repo.star': 'Finding it useful? Leave a Star',\n 'repo.link': 'GitHub repo',\n 'repo.aria': 'Open HsiangNianian/dsh-auto-continue on GitHub in a new tab',\n 'category.general.title': 'General',\n 'category.general.description': 'Control automatic recovery, visibility, and notifications.',\n 'category.recovery.title': 'Retry strategy',\n 'category.recovery.description': 'Set wait times, retry limits, and error classification.',\n 'category.startup.title': 'Startup recovery',\n 'category.startup.description': 'Find recently interrupted sessions when DSH restarts.',\n 'category.prompts.title': 'Continue text',\n 'category.prompts.description': 'Leave blank for built-in text in the current DSH language.',\n 'category.safety.title': 'Safety',\n 'category.safety.description': 'Avoid duplicate tool actions and break unproductive loops.',\n 'category.status.title': 'Status and logs',\n 'category.status.description': 'View activity and paused sessions.',\n 'field.paused': 'Enable auto-continue globally',\n 'field.showComposerToggle': 'Show auto-continue switch in the composer',\n 'field.showComposerToggleHint': 'Shown by default. Hiding the control does not change session modes. Click Save to apply.',\n 'field.usePluginSource': 'Send continue messages with plugin source',\n 'field.usePluginSourceHint': 'Off by default to keep the legacy user-message source. Turn on to identify messages as coming from this plugin. Click Save to apply.',\n 'composer.label': 'Auto-continue',\n 'composer.mode': 'Auto-continue mode',\n 'composer.scope': 'Only affects this session. Saved immediately and synced across tabs. Off also disables loop-guard interruptions here.',\n 'composer.default': 'Follow default',\n 'composer.off': 'Off',\n 'composer.recover': 'Recovery only',\n 'composer.loop': 'Autonomous loop',\n 'composer.paused': 'Globally paused',\n 'composer.unavailable': 'Waiting for host',\n 'composer.reconnecting': 'Reconnecting to the host… Showing the last known setting; changes are available again once reconnected.',\n 'composer.saving': 'Saving auto-continue setting…',\n 'composer.saveFailed': 'Could not save. Try again.',\n 'field.pausedHint': 'Resume interrupted sessions. Turn off and save to pause recovery globally and cancel queued continuations. The loop guard stays active; turn it off separately to stop automatic interruptions.',\n 'field.continueText': 'Continue text',\n 'field.continueTextHint': 'Message automatically sent after an interruption.',\n 'default.continueText': LOCALIZED_TEXT_DEFAULTS.en.continueText,\n 'field.continueTextMaxTokens': 'Continue text (max tokens)',\n 'field.continueTextMaxTokensHint': 'Text sent when the output token ceiling is reached; same placeholders as the continue text.',\n 'default.continueTextMaxTokens': LOCALIZED_TEXT_DEFAULTS.en.continueTextMaxTokens,\n 'field.resumeSilentTurns': 'Resume silent turns',\n 'field.resumeSilentTurnsHint': 'Resume observed model activity without visible output. No-op turns, images and extension blocks are not treated as silent; cooldown and retry limits still apply.',\n 'field.resumeSubagentSessions': 'Resume subagent sessions',\n 'field.resumeSubagentSessionsHint': 'Auto-continue interrupted subagent sessions when their main conversation has auto-continue enabled. Subagents never start the autonomous loop, are never loop-guard restarted, and are not recovered by the startup scan. Off by default. Only applies while the subagent is still loaded: DSH usually closes a background subagent as soon as it fails and reports the failure to its parent.',\n 'field.resumeCompletedTurns': 'Default session mode',\n 'field.resumeCompletedTurnsHint': 'Applies to sessions without their own mode. Recovery only resumes interruptions and silent turns; autonomous loop also continues after normal completions. Silent and failed turns still count toward the consecutive retry limit.',\n 'field.resumeInterruptedChildren': 'Wake child sessions after restart',\n 'field.resumeInterruptedChildrenHint': 'After DSH restarts, send the root session a list of interrupted subagent or team-member sessions so it can continue or wrap up their work. Off by default; root sessions you stopped manually stay stopped.',\n 'field.resumeGoals': 'Re-arm goals disarmed by a restart',\n 'field.resumeGoalsHint': 'When a session is auto-continued, re-arm an active goal that the host disarmed so its continuation rounds can run again. This authorizes on your behalf, so it is off by default.',\n 'field.resumePausedGoals': 'Resume paused goals',\n 'field.resumePausedGoalsHint': 'Also resume goals you paused by hand (requires “Re-arm goals disarmed by a restart” to be on as well). Pausing is normally a deliberate human decision; leave this off unless you want it.',\n 'field.pauseWhenOffline': 'Pause while offline',\n 'field.pauseWhenOfflineHint': 'Before retrying a network error (unreachable host, DNS failure, transport timeout), check that the host is online. While offline the retry waits without using up consecutive attempts, then continues once the network is back. With HTTP(S)_PROXY set, only network interfaces are checked.',\n 'field.offlineCheckMs': 'Offline re-check interval (ms)',\n 'field.offlineCheckMsHint': 'How often a held retry checks the network again. Minimum 1000.',\n 'field.loopMaxIterations': 'Autonomous loop round limit',\n 'field.loopMaxIterationsHint': 'Maximum autonomous rounds per session; 0 means no limit. When reached, the loop stops and tells you once; sending a message or turning the loop back on starts the count over.',\n 'field.continueTextLoop': 'Continue text (autonomous loop)',\n 'field.continueTextLoopHint': 'Text sent on each autonomous-loop continuation.',\n 'default.continueTextLoop': LOCALIZED_TEXT_DEFAULTS.en.continueTextLoop,\n 'field.continueTextSilent': 'Continue text (silent turn)',\n 'field.continueTextSilentHint': 'Text sent when a turn ends with reasoning only; same placeholders as the continue text.',\n 'default.continueTextSilent': LOCALIZED_TEXT_DEFAULTS.en.continueTextSilent,\n 'field.continueTextInterrupted': 'Continue text (after harness restart)',\n 'field.continueTextInterruptedHint': 'Text sent when resuming an interrupted session after DSH restarts.',\n 'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.en.continueTextInterrupted,\n 'field.guardTools': 'Idempotency guard',\n 'field.guardToolsHint': 'Before resuming, remind the model to check unconfirmed tool results or skip an action that already succeeded.',\n 'field.guardPendingText': 'Guard text (unconfirmed result)',\n 'field.guardPendingTextHint': 'Appended when the last tool may have partially executed; supports the {tool} placeholder.',\n 'default.guardPendingText': LOCALIZED_TEXT_DEFAULTS.en.guardPendingText,\n 'field.guardDoneText': 'Guard text (tool succeeded)',\n 'field.guardDoneTextHint': 'Appended when the last tool is confirmed done; supports {tool} and {result} (result excerpt).',\n 'default.guardDoneText': LOCALIZED_TEXT_DEFAULTS.en.guardDoneText,\n 'field.graceMs': 'Grace period (ms)',\n 'field.graceMsHint': 'Wait after an interruption; cancelled if the host recovers on its own.',\n 'field.cooldownMs': 'Cooldown (ms)',\n 'field.cooldownMsHint': 'Minimum interval between recovery attempts in the same session. Failures during cooldown wait until it ends, then enter the grace period. Autonomous continuations after normal completions are exempt.',\n 'field.maxConsecutive': 'Max consecutive',\n 'field.maxConsecutiveHint': 'Limit on consecutive recovery attempts. Resets on user intervention or a successful turn with visible output. Autonomous continuations after normal completions do not count.',\n 'field.scanOnBoot': 'Scan on host startup',\n 'field.scanOnBootHint': 'When DSH starts, find and resume recently interrupted sessions within the scan window, including sessions that are not currently open.',\n 'field.scanLimit': 'Scan limit',\n 'field.scanLimitHint': 'Maximum eligible sessions to recover per pass, most recently active first.',\n 'field.freshMs': 'Scan window (ms)',\n 'field.freshMsHint': 'Resume sessions interrupted within this duration. The startup scan also ends after this duration.',\n 'field.verbose': 'Verbose logs',\n 'field.verboseHint': 'Record auto-continue activity in DSH logs with the [auto-continue] prefix. CLI users can view them in the terminal running DSH.',\n 'field.classify': 'Classify errors',\n 'field.classifyHint': 'Auto-resume transient failures only (network/timeout/5xx…); auth, balance and model errors are skipped and notified.',\n 'field.retryableErrorPatterns': 'Custom retryable errors',\n 'field.retryableErrorPatternsHint': 'Enter one specific text fragment per line, ignoring case. A match in the error code, HTTP status, or message allows a retry. Broad fragments can also retry normally skipped authentication or balance errors.',\n 'field.retryableErrorPatternsPlaceholder': 'For example: Upstream rejected the request as invalid',\n 'field.backoffFactor': 'Backoff factor',\n 'field.backoffFactorHint': 'Cooldown multiplier per consecutive failure (2 = 20s→40s→80s…).',\n 'field.backoffMaxMs': 'Max backoff (ms)',\n 'field.backoffMaxMsHint': 'Cooldown stops increasing at this value after consecutive failures.',\n 'field.notify': 'Browser notifications',\n 'field.notifyHint': 'When enabled, notify about auto-continue activity and successful settings saves. Turning this off and saving also sends a confirmation. Allow browser notifications when first enabling it.',\n 'stats.title': \"Today's stats\",\n 'stats.sent': 'Auto-continued',\n 'stats.skipped': 'Skipped (permanent)',\n 'stats.recovered': 'Recovered',\n 'stats.failed': 'Failed after',\n 'stats.gaveUp': 'Gave up (cap)',\n 'stats.looped': 'Loops broken',\n 'field.loopGuard': 'Loop guard',\n 'field.loopGuardHint': 'Interrupt turns that produce consecutive short sentences without tool calls, repeat text, or repeat identical tool calls at the thresholds below. Restart with the loop text.',\n 'field.loopShortChars': 'Short-sentence max (chars)',\n 'field.loopShortCharsHint': 'A model message shorter than this counts as a short sentence.',\n 'field.loopWindowMs': 'Short-sentence window (ms)',\n 'field.loopWindowMsHint': 'Count consecutive short sentences only within this window.',\n 'field.loopShortCount': 'Short-sentence threshold',\n 'field.loopShortCountHint': 'How many consecutive short sentences inside the window, with no tool call, trip the loop guard.',\n 'field.loopRepeatText': 'Identical message count',\n 'field.loopRepeatTextHint': 'Interrupt after this many consecutive identical messages, regardless of length. Also applies to repeated paragraphs within a single streamed message.',\n 'field.loopToolRepeat': 'Same-tool repeat count',\n 'field.loopToolRepeatHint': 'Interrupt after this many consecutive calls with the same tool, arguments, and results.',\n 'field.loopText': 'Loop text',\n 'field.loopTextHint': 'Text sent after the loop guard restarts a turn; supports the {tool} placeholder.',\n 'default.loopText': LOCALIZED_TEXT_DEFAULTS.en.loopText,\n 'stats.byCode': 'By error code',\n 'stats.empty': 'No auto-continue activity today.',\n 'stats.reset': 'Reset',\n 'recovery.title': 'Recent recovery attempts',\n 'recovery.hint': 'The last 20 recovery attempts for this DSH instance, grouped by session. Cleared when the plugin restarts; normal autonomous continuations are excluded.',\n 'recovery.empty': 'No recovery attempts yet.',\n 'recovery.count': 'Attempts in window',\n 'recovery.consecutive': 'Consecutive at last send',\n 'recovery.latest': 'Latest reason',\n 'recovery.reason.error': 'Request error',\n 'recovery.reason.max-tokens': 'Output limit',\n 'recovery.reason.silent': 'No visible output',\n 'recovery.reason.interrupted': 'Host restart interruption',\n 'recovery.reason.loop-guard': 'Loop guard',\n 'recovery.reason.manual': 'Manual resume',\n 'pause.title': 'Paused sessions',\n 'pause.none': 'No sessions paused.',\n 'pause.clearAll': 'Clear all',\n 'pause.unpause': 'Resume',\n 'pause.minutes': 'min',\n 'chrome.collapse': 'Hide settings',\n 'chrome.expand': 'Show settings',\n 'chrome.unsaved': 'Unsaved',\n 'chrome.readOnly': 'Settings are read-only.',\n 'chrome.unavailable': 'Settings are unavailable.',\n 'chrome.saveFailed': 'Could not save. Your edits are still here; review them and try again.',\n 'chrome.discard': 'Discard',\n 'chrome.saving': 'Saving…',\n 'chrome.save': 'Save',\n 'chrome.overridden': 'Overridden',\n 'chrome.reset': 'Reset to default',\n 'chrome.invalidNumber': 'Enter a number, or leave blank to use the default.',\n 'chrome.inherit': 'Inherit',\n 'chrome.on': 'On',\n 'chrome.off': 'Off',\n};\n\n/** Russian dictionary, checked complete against the zh key set. */\nexport const ru: Record<SettingsCardKey, string> = {\n 'chrome.saved': 'Все изменения сохранены',\n 'notification.title': 'Настройки авто-продолжения',\n 'notification.enabled': 'Настройки сохранены. Уведомления браузера включены.',\n 'notification.disabled': 'Настройки сохранены. Уведомления браузера выключены.',\n 'notification.saved': 'Настройки авто-продолжения сохранены.',\n 'notification.blocked': 'Настройки сохранены, но браузер не разрешает уведомления. Разрешите уведомления в настройках этого сайта.',\n 'notification.unsupported': 'Настройки сохранены. Этот браузер не поддерживает уведомления.',\n 'notification.failed': 'Настройки сохранены, но уведомление не удалось отправить. Проверьте разрешения на уведомления для сайта и в системе.',\n 'chrome.categories': 'Категории настроек',\n 'repo.star': 'Понравилось? Поставьте звезду',\n 'repo.link': 'Репозиторий GitHub',\n 'repo.aria': 'Открыть HsiangNianian/dsh-auto-continue на GitHub в новой вкладке',\n 'category.general.title': 'Общие',\n 'category.general.description': 'Управление запуском, отображением и уведомлениями авто-продолжения.',\n 'category.recovery.title': 'Стратегия повторов',\n 'category.recovery.description': 'Время ожидания, лимиты повторов и классификация ошибок.',\n 'category.startup.title': 'Восстановление при запуске',\n 'category.startup.description': 'Поиск недавно прерванных сессий после перезапуска DSH.',\n 'category.prompts.title': 'Текст продолжения',\n 'category.prompts.description': 'Оставьте пустым, чтобы использовать встроенный текст на текущем языке DSH.',\n 'category.safety.title': 'Защита',\n 'category.safety.description': 'Защита от повторного выполнения инструментов и разрыв холостых циклов.',\n 'category.status.title': 'Состояние и журнал',\n 'category.status.description': 'Активность и приостановленные сессии.',\n 'field.paused': 'Включить авто-продолжение глобально',\n 'field.showComposerToggle': 'Показывать переключатель авто-продолжения в поле ввода',\n 'field.showComposerToggleHint': 'Показывается по умолчанию. Скрытие не меняет режимы сессий. Применится после нажатия «Сохранить».',\n 'composer.label': 'Авто-продолжение',\n 'composer.mode': 'Режим авто-продолжения',\n 'composer.scope': 'Действует только на эту сессию: сохраняется сразу и синхронизируется между вкладками. «Выключено» также отключает здесь прерывания защитой от циклов.',\n 'composer.default': 'Как по умолчанию',\n 'composer.off': 'Выключено',\n 'composer.recover': 'Только восстановление',\n 'composer.loop': 'Автономный цикл',\n 'composer.paused': 'Приостановлено глобально',\n 'composer.unavailable': 'Ожидание хоста',\n 'composer.reconnecting': 'Переподключение к хосту… Показана последняя известная настройка; изменить её можно после переподключения.',\n 'composer.saving': 'Сохранение авто-продолжения…',\n 'composer.saveFailed': 'Не удалось сохранить. Повторите попытку.',\n 'field.pausedHint': 'Восстанавливать прерванные сессии. Выключите и сохраните, чтобы приостановить восстановление глобально и отменить запланированные продолжения. Защита от циклов продолжает работать; чтобы остановить автоматические прерывания, отключите её отдельно.',\n 'field.continueText': 'Текст продолжения',\n 'field.continueTextHint': 'Сообщение, автоматически отправляемое после прерывания.',\n 'default.continueText': LOCALIZED_TEXT_DEFAULTS.ru.continueText,\n 'field.continueTextMaxTokens': 'Текст продолжения (лимит токенов)',\n 'field.continueTextMaxTokensHint': 'Отправляется при достижении лимита выходных токенов; те же подстановки, что и в тексте продолжения.',\n 'default.continueTextMaxTokens': LOCALIZED_TEXT_DEFAULTS.ru.continueTextMaxTokens,\n 'field.resumeSilentTurns': 'Продолжать ходы без вывода',\n 'field.resumeSilentTurnsHint': 'Продолжать при наблюдаемой активности модели без видимого вывода. Пустые ходы, изображения и блоки расширений тихими не считаются; задержка и лимиты повторов действуют.',\n 'field.resumeSubagentSessions': 'Продолжать сессии субагентов',\n 'field.resumeSubagentSessionsHint': 'Автоматически продолжать прерванные сессии субагентов, если в их основном диалоге включено авто-продолжение. Субагенты не запускают автономный цикл, не перезапускаются защитой от циклов и не восстанавливаются сканированием при запуске. По умолчанию выключено. Работает, только пока субагент ещё загружен: DSH обычно закрывает фоновый субагент сразу после сбоя и сообщает об ошибке родительскому диалогу.',\n 'field.resumeCompletedTurns': 'Режим сессии по умолчанию',\n 'field.resumeCompletedTurnsHint': 'Для сессий без собственного режима. «Только восстановление» не трогает обычные завершения; «Автономный цикл» продолжает после них. Тихие и неудачные ходы по-прежнему расходуют бюджет повторов.',\n 'field.continueTextLoop': 'Текст продолжения (автономный цикл)',\n 'field.continueTextLoopHint': 'Текст, отправляемый при каждом продолжении автономного цикла.',\n 'default.continueTextLoop': LOCALIZED_TEXT_DEFAULTS.ru.continueTextLoop,\n 'field.continueTextSilent': 'Текст продолжения (ход без вывода)',\n 'field.continueTextSilentHint': 'Текст, отправляемый, когда ход заканчивается только рассуждениями; те же подстановки, что и в тексте продолжения.',\n 'default.continueTextSilent': LOCALIZED_TEXT_DEFAULTS.ru.continueTextSilent,\n 'field.continueTextInterrupted': 'Текст продолжения (после перезапуска хоста)',\n 'field.continueTextInterruptedHint': 'Текст, отправляемый, когда сканирование при запуске продолжает сессию, прерванную перезапуском; по умолчанию объясняет перезапуск и просит сверять состояние перед повтором.',\n 'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.ru.continueTextInterrupted,\n 'field.guardTools': 'Защита от повторного выполнения',\n 'field.guardToolsHint': 'Перед продолжением проверяет последний вызов инструмента: если результат не подтверждён, просит сначала проверить состояние; если вызов успешен — не повторять его. Помогает не дублировать коммиты и вызовы API.',\n 'field.guardPendingText': 'Текст защиты (результат не подтверждён)',\n 'field.guardPendingTextHint': 'Добавляется, если последний инструмент мог выполниться частично; поддерживает подстановку {tool}.',\n 'default.guardPendingText': LOCALIZED_TEXT_DEFAULTS.ru.guardPendingText,\n 'field.guardDoneText': 'Текст защиты (инструмент выполнен)',\n 'field.guardDoneTextHint': 'Добавляется, если последний инструмент подтверждённо выполнен; поддерживает подстановки {tool} и {result} (фрагмент результата).',\n 'default.guardDoneText': LOCALIZED_TEXT_DEFAULTS.ru.guardDoneText,\n 'field.graceMs': 'Период ожидания (мс)',\n 'field.graceMsHint': 'Пауза после прерывания; отменяется, если хост восстановится сам.',\n 'field.cooldownMs': 'Задержка перед повтором (мс)',\n 'field.cooldownMsHint': 'Минимальный интервал между попытками восстановления; сбои в этот период ждут остаток интервала, затем — период ожидания. Обычные передачи автономного цикла от этого освобождены.',\n 'field.maxConsecutive': 'Максимум подряд',\n 'field.maxConsecutiveHint': 'Лимит последовательных попыток восстановления; сбрасывается при вмешательстве пользователя или завершении хода с видимым выводом. Обычные передачи автономного цикла не считаются.',\n 'field.scanOnBoot': 'Сканирование при запуске хоста',\n 'field.scanOnBootHint': 'Ждать поздно загружаемые прерванные сессии в окне сканирования при запуске; сохранённые сессии, которые хост не перезагрузил, тоже материализуются и проверяются; каждая готовая сессия проверяется один раз.',\n 'field.scanLimit': 'Лимит сканирования',\n 'field.scanLimitHint': 'Сколько подходящих сессий восстанавливать за проход; сначала самые недавно активные.',\n 'field.freshMs': 'Окно сканирования (мс)',\n 'field.freshMsHint': 'Учитываются только прерывания в этом окне; опрос при запуске тоже прекращается по его истечении.',\n 'field.verbose': 'Подробный журнал',\n 'field.verboseHint': 'Записывать активность движка в журнал хоста DSH с префиксом [auto-continue]; при работе через CLI эти строки видны в терминале, где запущен DSH.',\n 'field.classify': 'Классификация ошибок',\n 'field.classifyHint': 'Автоматически восстанавливать только временные сбои (сеть, тайм-аут, 5xx…); ошибки авторизации, баланса и модели пропускаются с уведомлением.',\n 'field.retryableErrorPatterns': 'Свои восстанавливаемые ошибки',\n 'field.retryableErrorPatternsHint': 'По одному литеральному фрагменту на строку без учёта регистра. Совпадение с кодом ошибки, HTTP-статусом или сообщением переопределяет встроенную классификацию. Указывайте только стабильный текст провайдера; широкие совпадения также запускают повтор для обычно пропускаемых ошибок аутентификации и баланса.',\n 'field.retryableErrorPatternsPlaceholder': 'Например: Upstream rejected the request as invalid',\n 'field.backoffFactor': 'Коэффициент задержки',\n 'field.backoffFactorHint': 'Множитель задержки при повторных сбоях (2 = 20 с → 40 с → 80 с…).',\n 'field.backoffMaxMs': 'Максимальная задержка (мс)',\n 'field.backoffMaxMsHint': 'Верхняя граница адаптивной задержки.',\n 'field.notify': 'Уведомления браузера',\n 'field.notifyHint': 'Уведомлять о событиях авто-продолжения и успешном сохранении настроек. Сохранение изменения этого параметра тоже подтверждает его состояние. При первом включении нужно разрешить уведомления в браузере.',\n 'stats.title': 'Статистика за сегодня',\n 'stats.sent': 'Авто-продолжений',\n 'stats.skipped': 'Пропущено (постоянные)',\n 'stats.recovered': 'Восстановлено',\n 'stats.failed': 'Сбоев после продолжения',\n 'stats.gaveUp': 'Остановлено (лимит)',\n 'stats.looped': 'Разорвано циклов',\n 'field.loopGuard': 'Защита от циклов',\n 'field.loopGuardHint': 'Распознаёт холостой ход: много коротких фраз без вызовов инструментов, повторяющиеся абзацы в одном потоковом сообщении или повтор одного инструмента — затем отменяет ход и перезапускает его с текстом цикла.',\n 'field.loopShortChars': 'Макс. длина короткой фразы (символов)',\n 'field.loopShortCharsHint': 'Сообщение модели короче этого значения считается короткой фразой (признак холостого хода).',\n 'field.loopWindowMs': 'Окно коротких фраз (мс)',\n 'field.loopWindowMsHint': 'Короткие фразы должны идти подряд внутри этого окна; обычные рассуждения, растянутые во времени, не считаются.',\n 'field.loopShortCount': 'Порог коротких фраз',\n 'field.loopShortCountHint': 'Сколько коротких фраз подряд в окне без вызова инструмента запускают защиту от циклов.',\n 'field.loopRepeatText': 'Порог одинаковых сообщений',\n 'field.loopRepeatTextHint': 'Сколько одинаковых сообщений подряд запускают защиту (сильнейший признак, любая длина; также используется для повторяющихся абзацев внутри одного потокового сообщения).',\n 'field.loopToolRepeat': 'Порог повторов инструмента',\n 'field.loopToolRepeatHint': 'Сколько вызовов одного инструмента с одинаковыми аргументами и результатом подряд запускают защиту; изменение аргументов или результата считается прогрессом.',\n 'field.loopText': 'Текст цикла',\n 'field.loopTextHint': 'Отправляется после перезапуска хода защитой от циклов; поддерживает подстановку {tool}.',\n 'default.loopText': LOCALIZED_TEXT_DEFAULTS.ru.loopText,\n 'stats.byCode': 'По коду ошибки',\n 'stats.empty': 'Сегодня ещё не было авто-продолжений.',\n 'stats.reset': 'Сбросить',\n 'recovery.title': 'Недавние попытки восстановления',\n 'recovery.hint': 'Счётчики по сессиям для последних 20 подсказок восстановления на этом хосте; очищаются при перезапуске плагина. Обычные автономные продолжения не учитываются. Отправленная подсказка не означает завершения задачи. Если восстановление повторяется, проверьте диалог и подумайте о передаче в новую сессию.',\n 'recovery.empty': 'Попыток восстановления пока нет.',\n 'recovery.count': 'Попыток в окне',\n 'recovery.consecutive': 'Подряд при последней отправке',\n 'recovery.latest': 'Последняя причина',\n 'recovery.reason.error': 'Ошибка запроса',\n 'recovery.reason.max-tokens': 'Лимит вывода',\n 'recovery.reason.silent': 'Нет видимого вывода',\n 'recovery.reason.interrupted': 'Прерывание при перезапуске хоста',\n 'recovery.reason.loop-guard': 'Защита от циклов',\n 'recovery.reason.manual': 'Ручное продолжение',\n 'pause.title': 'Приостановленные сессии',\n 'pause.none': 'Нет приостановленных сессий.',\n 'pause.clearAll': 'Снять все',\n 'pause.unpause': 'Продолжить',\n 'pause.minutes': 'мин',\n 'chrome.collapse': 'Скрыть настройки',\n 'chrome.expand': 'Показать настройки',\n 'chrome.unsaved': 'Не сохранено',\n 'chrome.readOnly': 'В этом развёртывании настройки доступны только для чтения.',\n 'chrome.unavailable': 'Настройки недоступны.',\n 'chrome.saveFailed': 'Развёртывание не приняло эти значения; они оставлены, чтобы вы их исправили.',\n 'chrome.discard': 'Отменить',\n 'chrome.saving': 'Сохранение…',\n 'chrome.save': 'Сохранить',\n 'chrome.overridden': 'Изменено',\n 'chrome.reset': 'Сбросить',\n 'chrome.invalidNumber': 'Введите число или оставьте поле пустым, чтобы использовать значение по умолчанию.',\n 'chrome.inherit': 'Наследовать',\n 'chrome.on': 'Вкл',\n 'chrome.off': 'Выкл',\n 'field.usePluginSource': 'Отправлять сообщения автопродолжения с меткой плагина',\n 'field.usePluginSourceHint': 'По умолчанию выключено, чтобы сохранить обычный источник «сообщение пользователя». Включите, чтобы помечать сообщения как пришедшие от плагина. Нажмите «Сохранить», чтобы применить.',\n 'field.resumeInterruptedChildren': 'Будить дочерние сессии после перезапуска',\n 'field.resumeInterruptedChildrenHint': 'Когда стартовый скан находит сессию субагента или участника команды, прерванную перезапуском, родительской сессии отправляется одно сообщение со списком таких детей, чтобы родитель мог продолжить или завершить их. Пропускается, если родитель завершился штатно или был остановлен вручную. По умолчанию выключено.',\n 'field.resumeGoals': 'Перевзводить цели, снятые перезапуском',\n 'field.resumeGoalsHint': 'Когда сессия автопродолжается, активная цель, снятая хостом при перезапуске, снова взводится, чтобы её раунды продолжения могли выполняться. Это действует от вашего имени, поэтому по умолчанию выключено.',\n 'field.resumePausedGoals': 'Возобновлять приостановленные цели',\n 'field.resumePausedGoalsHint': 'Также возобновлять цели, приостановленные вами вручную (требует включённого «Перевзводить цели, снятые перезапуском»). Пауза обычно осознанное решение — оставляйте выключенным, если не нужно.',\n 'field.pauseWhenOffline': 'Пауза при отсутствии сети',\n 'field.pauseWhenOfflineHint': 'Перед повтором сетевой ошибки (недоступный хост, сбой DNS, таймаут транспорта) проверять, что хост в сети. Пока сети нет, повтор ждёт, не расходуя попытки, и продолжается, когда сеть вернулась. При заданном HTTP(S)_PROXY проверяются только сетевые интерфейсы.',\n 'field.offlineCheckMs': 'Интервал повторной проверки сети (мс)',\n 'field.offlineCheckMsHint': 'Как часто отложенный повтор снова проверяет сеть. Минимум 1000.',\n 'field.loopMaxIterations': 'Лимит раундов автономного цикла',\n 'field.loopMaxIterationsHint': 'Максимум автономных раундов на сессию; 0 — без лимита. По достижении цикл останавливается и сообщает об этом один раз; отправка сообщения или повторное включение цикла начинают счёт заново.',\n};\n", "/**\n * The auto-continue settings card: edits the `auto-continue` namespace fields\n * from the legacy settings section or the bundle's plugin-manager page.\n *\n * Self-contained card chrome (disclosure header, staged fields, save/discard\n * footer) following the plugin-card store pattern of the DSH plugin\n * configuration section; styles live in `styles.ts` and use the DSH design\n * tokens so the card follows the active theme.\n */\nimport { useEffect, useId, useState, type ReactNode } from 'react';\nimport type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots';\nimport { DEFAULT_CONFIG, type AutoContinueSettings } from './engine.ts';\nimport type { SessionMode } from '../shared/core.ts';\nimport type { ComposerToggleFace, ComposerToggleState } from './composer-toggle.tsx';\nimport { NativeSwitch } from './native-switch.tsx';\nimport { createSnapshotStore, type SettingsScope, type SnapshotStore } from './dsh-store-compat.ts';\nimport {\n pausedSessions,\n readTodayStats,\n readRecoveryAttempts,\n readSessionPolicy,\n isBridgeConnected,\n resetTodayStats,\n setSessionMode,\n subscribeBridge,\n unpauseSession,\n} from './bridge.ts';\nimport type { SettingsCardKey } from './locales.ts';\nimport {\n booleanField,\n canWriteSettings,\n CardForm,\n numberField,\n textField,\n type CardActions,\n type CardFieldState,\n type CardShell,\n} from './settings-form.ts';\nimport { injectStyles } from './styles.ts';\nimport { prepareSettingsNotification, showSettingsNotification } from './settings-notifications.ts';\n\n// Styles must land during factory materialization so the module system's\n// style bookkeeping (HMR) owns them.\ninjectStyles();\n\n/**\n * Native plugin-settings primitives. Older hosts (and the unit-test fixture)\n * do not export them; the legacy hand-built card stays as the fallback.\n */\nconst nativeSettings = (() => {\n try {\n return require('@deepseek-ai/dsh-client-ui-primitives') as {\n SettingsForm?: React.ComponentType<{\n labels: { save: string; saving: string; saveFailed: string; readOnly: string; unavailable: string };\n state: CardShell;\n onSave: () => void;\n onDiscard: () => void;\n children: ReactNode;\n }>;\n SettingsValueField?: React.ComponentType<Record<string, unknown>>;\n SegmentedControl?: React.ComponentType<{\n id?: string;\n options: ReadonlyArray<{ value: string; label: string }>;\n value: string;\n onChange: (value: string) => void;\n label: string;\n disabled?: boolean;\n }>;\n };\n } catch {\n return {};\n }\n})();\n\nconst NativeSettingsForm = nativeSettings.SettingsForm;\nconst NativeValueField = nativeSettings.SettingsValueField;\nconst NativeSegmentedControl = nativeSettings.SegmentedControl;\nconst hasNativeSettings = typeof NativeSettingsForm === 'function' && typeof NativeValueField === 'function';\n\n/** What the auto-continue card renders. */\nexport interface AutoContinueSettingsCardState extends CardShell {\n /** Committed global state; a staged edit does not pause the engine yet. */\n enabled: boolean;\n /** Feedback for the last local save, including browser permission problems. */\n notificationFeedback: SettingsCardKey | undefined;\n paused: CardFieldState;\n showComposerToggle: CardFieldState;\n usePluginSource: CardFieldState;\n continueText: CardFieldState;\n continueTextMaxTokens: CardFieldState;\n resumeSilentTurns: CardFieldState;\n resumeSubagentSessions: CardFieldState;\n resumeCompletedTurns: CardFieldState;\n resumeInterruptedChildren: CardFieldState;\n resumeGoals: CardFieldState;\n resumePausedGoals: CardFieldState;\n pauseWhenOffline: CardFieldState;\n offlineCheckMs: CardFieldState;\n loopMaxIterations: CardFieldState;\n continueTextLoop: CardFieldState;\n continueTextSilent: CardFieldState;\n continueTextInterrupted: CardFieldState;\n guardTools: CardFieldState;\n guardPendingText: CardFieldState;\n guardDoneText: CardFieldState;\n graceMs: CardFieldState;\n cooldownMs: CardFieldState;\n maxConsecutive: CardFieldState;\n scanOnBoot: CardFieldState;\n scanLimit: CardFieldState;\n freshMs: CardFieldState;\n verbose: CardFieldState;\n classify: CardFieldState;\n retryableErrorPatterns: CardFieldState;\n backoffFactor: CardFieldState;\n backoffMaxMs: CardFieldState;\n notify: CardFieldState;\n loopGuard: CardFieldState;\n loopShortChars: CardFieldState;\n loopWindowMs: CardFieldState;\n loopShortCount: CardFieldState;\n loopRepeatText: CardFieldState;\n loopToolRepeat: CardFieldState;\n loopText: CardFieldState;\n}\n\n/** The registration-side face the card's slot entry injects. */\nexport interface AutoContinueSettingsCardFace extends CardActions {\n hooks: {\n /** Card snapshot bound by the renderer as useAutoContinueSettingsCard. */\n autoContinueSettingsCard: SnapshotStore<AutoContinueSettingsCardState>;\n };\n}\n\n/** Bridges the `auto-continue` scope onto the card's staged form. */\nexport class AutoContinueSettingsCardController {\n private readonly form: CardForm<AutoContinueSettings>;\n private readonly store: SnapshotStore<AutoContinueSettingsCardState>;\n private readonly composer: SnapshotStore<ComposerToggleState>;\n private readonly composerSaving = new Set<string>();\n private readonly composerFailed = new Set<string>();\n private readonly stopComposer: () => void;\n private disposed = false;\n private saveSequence = 0;\n private notificationFeedback: SettingsCardKey | undefined;\n\n /**\n * @param scope - the bound settings scope for the `auto-continue` namespace.\n */\n constructor(\n private readonly scope: SettingsScope<AutoContinueSettings>,\n private readonly getLocale: () => string,\n ) {\n this.form = new CardForm(scope, [\n booleanField('paused'),\n booleanField('showComposerToggle'),\n booleanField('usePluginSource'),\n textField('continueText'),\n textField('continueTextMaxTokens'),\n booleanField('resumeSilentTurns'),\n booleanField('resumeSubagentSessions'),\n booleanField('resumeCompletedTurns'),\n booleanField('resumeInterruptedChildren'),\n booleanField('resumeGoals'),\n booleanField('resumePausedGoals'),\n booleanField('pauseWhenOffline'),\n numberField('offlineCheckMs', 1000),\n numberField('loopMaxIterations', 0),\n textField('continueTextLoop'),\n textField('continueTextSilent'),\n textField('continueTextInterrupted'),\n booleanField('guardTools'),\n textField('guardPendingText'),\n textField('guardDoneText'),\n numberField('graceMs', 0),\n numberField('cooldownMs', 0),\n numberField('maxConsecutive', 1),\n booleanField('scanOnBoot'),\n numberField('scanLimit', 1),\n numberField('freshMs', 0),\n booleanField('verbose'),\n booleanField('classify'),\n textField('retryableErrorPatterns'),\n numberField('backoffFactor', 1),\n numberField('backoffMaxMs', 0),\n booleanField('notify'),\n booleanField('loopGuard'),\n numberField('loopShortChars', 1),\n numberField('loopWindowMs', 1000),\n numberField('loopShortCount', 2),\n numberField('loopRepeatText', 2),\n numberField('loopToolRepeat', 2),\n textField('loopText'),\n ]);\n this.store = this.form.bind(() => this.projection(), createSnapshotStore);\n this.composer = this.form.bind(() => this.composerProjection(), createSnapshotStore);\n this.stopComposer = subscribeBridge(() => this.composer.set(this.composerProjection()));\n }\n\n private projection(): AutoContinueSettingsCardState {\n return {\n ...this.form.shell(),\n enabled: !(this.scope.getSnapshot().value?.paused ?? DEFAULT_CONFIG.paused),\n notificationFeedback: this.notificationFeedback,\n paused: this.form.field('paused'),\n showComposerToggle: this.form.field('showComposerToggle'),\n usePluginSource: this.form.field('usePluginSource'),\n continueText: this.form.field('continueText'),\n continueTextMaxTokens: this.form.field('continueTextMaxTokens'),\n resumeSilentTurns: this.form.field('resumeSilentTurns'),\n resumeSubagentSessions: this.form.field('resumeSubagentSessions'),\n resumeCompletedTurns: this.form.field('resumeCompletedTurns'),\n resumeInterruptedChildren: this.form.field('resumeInterruptedChildren'),\n resumeGoals: this.form.field('resumeGoals'),\n resumePausedGoals: this.form.field('resumePausedGoals'),\n pauseWhenOffline: this.form.field('pauseWhenOffline'),\n offlineCheckMs: this.form.field('offlineCheckMs'),\n loopMaxIterations: this.form.field('loopMaxIterations'),\n continueTextLoop: this.form.field('continueTextLoop'),\n continueTextSilent: this.form.field('continueTextSilent'),\n continueTextInterrupted: this.form.field('continueTextInterrupted'),\n guardTools: this.form.field('guardTools'),\n guardPendingText: this.form.field('guardPendingText'),\n guardDoneText: this.form.field('guardDoneText'),\n graceMs: this.form.field('graceMs'),\n cooldownMs: this.form.field('cooldownMs'),\n maxConsecutive: this.form.field('maxConsecutive'),\n scanOnBoot: this.form.field('scanOnBoot'),\n scanLimit: this.form.field('scanLimit'),\n freshMs: this.form.field('freshMs'),\n verbose: this.form.field('verbose'),\n classify: this.form.field('classify'),\n retryableErrorPatterns: this.form.field('retryableErrorPatterns'),\n backoffFactor: this.form.field('backoffFactor'),\n backoffMaxMs: this.form.field('backoffMaxMs'),\n notify: this.form.field('notify'),\n loopGuard: this.form.field('loopGuard'),\n loopShortChars: this.form.field('loopShortChars'),\n loopWindowMs: this.form.field('loopWindowMs'),\n loopShortCount: this.form.field('loopShortCount'),\n loopRepeatText: this.form.field('loopRepeatText'),\n loopToolRepeat: this.form.field('loopToolRepeat'),\n loopText: this.form.field('loopText'),\n };\n }\n\n /**\n * Build the face the card's slot registration injects.\n * @returns the card's snapshot and its form actions.\n */\n inject(): AutoContinueSettingsCardFace {\n return { hooks: { autoContinueSettingsCard: this.store }, ...this.form.actions(), save: () => void this.save() };\n }\n\n private async save(): Promise<void> {\n const state = this.form.shell();\n const snapshot = this.scope.getSnapshot();\n if (this.disposed || !state.available || !state.writable || !state.dirty || state.invalid || state.saving) return;\n const sequence = ++this.saveSequence;\n const before = snapshot.value?.notify ?? DEFAULT_CONFIG.notify;\n const target = this.form.field('notify').text;\n // Start the permission prompt in the click handler, but save independently.\n const permission = prepareSettingsNotification(target === '' ? DEFAULT_CONFIG.notify : target === 'true');\n this.notificationFeedback = undefined;\n if (!await this.form.save() || this.disposed) return;\n const after = this.scope.getSnapshot().value?.notify ?? DEFAULT_CONFIG.notify;\n if (!before && !after) return;\n const result = await permission;\n // A later save or a provider teardown makes this pending confirmation stale.\n if (this.disposed || sequence !== this.saveSequence || (this.scope.getSnapshot().value?.notify ?? DEFAULT_CONFIG.notify) !== after) return;\n this.notificationFeedback = showSettingsNotification(before === after ? 'saved' : after ? 'enabled' : 'disabled', this.getLocale(), result);\n this.store.set(this.projection());\n }\n\n injectComposer(sessionId: string): ComposerToggleFace {\n return { hooks: { autoContinueComposer: this.composer }, sessionId, setMode: (mode) => void this.setMode(sessionId, mode) };\n }\n\n private composerProjection(): ComposerToggleState {\n const snapshot = this.scope.getSnapshot();\n const policy = readSessionPolicy();\n const connected = isBridgeConnected();\n return {\n visible: snapshot.status === 'ready' && (snapshot.value?.showComposerToggle ?? DEFAULT_CONFIG.showComposerToggle),\n policy,\n reconnecting: policy !== undefined && !connected,\n writable: connected && canWriteSettings(snapshot) && policy?.writable === true,\n saving: new Set(this.composerSaving),\n failed: new Set(this.composerFailed),\n };\n }\n\n private async setMode(sessionId: string, mode: SessionMode): Promise<void> {\n if (this.disposed || !sessionId || this.composerSaving.has(sessionId) || !this.composerProjection().writable) return;\n this.composerSaving.add(sessionId);\n this.composerFailed.delete(sessionId);\n this.composer.set(this.composerProjection());\n try {\n await setSessionMode(sessionId, mode);\n } catch {\n this.composerFailed.add(sessionId);\n } finally {\n this.composerSaving.delete(sessionId);\n if (!this.disposed) this.composer.set(this.composerProjection());\n }\n }\n\n /** Release this card's subscription to the provider-owned settings form. */\n dispose(): void {\n this.disposed = true;\n this.stopComposer();\n this.form.dispose();\n }\n}\n\n/** Props the renderer binds for the auto-continue plugin-configuration card. */\nexport type AutoContinueSettingsCardProps =\n PropsLocale<'auto-continue'> & InjectFace<AutoContinueSettingsCardFace>;\n\n/** The bundle page supplies no list container, unlike the legacy settings slot. */\nexport function AutoContinueSettingsPage(props: AutoContinueSettingsCardProps) {\n return (\n <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>\n <AutoContinueSettingsCard {...props} />\n </ul>\n );\n}\n\ntype FieldName = Exclude<keyof AutoContinueSettingsCardState, keyof CardShell | 'enabled' | 'notificationFeedback'>;\nconst groups = [\n { id: 'general', fields: ['paused', 'showComposerToggle', 'usePluginSource', 'resumeSilentTurns', 'resumeSubagentSessions', 'resumeCompletedTurns', 'loopMaxIterations', 'notify'] },\n { id: 'recovery', fields: ['graceMs', 'cooldownMs', 'maxConsecutive', 'classify', 'retryableErrorPatterns', 'backoffFactor', 'backoffMaxMs', 'pauseWhenOffline', 'offlineCheckMs', 'resumeGoals', 'resumePausedGoals'] },\n { id: 'startup', fields: ['scanOnBoot', 'resumeInterruptedChildren', 'scanLimit', 'freshMs'] },\n { id: 'prompts', fields: ['continueText', 'continueTextMaxTokens', 'continueTextSilent', 'continueTextInterrupted', 'continueTextLoop', 'guardPendingText', 'guardDoneText', 'loopText'] },\n { id: 'safety', fields: ['guardTools', 'loopGuard', 'loopShortChars', 'loopWindowMs', 'loopShortCount', 'loopRepeatText', 'loopToolRepeat'] },\n { id: 'status', fields: ['verbose'] },\n] as const satisfies ReadonlyArray<{ id: string; fields: readonly FieldName[] }>;\ntype Category = typeof groups[number]['id'];\nconst textDefaults: Partial<Record<FieldName, SettingsCardKey>> = {\n continueText: 'default.continueText', continueTextMaxTokens: 'default.continueTextMaxTokens',\n continueTextSilent: 'default.continueTextSilent', continueTextLoop: 'default.continueTextLoop',\n continueTextInterrupted: 'default.continueTextInterrupted',\n guardPendingText: 'default.guardPendingText', guardDoneText: 'default.guardDoneText', loopText: 'default.loopText',\n};\n\nconst REPOSITORY_URL = 'https://github.com/HsiangNianian/dsh-auto-continue';\n\nfunction RepositoryInvite({ t }: { t: (key: SettingsCardKey) => string }) {\n return <p className=\"dshAcInvite\">\n <span className=\"dshAcInviteStar\" aria-hidden=\"true\">★</span>\n <span>{t('repo.star')}</span>\n <a className=\"dshAcRepoLink\" href={REPOSITORY_URL} target=\"_blank\" rel=\"noopener noreferrer\" aria-label={t('repo.aria')}>\n <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M12 2.4a9.8 9.8 0 0 0-3.1 19.1c.5.1.7-.2.7-.5v-1.9c-2.8.6-3.4-1.2-3.4-1.2-.5-1.1-1.1-1.4-1.1-1.4-.9-.6.1-.6.1-.6 1 0 1.5 1 1.5 1 .9 1.5 2.3 1.1 2.9.8.1-.6.4-1.1.6-1.3-2.2-.3-4.6-1.1-4.6-4.9 0-1.1.4-2 1-2.7-.1-.3-.4-1.3.1-2.7 0 0 .8-.3 2.8 1a9.5 9.5 0 0 1 5 0c1.9-1.3 2.8-1 2.8-1 .5 1.4.2 2.4.1 2.7.6.7 1 1.6 1 2.7 0 3.8-2.3 4.6-4.6 4.9.4.3.7.9.7 1.8V21c0 .3.2.6.7.5A9.8 9.8 0 0 0 12 2.4Z\" /></svg>\n {t('repo.link')}\n <svg className=\"dshAcExternal\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M6 3h7v7M13 3 7 9M11 9v3a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h3\" /></svg>\n </a>\n </p>;\n}\n\n/** Controls edit the existing staged form; navigation never owns or discards drafts. */\nfunction SettingField({ name, id, state, actions, disabled, t }: {\n name: FieldName; id: string; state: CardFieldState; actions: CardActions; disabled: boolean;\n t: (key: SettingsCardKey) => string;\n}) {\n const boolean = typeof DEFAULT_CONFIG[name] === 'boolean';\n const numeric = typeof DEFAULT_CONFIG[name] === 'number';\n const label = t(`field.${name}` as SettingsCardKey);\n const hint = t(`field.${name}Hint` as SettingsCardKey);\n const value = state.text === '' ? DEFAULT_CONFIG[name] : state.text === 'true';\n const placeholderKey = textDefaults[name];\n const placeholder = placeholderKey ? t(placeholderKey) : name === 'retryableErrorPatterns' ? t('field.retryableErrorPatternsPlaceholder') : String(DEFAULT_CONFIG[name]);\n const common = { id, disabled, 'aria-describedby': `${id}-hint`, 'aria-invalid': state.invalid || undefined, value: state.text, onChange: (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => actions.edit(name, event.target.value) };\n return <div className={`dshAcField${!boolean && !numeric ? ' dshAcFieldText' : ''}`} data-field={name}>\n <div className=\"dshAcFieldCopy\">\n {boolean ? <span className=\"dshAcLabel\">{label}</span> : <label className=\"dshAcLabel\" htmlFor={id}>{label}</label>}\n <p className={state.invalid ? 'dshAcInvalid' : 'dshAcHint'} id={`${id}-hint`}>{state.invalid ? t('chrome.invalidNumber') : hint}</p>\n </div>\n <div className=\"dshAcFieldControl\">\n {state.overridden && <button type=\"button\" className=\"dshAcReset\" disabled={disabled} aria-label={`${t('chrome.reset')}: ${label}`} onClick={() => actions.resetField(name)}>{t('chrome.reset')}</button>}\n {name === 'resumeCompletedTurns' ? <select id={id} className=\"dshAcMode\" aria-label={label} aria-describedby={`${id}-hint`}\n disabled={disabled} value={String(value)} onChange={event => actions.edit(name, event.target.value)}>\n <option value=\"false\">{t('composer.recover')}</option><option value=\"true\">{t('composer.loop')}</option>\n </select> : boolean ? <span className=\"dshAcSwitchTarget\"><NativeSwitch label={label} title={hint} disabled={disabled}\n checked={name === 'paused' ? !value : Boolean(value)} onChange={checked => actions.edit(name, String(name === 'paused' ? !checked : checked))} /></span>\n : numeric ? <input {...common} className=\"dshAcInput dshAcNumber\" type=\"text\" inputMode=\"numeric\" placeholder={placeholder} />\n : <textarea {...common} className=\"dshAcInput dshAcTextArea\" rows={name === 'retryableErrorPatterns' ? 3 : 2} placeholder={placeholder} />}\n </div>\n </div>;\n}\n\n\n/** One field rendered with the host's own settings primitives. */\nfunction NativeSettingField({ name, id, state, actions, disabled, t }: {\n name: FieldName; id: string; state: CardFieldState; actions: CardActions; disabled: boolean;\n t: (key: SettingsCardKey) => string;\n}) {\n const boolean = typeof DEFAULT_CONFIG[name] === 'boolean';\n const numeric = typeof DEFAULT_CONFIG[name] === 'number';\n const label = t(`field.${name}` as SettingsCardKey);\n const hint = t(`field.${name}Hint` as SettingsCardKey);\n const value = state.text === '' ? DEFAULT_CONFIG[name] : state.text === 'true';\n const placeholderKey = textDefaults[name];\n const placeholder = placeholderKey ? t(placeholderKey) : name === 'retryableErrorPatterns' ? t('field.retryableErrorPatternsPlaceholder') : String(DEFAULT_CONFIG[name]);\n const reset = state.overridden\n ? <button type=\"button\" className=\"dshAcNativeReset\" disabled={disabled} aria-label={`${t('chrome.reset')}: ${label}`} onClick={() => actions.resetField(name)}>{t('chrome.reset')}</button>\n : null;\n\n if (name === 'resumeCompletedTurns') {\n const items = [{ value: 'false', label: t('composer.recover') }, { value: 'true', label: t('composer.loop') }];\n return <div className=\"dshAcNativeField\" data-field={name}>\n <div className=\"dshAcNativeHead\"><label className=\"dshAcNativeLabel\" htmlFor={id}>{label}</label>{reset}</div>\n {NativeSegmentedControl\n ? <NativeSegmentedControl id={id} options={items} value={value ? 'true' : 'false'} onChange={next => actions.edit(name, next)} label={label} disabled={disabled} />\n : <select id={id} className=\"dshAcMode\" aria-label={label} disabled={disabled} value={String(value)} onChange={event => actions.edit(name, event.target.value)}>\n <option value=\"false\">{t('composer.recover')}</option><option value=\"true\">{t('composer.loop')}</option>\n </select>}\n <p className=\"dshAcNativeHint\" id={`${id}-hint`}>{hint}</p>\n </div>;\n }\n\n if (boolean) {\n return <div className=\"dshAcNativeField\" data-field={name}>\n <div className=\"dshAcNativeToggleRow\">\n <label className=\"dshAcNativeLabel\" htmlFor={id}>{label}</label>\n <span className=\"dshAcNativeActions\">\n {reset}\n <NativeSwitch label={label} title={hint} disabled={disabled}\n checked={name === 'paused' ? !value : Boolean(value)}\n onChange={checked => actions.edit(name, String(name === 'paused' ? !checked : checked))} />\n </span>\n </div>\n <p className=\"dshAcNativeHint\" id={`${id}-hint`}>{hint}</p>\n </div>;\n }\n\n if (numeric) {\n const ValueField = NativeValueField!;\n return <ValueField id={id} label={label} hint={hint} overriddenLabel={t('chrome.overridden')}\n resetLabel={t('chrome.reset')} invalidLabel={t('chrome.invalidNumber')} disabled={disabled}\n numeric {...state} placeholder={placeholder}\n onEdit={(text: string) => actions.edit(name, text)} onReset={() => actions.resetField(name)} />;\n }\n\n return <div className=\"dshAcNativeField\" data-field={name}>\n <div className=\"dshAcNativeHead\"><label className=\"dshAcNativeLabel\" htmlFor={id}>{label}</label>{reset}</div>\n <textarea id={id} className=\"dshAcNativeTextarea\" rows={name === 'retryableErrorPatterns' ? 3 : 2}\n disabled={disabled} value={state.text} placeholder={placeholder} aria-invalid={state.invalid || undefined}\n aria-describedby={`${id}-hint`} onChange={event => actions.edit(name, event.target.value)} />\n <p className=\"dshAcNativeHint\" id={`${id}-hint`}>{state.invalid ? t('chrome.invalidNumber') : hint}</p>\n </div>;\n}\n\n/** 实时面板: 今日统计 + 已暂停会话。浏览器本地状态, 每 5 秒刷新一次。 */\nfunction LivePanels(props: { t: (key: SettingsCardKey) => string }) {\n const { t } = props;\n const [, refresh] = useState(0);\n useEffect(() => {\n // host 状态桥推送时刷新; 5 秒轮询兜底(桥短暂断线时)\n const unsubscribe = subscribeBridge(() => refresh((value) => value + 1));\n const timer = setInterval(() => refresh((value) => value + 1), 5000);\n return () => {\n unsubscribe();\n clearInterval(timer);\n };\n }, []);\n const stats = readTodayStats();\n const hasStats = stats.sent + stats.skipped + stats.recovered + stats.failed + stats.gaveUp + stats.looped > 0;\n const codes = Object.entries(stats.byCode)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5);\n const paused = pausedSessions();\n const attempts = readRecoveryAttempts();\n const sessions = [...new Set(attempts.map(attempt => attempt.sessionId))];\n return (\n <>\n <section className=\"dshAcPanel\">\n <div className=\"dshAcPanelHead\">\n <span className=\"dshAcPanelTitle\">{t('stats.title')}</span>\n {hasStats ? (\n <button\n type=\"button\"\n className=\"dshAcReset\"\n onClick={() => {\n resetTodayStats();\n refresh((value) => value + 1);\n }}\n >\n {t('stats.reset')}\n </button>\n ) : null}\n </div>\n {!hasStats ? (\n <p className=\"dshAcHint\">{t('stats.empty')}</p>\n ) : (\n <>\n <dl className=\"dshAcStats\">\n <div><dt>{t('stats.sent')}</dt><dd>{stats.sent}</dd></div>\n <div><dt>{t('stats.recovered')}</dt><dd>{stats.recovered}</dd></div>\n <div><dt>{t('stats.failed')}</dt><dd>{stats.failed}</dd></div>\n <div><dt>{t('stats.skipped')}</dt><dd>{stats.skipped}</dd></div>\n <div><dt>{t('stats.gaveUp')}</dt><dd>{stats.gaveUp}</dd></div>\n <div><dt>{t('stats.looped')}</dt><dd>{stats.looped}</dd></div>\n </dl>\n {codes.length > 0 ? (\n <div className=\"dshAcCodes\">\n <span className=\"dshAcHint\">{t('stats.byCode')}:</span>\n {codes.map(([code, count]) => (\n <span key={code} className=\"dshAcCode\">\n {code} ×{count}\n </span>\n ))}\n </div>\n ) : null}\n </>\n )}\n </section>\n <section className=\"dshAcPanel\">\n <div className=\"dshAcPanelHead\">\n <span className=\"dshAcPanelTitle\">{t('recovery.title')}</span>\n </div>\n <p className=\"dshAcHint\">{t('recovery.hint')}</p>\n {sessions.length === 0 ? <p className=\"dshAcHint\">{t('recovery.empty')}</p> : (\n <ul className=\"dshAcPauseList\">\n {sessions.map(sessionId => {\n const recent = attempts.filter(attempt => attempt.sessionId === sessionId);\n const latest = recent[0]!;\n return (\n <li key={sessionId}>\n <div className=\"dshAcRecovery\">\n <span className=\"dshAcPauseId\">{sessionId}</span>\n <span>{t('recovery.count')}: {recent.length} · {t('recovery.consecutive')}: {latest.consecutive}</span>\n <span>{t('recovery.latest')}: {t(`recovery.reason.${latest.reason}`)}</span>\n <time className=\"dshAcHint\" dateTime={new Date(latest.at).toISOString()}>{new Date(latest.at).toLocaleString()}</time>\n </div>\n </li>\n );\n })}\n </ul>\n )}\n </section>\n <section className=\"dshAcPanel\">\n <div className=\"dshAcPanelHead\">\n <span className=\"dshAcPanelTitle\">{t('pause.title')}</span>\n {paused.length > 0 ? (\n <button\n type=\"button\"\n className=\"dshAcReset\"\n onClick={() => {\n for (const item of paused) unpauseSession(item.sessionId);\n refresh((value) => value + 1);\n }}\n >\n {t('pause.clearAll')}\n </button>\n ) : null}\n </div>\n {paused.length === 0 ? (\n <p className=\"dshAcHint\">{t('pause.none')}</p>\n ) : (\n <ul className=\"dshAcPauseList\">\n {paused.map((item) => (\n <li key={item.sessionId}>\n <span className=\"dshAcPauseId\">{item.sessionId.slice(0, 8)}…</span>\n <span className=\"dshAcHint\">\n {Math.max(1, Math.ceil((item.until - Date.now()) / 60000))} {t('pause.minutes')}\n </span>\n <button\n type=\"button\"\n className=\"dshAcReset\"\n onClick={() => {\n unpauseSession(item.sessionId);\n refresh((value) => value + 1);\n }}\n >\n {t('pause.unpause')}\n </button>\n </li>\n ))}\n </ul>\n )}\n </section>\n </>\n );\n}\n\n/** Native category layout; the plugin manager above already owns the title, version and status. */\nexport function AutoContinueSettingsCard(props: AutoContinueSettingsCardProps) {\n const { t } = props;\n const state = props.useAutoContinueSettingsCard(snapshot => snapshot);\n const [active, setActive] = useState<Category>('general');\n const prefix = useId();\n const group = groups.find(item => item.id === active)!;\n const native = hasNativeSettings;\n if (!state.available) return null;\n return <li className=\"dshAcCard\">\n <RepositoryInvite t={t} />\n {!native && !state.writable && <p className=\"dshAcReadOnly\" role=\"status\">{t('chrome.readOnly')}</p>}\n <div className=\"dshAcLayout\">\n <div className=\"dshAcNav\" role=\"tablist\" aria-label={t('chrome.categories')}>\n {groups.map((item, index) => {\n const invalid = item.fields.some(name => state[name].invalid);\n const title = t(`category.${item.id}.title`);\n return <button type=\"button\" role=\"tab\" key={item.id} id={`${prefix}-tab-${item.id}`} data-category={item.id}\n aria-controls={`${prefix}-panel-${item.id}`} aria-selected={active === item.id} tabIndex={active === item.id ? 0 : -1}\n aria-label={invalid ? `${title}: ${t('chrome.invalidNumber')}` : title}\n onClick={() => setActive(item.id)} onKeyDown={event => {\n const offset = ['ArrowRight', 'ArrowDown'].includes(event.key) ? 1 : ['ArrowLeft', 'ArrowUp'].includes(event.key) ? -1 : 0;\n if (!offset && event.key !== 'Home' && event.key !== 'End') return;\n event.preventDefault();\n const next = event.key === 'Home' ? 0 : event.key === 'End' ? groups.length - 1 : (index + offset + groups.length) % groups.length;\n setActive(groups[next]!.id);\n const button = event.currentTarget.parentElement?.querySelectorAll<HTMLButtonElement>('[role=\"tab\"]')[next];\n button?.focus();\n button?.scrollIntoView({ block: 'nearest', inline: 'nearest' });\n }}>{title}{invalid && <span className=\"dshAcInvalidMark\" aria-hidden=\"true\">!</span>}</button>;\n })}\n </div>\n <section className=\"dshAcCategory\" role=\"tabpanel\" id={`${prefix}-panel-${active}`} aria-labelledby={`${prefix}-tab-${active}`}>\n <div className=\"dshAcCategoryHeading\"><h3>{t(`category.${active}.title`)}</h3><p>{t(`category.${active}.description`)}</p></div>\n {native ? (\n <NativeSettingsForm labels={{\n save: t('chrome.save'), saving: t('chrome.saving'), saveFailed: t('chrome.saveFailed'),\n readOnly: t('chrome.readOnly'), unavailable: t('chrome.unavailable'),\n }} state={state} onSave={props.save} onDiscard={props.discard}>\n <div className=\"dshAcNativeFields\">\n {group.fields.map(name => <NativeSettingField key={name} name={name} id={`${prefix}-${name}`} state={state[name]} actions={props} disabled={!state.writable} t={t} />)}\n {active === 'status' && <LivePanels t={t} />}\n </div>\n </NativeSettingsForm>\n ) : (\n <>\n {group.fields.map(name => <SettingField key={name} name={name} id={`${prefix}-${name}`} state={state[name]} actions={props} disabled={!state.writable} t={t} />)}\n {active === 'status' && <LivePanels t={t} />}\n <footer className=\"dshAcFooter\" data-dirty={state.dirty}>\n <p className={state.failed || state.invalid ? 'dshAcInvalid' : 'dshAcHint'} role=\"status\">{t(state.failed ? 'chrome.saveFailed' : state.invalid ? 'chrome.invalidNumber' : state.saving ? 'chrome.saving' : state.dirty ? 'chrome.unsaved' : state.notificationFeedback ?? 'chrome.saved')}</p>\n <div><button type=\"button\" className=\"dshAcDiscard\" disabled={!state.dirty || state.saving} onClick={props.discard}>{t('chrome.discard')}</button><button type=\"button\" className=\"dshAcSave\" disabled={!state.dirty || state.invalid || state.saving || !state.writable} onClick={props.save}>{t(state.saving ? 'chrome.saving' : 'chrome.save')}</button></div>\n </footer>\n </>\n )}\n </section>\n </div>\n </li>;\n}\n", "import type { ComponentType } from 'react';\n\ninterface SwitchProps {\n checked: boolean;\n onChange: (checked: boolean) => void;\n label: string;\n disabled?: boolean;\n title?: string;\n}\n\n// DSH 0.1.0-rc.7 predates this export. Keep its settings page usable while\n// current hosts render their own Switch, including the active theme's styles.\nfunction legacySwitch(props: SwitchProps) {\n return (\n <button type=\"button\" role=\"switch\" className=\"dshAcSwitch\"\n aria-checked={props.checked} aria-label={props.label} disabled={props.disabled}\n title={props.title} onClick={() => props.onChange(!props.checked)}>\n <span />\n </button>\n );\n}\n\nfunction resolveSwitch(): ComponentType<SwitchProps> {\n try {\n const { Switch } = require('@deepseek-ai/dsh-client-ui-primitives') as { Switch?: ComponentType<SwitchProps> };\n if (typeof Switch === 'function') return Switch;\n } catch {\n // Legacy hosts can omit the primitives module from their client graph.\n }\n return legacySwitch;\n}\n\nexport const NativeSwitch = resolveSwitch();\n", "/**\n * Snapshot-store bridge across the two public DSH client module layouts.\n *\n * DSH 0.1.2 moved the store engine from the dynamic\n * `@deepseek-ai/dsh-client-runtime/client` row into the shell-seeded\n * `@deepseek-ai/dsh-client-store` platform module. Keep the probe dynamic so\n * esbuild does not turn both candidates into eager top-level requires: the\n * loader must only resolve the module that exists in the running DSH cohort.\n */\n\n/** Writable observable snapshot used by the settings card. */\nexport interface SnapshotStore<T> {\n getSnapshot(): T;\n subscribe(listener: () => void): () => void;\n update(mutator: (draft: T) => void): void;\n set(next: T): void;\n}\n\n/** Settings state consumed by the staged form. */\nexport interface SettingsScopeSnapshot<T> {\n status: 'loading' | 'ready' | 'unavailable';\n value: T | undefined;\n base: unknown;\n user: unknown;\n revision: number | undefined;\n writable: boolean;\n mode?: 'host' | 'memory';\n}\n\n/** Stable subset shared by settings scopes and DSH 0.1.7 configuration forms. */\nexport interface SettingsScope<T> {\n getSnapshot(): SettingsScopeSnapshot<T>;\n subscribe(listener: () => void): () => void;\n set(field: string, value: unknown): Promise<void | boolean>;\n unset(field: string): Promise<void | boolean>;\n}\n\ninterface SnapshotStoreModule {\n createSnapshotStore<T>(\n init: T,\n options?: { flush?: 'raf' | 'sync'; persist?: { name: string } },\n ): SnapshotStore<T>;\n}\n\nfunction resolveSnapshotStore(): SnapshotStoreModule {\n // String assembly is intentional: it preserves the lazy try/fallback in the\n // emitted client bundle instead of letting the bundler resolve both names.\n const current = ['@deepseek-ai/dsh-client', '-store'].join('');\n const legacy = ['@deepseek-ai/dsh-client-runtime', '/client'].join('');\n try {\n return require(current) as SnapshotStoreModule;\n } catch {\n return require(legacy) as SnapshotStoreModule;\n }\n}\n\nexport const { createSnapshotStore } = resolveSnapshotStore();\n", "/**\n * Host status bridge, browser side.\n *\n * Subscribes to the host engine's `/api/auto-continue-bridge` SSE stream:\n * notifications (shown via the browser Notification API, action buttons POST\n * to `/api/auto-continue-action`) and runtime state (today's stats and the\n * paused-sessions list) consumed by the settings card's live panels.\n */\n\nimport type { RecoveryAttempt, SessionMode, SessionPolicy } from '../shared/core.ts';\n\n/** 今日统计视图(与 host 引擎的 DayStats 对应)。 */\nexport interface DayStatsView {\n date: string;\n sent: number;\n skipped: number;\n recovered: number;\n failed: number;\n gaveUp: number;\n looped: number;\n byCode: Record<string, number>;\n}\n\n/** 已暂停会话视图。 */\nexport interface PausedSessionView {\n sessionId: string;\n until: number;\n}\n\ninterface BridgeState {\n stats: DayStatsView;\n paused: PausedSessionView[];\n recoveryAttempts: RecoveryAttempt[];\n sessionPolicy?: SessionPolicy;\n /** False while the SSE stream is down; the last known policy stays readable but not writable. */\n connected: boolean;\n}\n\ninterface BridgeNotice {\n id: string;\n title: string;\n body: string;\n sessionId?: string;\n actions: { action: string; title: string }[];\n at: number;\n}\n\nconst EMPTY_STATS: DayStatsView = {\n date: '',\n sent: 0,\n skipped: 0,\n recovered: 0,\n failed: 0,\n gaveUp: 0,\n looped: 0,\n byCode: {},\n};\n\nlet state: BridgeState = { stats: EMPTY_STATS, paused: [], recoveryAttempts: [], connected: false };\nconst listeners = new Set<() => void>();\n\n/** 当前桥状态里的已暂停会话(卡片面板用)。 */\nexport function pausedSessions(): PausedSessionView[] {\n return state.paused;\n}\n\n/** 当前桥状态里的今日统计(卡片面板用)。 */\nexport function readTodayStats(): DayStatsView {\n return state.stats;\n}\n\nexport function readRecoveryAttempts(): RecoveryAttempt[] {\n return state.recoveryAttempts;\n}\n\n/** Last policy the host sent. It survives a bridge reconnect, so check {@link isBridgeConnected} before writing. */\nexport function readSessionPolicy(): SessionPolicy | undefined {\n return state.sessionPolicy;\n}\n\nexport function isBridgeConnected(): boolean {\n return state.connected;\n}\n\nexport async function setSessionMode(sessionId: string, mode: SessionMode): Promise<void> {\n if (!state.connected || !state.sessionPolicy?.writable) throw new Error('Session settings are unavailable');\n const response = await fetch('/api/auto-continue-action', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ action: 'set-session-mode', sessionId, mode }),\n });\n const result = await response.json();\n if (!response.ok || result?.ok !== true || result.sessionId !== sessionId || result.mode !== mode) {\n throw new Error('Session mode was not saved');\n }\n}\n\n/** 清零今日统计(经动作端点交给 host 引擎执行)。 */\nexport function resetTodayStats(): void {\n void postAction({ action: 'reset-stats' });\n}\n\n/** 解除某个会话的暂停(经动作端点交给 host 引擎执行)。 */\nexport function unpauseSession(sessionId: string): void {\n void postAction({ action: 'unpause', sessionId });\n}\n\n/** 订阅桥状态变化(卡片面板刷新用)。 */\nexport function subscribeBridge(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/** 通知按钮动作回传 host(立即续跑 / 暂停该会话 1 小时 / 解除暂停 / 清零统计)。 */\nasync function postAction(payload: { action: string; sessionId?: string }): Promise<void> {\n try {\n await fetch('/api/auto-continue-action', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n });\n } catch {\n /* host 不可达时静默 */\n }\n}\n\nfunction handleEvent(event: { type: string; notice?: BridgeNotice; stats?: DayStatsView; paused?: PausedSessionView[]; recoveryAttempts?: RecoveryAttempt[]; sessionPolicy?: SessionPolicy }): void {\n if (event.type === 'state') {\n const policy = event.sessionPolicy;\n state = {\n stats: event.stats ?? EMPTY_STATS,\n paused: event.paused ?? [],\n recoveryAttempts: event.recoveryAttempts ?? [],\n sessionPolicy: policy && typeof policy.modes === 'object' && policy.modes !== null && !Array.isArray(policy.modes) &&\n (policy.defaultMode === 'recover' || policy.defaultMode === 'loop') && typeof policy.paused === 'boolean' && typeof policy.writable === 'boolean'\n ? policy : undefined,\n connected: true,\n };\n for (const listener of listeners) listener();\n } else if (event.type === 'notice' && event.notice !== undefined) {\n showNotification(event.notice);\n }\n}\n\n/** 浏览器通知: 展示 host 通知并挂动作按钮。 */\nfunction showNotification(notice: BridgeNotice): void {\n try {\n const N = (globalThis as { Notification?: unknown }).Notification as\n | (new (t: string, o: { body: string; actions?: { action: string; title: string }[] }) => unknown)\n | undefined;\n if (typeof N === 'undefined') return;\n const permission = (N as unknown as { permission?: string }).permission;\n const create = (): void => {\n const instance = new N(notice.title, {\n body: notice.body,\n ...(notice.actions.length > 0 ? { actions: notice.actions } : {}),\n });\n const target = instance as {\n onclick?: (() => void) | null;\n onaction?: ((event: { action: string }) => void) | null;\n };\n target.onclick = () => {\n try {\n (globalThis as { focus?: () => void }).focus?.();\n } catch {\n /* ignore */\n }\n };\n target.onaction = (event) => {\n if (notice.sessionId !== undefined) {\n void postAction({ action: event.action, sessionId: notice.sessionId });\n }\n };\n };\n if (permission === 'granted') {\n create();\n } else if (permission === 'default') {\n void (N as unknown as { requestPermission?: () => Promise<string> }).requestPermission?.()\n .then((result) => {\n if (result === 'granted') create();\n })\n .catch(() => {});\n }\n } catch {\n /* 通知失败不影响核心逻辑 */\n }\n}\n\n/**\n * 启动桥订阅(带断线重连), 返回停止函数。\n * 由 client apply 的 ctx.effect 持有。\n */\nexport function startBridge(): () => void {\n let stopped = false;\n let controller: AbortController | undefined;\n // A dropped stream (engine rebuild, sleep, a proxy closing an idle socket) keeps the\n // last policy on screen so the composer does not flash to \"off\" while reconnecting (#86).\n const disconnected = () => {\n if (!state.connected) return;\n state = { ...state, connected: false };\n for (const listener of listeners) listener();\n };\n const reset = () => {\n state = { ...state, sessionPolicy: undefined, connected: false };\n for (const listener of listeners) listener();\n };\n reset();\n let failures = 0;\n\n const loop = async (): Promise<void> => {\n while (!stopped) {\n controller = new AbortController();\n try {\n const response = await fetch('/api/auto-continue-bridge', { signal: controller.signal });\n if (!response.ok || response.body === null) throw new Error(`bridge HTTP ${response.status}`);\n failures = 0;\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n if (done || stopped) break;\n buffer += decoder.decode(value, { stream: true });\n let idx = buffer.indexOf('\\n\\n');\n while (idx !== -1) {\n const chunk = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n for (const line of chunk.split('\\n')) {\n if (line.startsWith('data: ')) {\n try {\n handleEvent(JSON.parse(line.slice(6)) as Parameters<typeof handleEvent>[0]);\n } catch {\n /* 忽略坏帧 */\n }\n }\n }\n idx = buffer.indexOf('\\n\\n');\n }\n }\n } catch {\n /* 断线: 退避重连 */\n }\n if (!stopped) {\n disconnected();\n // The first retry is quick: most drops are the host rebuilding its engine.\n const delay = failures === 0 ? 500 : 3000;\n failures += 1;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n };\n void loop();\n\n return () => {\n stopped = true;\n controller?.abort();\n reset();\n };\n}\n", "/**\n * Staged form model behind the plugin settings card — a self-contained\n * implementation of the plugin-card store pattern used by the DSH plugin\n * configuration section.\n *\n * A card stages what the user types and writes it only when they save. Each\n * settings write is a durable, revision-fenced document mutation, so staging\n * keeps what is on screen exactly what a save would store. A field shows its\n * effective value — the user layer over the composition layer over the schema\n * default — and whether the user layer carries it (presence, not value\n * equality, marks an override).\n */\nimport type { SettingsScope, SettingsScopeSnapshot, SnapshotStore } from './dsh-store-compat.ts';\n\n/** Current forms omit mode; legacy memory scopes still cannot persist settings. */\nexport function canWriteSettings(snapshot: SettingsScopeSnapshot<unknown>): boolean {\n return snapshot.status === 'ready' && snapshot.writable && (snapshot.mode === undefined || snapshot.mode === 'host');\n}\n\n/** The write one field's staged text performs when the card is saved. */\nexport type FieldWrite = { kind: 'set'; value: unknown } | { kind: 'clear' };\n\n/** How one field converts between its stored value and its draft text. */\nexport interface CardFieldSpec {\n /** Field name inside the namespace section. */\n field: string;\n /** Render a stored value as draft text; the empty string when the section carries none. */\n format: (value: unknown) => string;\n /**\n * The write this draft text stages, or undefined when the text is not a\n * value this field accepts — which blocks the save rather than discarding it.\n */\n parse: (text: string) => FieldWrite | undefined;\n}\n\n/** One field as the card's control renders it. */\nexport interface CardFieldState {\n /** Draft text the control renders. */\n text: string;\n /** Whether saving would leave a user-layer entry for this field. */\n overridden: boolean;\n /** Whether the draft is not a value this field accepts, which blocks saving. */\n invalid: boolean;\n}\n\n/** Form state every plugin card shares. */\nexport interface CardShell {\n /** False while the namespace is not served to this client; the card renders nothing. */\n available: boolean;\n /** Whether the Host document accepts writes. */\n writable: boolean;\n /** Whether the form holds edits that a save would write. */\n dirty: boolean;\n /** Whether any staged draft is invalid, which blocks the save. */\n invalid: boolean;\n /** Whether a save is crossing the wire. */\n saving: boolean;\n /** Whether the last save did not land as staged; cleared by the next edit or save. */\n failed: boolean;\n}\n\n/** The write actions the card's slot entry injects. */\nexport interface CardActions {\n /** Stage draft text for one field. */\n edit: (field: string, text: string) => void;\n /** Stage a clear, so saving lets the field re-inherit the composition layer. */\n resetField: (field: string) => void;\n /** Write every staged edit, then re-seed from what the Host accepted. */\n save: () => void;\n /** Drop every staged edit. */\n discard: () => void;\n}\n\n/** A whole-number field. An empty draft clears the field; a non-number or out-of-range draft blocks the save. */\nexport function numberField(field: string, min = 0): CardFieldSpec {\n return {\n field,\n format: (value) => (typeof value === 'number' ? String(value) : ''),\n parse: (text) => {\n const trimmed = text.trim();\n if (trimmed === '') return { kind: 'clear' };\n const parsed = Number(trimmed);\n if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < min) return undefined;\n return { kind: 'set', value: parsed };\n },\n };\n}\n\n/** A free-text field. An empty draft clears the field, so emptying the control and saving is the same gesture as resetting it. */\nexport function textField(field: string): CardFieldSpec {\n return {\n field,\n format: (value) => (typeof value === 'string' ? value : ''),\n parse: (text) => {\n const trimmed = text.trim();\n return trimmed === '' ? { kind: 'clear' } : { kind: 'set', value: trimmed };\n },\n };\n}\n\n/** A boolean field, edited through true/false draft text; an empty draft inherits. */\nexport function booleanField(field: string): CardFieldSpec {\n return {\n field,\n format: (value) => (typeof value === 'boolean' ? String(value) : ''),\n parse: (text) => {\n const trimmed = text.trim();\n if (trimmed === '') return { kind: 'clear' };\n if (trimmed === 'true') return { kind: 'set', value: true };\n if (trimmed === 'false') return { kind: 'set', value: false };\n return undefined;\n },\n };\n}\n\n/** One field's staged edit. */\ninterface StagedEdit {\n /** Draft text the control renders. */\n text: string;\n /** True when this edit clears the field whatever text it shows. */\n clear: boolean;\n}\n\n/**\n * Stages one card's edits over one settings namespace and writes them on save.\n *\n * The Host is the only authority on whether a value was accepted, so the\n * outcome is read back from the section rather than predicted here. A save\n * that did not land keeps its drafts, so the user can correct them instead of\n * retyping.\n */\nexport class CardForm<T> {\n private readonly specs: Map<string, CardFieldSpec>;\n private readonly staged = new Map<string, StagedEdit>();\n private readonly listeners = new Set<() => void>();\n private readonly unsubscribe: () => void;\n private saving = false;\n private failed = false;\n\n /**\n * @param scope - the bound settings scope for this card's namespace.\n * @param specs - the section fields this card edits.\n */\n constructor(\n private readonly scope: SettingsScope<T>,\n specs: CardFieldSpec[],\n ) {\n this.specs = new Map(specs.map((spec) => [spec.field, spec]));\n this.unsubscribe = this.scope.subscribe(() => this.publish());\n }\n\n /** Release this editor's listeners without disposing the provider's shared form. */\n dispose(): void {\n this.unsubscribe();\n this.listeners.clear();\n }\n\n /** Publish a projection of this form, rebuilt whenever the scope or a draft changes. */\n bind<S>(project: () => S, createStore: (init: S) => SnapshotStore<S>): SnapshotStore<S> {\n const store = createStore(project());\n this.listeners.add(() => store.set(project()));\n return store;\n }\n\n /** Read the card-level state: what the Host serves, and what a save would do. */\n shell(): CardShell {\n const snapshot = this.scope.getSnapshot();\n return {\n available: snapshot.status === 'ready',\n writable: canWriteSettings(snapshot),\n dirty: this.plan().length > 0,\n invalid: this.plan().some((item) => item.run === undefined),\n saving: this.saving,\n failed: this.failed,\n };\n }\n\n /** Read one field's state from the effective section and its staged draft. */\n field(field: string): CardFieldState {\n const spec = this.specOf(field);\n const staged = this.staged.get(field);\n if (staged === undefined) {\n return {\n text: spec.format(this.sectionValue(field)),\n overridden: this.stored(field),\n invalid: false,\n };\n }\n const write = staged.clear ? { kind: 'clear' as const } : spec.parse(staged.text);\n return {\n text: staged.text,\n overridden: write?.kind === 'set',\n invalid: write === undefined,\n };\n }\n\n /** The actions the card's slot registration injects. */\n actions(): CardActions {\n return {\n edit: (field, text) => this.stage(field, { text, clear: false }),\n resetField: (field) => {\n this.stage(field, { text: this.specOf(field).format(this.baseValue(field)), clear: true });\n },\n save: () => void this.save(),\n discard: () => {\n if (this.staged.size === 0 && !this.failed) return;\n this.staged.clear();\n this.failed = false;\n this.publish();\n },\n };\n }\n\n /**\n * Write every staged edit, then re-seed from what the Host accepted.\n * @returns true only when a non-empty save was accepted and read back.\n */\n async save(): Promise<boolean> {\n const plan = this.plan();\n const writes = plan.flatMap((item) => (item.run === undefined ? [] : [item.run]));\n const snapshot = this.scope.getSnapshot();\n if (plan.length === 0 || this.saving || writes.length !== plan.length || !canWriteSettings(snapshot)) return false;\n // Keep the staged edits this save writes. A field can be staged again\n // while a write is pending, so clear it only if that exact edit remains.\n const edits = plan.map(({ field, staged }) => ({ field, staged }));\n this.saving = true;\n this.failed = false;\n this.publish();\n let landed = true;\n try {\n for (const write of writes) {\n landed = (await write()) && landed;\n }\n } catch {\n landed = false;\n }\n if (landed) {\n for (const { field, staged } of edits) {\n if (this.staged.get(field) === staged) this.staged.delete(field);\n }\n }\n this.saving = false;\n this.failed = !landed;\n this.publish();\n return landed;\n }\n\n /**\n * Every staged edit a save would write. An entry whose draft is not a value\n * its field accepts carries no write: the form is still dirty, and the save\n * refuses rather than dropping the edit. A staged edit that matches the\n * effective section is not a write at all.\n */\n private plan(): { field: string; staged: StagedEdit; run: (() => Promise<boolean>) | undefined }[] {\n const plan: { field: string; staged: StagedEdit; run: (() => Promise<boolean>) | undefined }[] = [];\n for (const [field, staged] of this.staged) {\n const spec = this.specOf(field);\n if (staged.clear) {\n if (this.stored(field)) plan.push({ field, staged, run: () => this.clear(field) });\n continue;\n }\n if (staged.text === spec.format(this.sectionValue(field))) continue;\n const write = spec.parse(staged.text);\n if (write === undefined) plan.push({ field, staged, run: undefined });\n else if (write.kind === 'clear') plan.push({ field, staged, run: () => this.clear(field) });\n else plan.push({ field, staged, run: () => this.store(field, write.value) });\n }\n return plan;\n }\n\n private async clear(field: string): Promise<boolean> {\n const accepted = await this.scope.unset(field);\n return accepted !== false && !this.stored(field);\n }\n\n private async store(field: string, value: unknown): Promise<boolean> {\n const accepted = await this.scope.set(field, value);\n return accepted !== false && this.userLayer()?.[field] === value;\n }\n\n private stage(field: string, edit: StagedEdit): void {\n this.staged.set(field, edit);\n this.failed = false;\n this.publish();\n }\n\n private specOf(field: string): CardFieldSpec {\n const spec = this.specs.get(field);\n if (spec === undefined) throw new Error(`settings card has no field ${field}`);\n return spec;\n }\n\n private sectionValue(field: string): unknown {\n return (this.scope.getSnapshot().value as Record<string, unknown> | undefined)?.[field];\n }\n\n private baseValue(field: string): unknown {\n return (this.scope.getSnapshot().base as Record<string, unknown> | undefined)?.[field];\n }\n\n private userLayer(): Record<string, unknown> | undefined {\n return this.scope.getSnapshot().user as Record<string, unknown> | undefined;\n }\n\n private stored(field: string): boolean {\n const user = this.userLayer();\n return user !== undefined && Object.prototype.hasOwnProperty.call(user, field);\n }\n\n private publish(): void {\n for (const listener of this.listeners) listener();\n }\n}\n", "/**\n * Styles for the auto-continue settings card, injected at factory\n * materialization so the client module system's style bookkeeping (HMR) owns\n * them. Uses the DSH design tokens (`--dsw-alias-*`) so the card follows the\n * active theme.\n */\n\nconst css = `\n.dshAcComposer { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 6px; min-width: 0; min-height: 28px; max-width: 100%; font: inherit; }\n.dshAcComposerCore { display: inline-flex; align-items: center; gap: 6px; min-width: 0; max-width: 100%; }\n.dshAcComposerCore > span { min-width: 0; }\n.dshAcModeTrigger { display: inline-flex; align-items: center; gap: 3px; min-width: 0; max-width: 132px; height: 28px; margin-left: -1px; padding: 0 4px 0 7px; border: 0; border-radius: var(--dsw-radius-sm, 6px); background: none; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 13px; font-weight: 500; line-height: 20px; cursor: pointer; }\n.dshAcModeTrigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }\n.dshAcModeTrigger:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }\n.dshAcModeTrigger:disabled { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-tertiary)); cursor: default; }\n.dshAcModeTriggerLabel { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.dshAcModeChevron { display: inline-flex; flex: none; color: var(--dsw-alias-label-caption, var(--dsw-alias-label-tertiary)); transition: transform .12s ease; }\n.dshAcModeChevron > svg { display: block; width: 14px; height: 14px; }\n.dshAcModeChevronFallback { fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }\n.dshAcModeChevron[data-open=true] { transform: rotate(180deg); }\n.dshAcModeMenu { position: relative; display: inline-flex; align-items: center; gap: 3px; min-width: 0; max-width: 132px; height: 28px; margin-left: -1px; padding: 0 4px 0 7px; border-radius: var(--dsw-radius-sm, 6px); color: var(--dsw-alias-label-secondary); font-size: 13px; font-weight: 500; line-height: 20px; }\n.dshAcModeMenu:hover:not([data-disabled=true]) { color: var(--dsw-alias-label-primary); background: var(--dsw-alias-interactive-bg-hover); }\n.dshAcModeMenu[data-disabled=true] { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-tertiary)); }\n.dshAcComposerSelect { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; }\n.dshAcComposerSelect:disabled { cursor: default; }\n/* Settings-card select (default session mode); kept scoped so the composer's\n invisible overlay cannot stretch it over the whole app. */\n.dshAcCard .dshAcMode { min-height: 32px; max-width: 100%; padding: 4px 6px; border: 1px solid var(--dsh-ac-line); border-radius: 6px; background: var(--dsh-ac-bg); color: var(--dsh-ac-text); font: inherit; font-size: 12px; }\n.dshAcCard .dshAcMode:disabled { opacity: .5; }\n.dshAcCard .dshAcMode:focus-visible { outline: 2px solid var(--dsh-ac-text); outline-offset: 3px; }\n.dshAcComposerLabel { display: inline-flex; align-items: center; gap: 5px; flex: none; color: var(--dsw-alias-label-secondary); font-size: 12px; white-space: nowrap; }\n.dshAcIconBtn { position: relative; display: inline-grid; place-items: center; flex: none; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 999px; background-color: transparent; color: var(--dsw-alias-label-secondary, inherit); opacity: .9; cursor: pointer; transition: opacity .15s ease, background-color .15s ease, color .15s ease; }\n.dshAcIconBtn > svg { display: block; width: 14px; height: 14px; }\n.dshAcIconBtn[data-state=\"on\"] { color: var(--dsw-alias-brand-primary, #4d8cff); opacity: 1; background-color: rgba(77, 140, 255, .14); background-color: color-mix(in srgb, var(--dsw-alias-brand-primary, #4d8cff) 14%, transparent); }\n.dshAcIconBtn[data-state=\"on\"]:hover:not(:disabled) { background-color: rgba(77, 140, 255, .22); background-color: color-mix(in srgb, var(--dsw-alias-brand-primary, #4d8cff) 22%, transparent); }\n.dshAcIconBtn[data-state=\"off\"] { opacity: .5; }\n.dshAcIconBtn[data-state=\"off\"]:hover:not(:disabled) { opacity: .8; background: var(--dsw-alias-interactive-bg-hover); }\n.dshAcIconBtn:disabled { cursor: default; opacity: .4; }\n/* Reconnecting keeps the last known state visible, just dimmed. */\n.dshAcIconBtn[data-stale=\"true\"]:disabled { opacity: .65; }\n.dshAcIconBtn:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-brand-primary)); }\n.dshAcGlyph { fill: none; stroke: currentColor; stroke-width: 1.35; stroke-linecap: round; stroke-linejoin: round; }\n.dshAcIconBtn[data-state=\"on\"] > .dshAcGlyph { stroke-width: 1.6; }\n/* In the composer the mode name moves into the menu and tooltip; only the chevron stays. */\n.dshAcComposer .dshAcModeTriggerLabel { display: none; }\n.dshAcComposer .dshAcModeTrigger, .dshAcComposer .dshAcModeMenu { max-width: 28px; margin-left: -4px; padding: 0 2px; }\n.dshAcSwitchTarget { display: inline-flex; align-items: center; flex: none; min-height: 32px; }\n.dshAcSwitchTarget > button { position: relative; }\n.dshAcSwitchTarget > button::before { content: ''; position: absolute; inset: -4px; }\n.dshAcComposerError { color: var(--dsw-alias-state-error-primary, var(--dsw-alias-label-secondary)); font-size: 12px; max-width: 160px; }\n.dshAcComposerError:empty { display: none; }\n.dshAcToastIcon { display: block; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }\n.dshAcSwitch { position: relative; box-sizing: border-box; flex: none; width: 36px; height: 20px; padding: 2px; border: 0; border-radius: 999px; background: var(--dsw-alias-border-l3); cursor: pointer; }\n.dshAcSwitch[aria-checked='true'] { background: var(--dsw-alias-brand-primary); }\n.dshAcSwitch > span { display: block; width: 16px; height: 16px; border-radius: 50%; background: var(--dsw-alias-label-primary-foreground); }\n.dshAcSwitch[aria-checked='true'] > span { transform: translateX(16px); }\n.dshAcSwitch[aria-checked='false'] > span { background: var(--dsw-alias-switch-thumb, var(--dsw-alias-label-primary-foreground)); }\n.dshAcSwitch:disabled { opacity: .5; cursor: default; }\n.dshAcSwitch:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }\n.dshAcCard {\n --dsh-ac-bg: var(--dsw-alias-bg-base, var(--dsw-alias-bg-layer-2));\n --dsh-ac-line: var(--dsw-alias-border-l2);\n --dsh-ac-text: var(--dsw-alias-label-primary);\n --dsh-ac-muted: var(--dsw-alias-label-tertiary);\n container: auto-continue-settings / inline-size;\n color: var(--dsh-ac-text);\n font: inherit;\n font-size: 13px;\n line-height: 1.5;\n list-style: none;\n padding: 0;\n}\n.dshAcCard *, .dshAcCard *::before, .dshAcCard *::after { box-sizing: border-box; }\n.dshAcCard :is(h2,h3,p) { margin: 0; }\n.dshAcCard :is(button,input,textarea) { font: inherit; }\n.dshAcCard button { cursor: pointer; }\n.dshAcCard button:disabled { opacity: .4; cursor: default; }\n.dshAcCard :is(a,button,input,textarea):focus-visible { outline: 2px solid var(--dsh-ac-text); outline-offset: 3px; }\n.dshAcInvite { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 10px; margin: 0 0 18px; color: var(--dsh-ac-muted); font-size: 12px; line-height: 1.6; }\n.dshAcInviteStar { color: #e9be6d; font-size: 13px; line-height: 1; }\n.dshAcRepoLink { display: inline-flex; align-items: center; gap: 5px; color: var(--dsh-ac-text); text-decoration: none; }\n.dshAcRepoLink:hover { text-decoration: underline; }\n.dshAcRepoLink > svg:first-child { width: 14px; height: 14px; fill: currentColor; }\n.dshAcRepoLink > svg.dshAcExternal { width: 11px; height: 11px; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }\n.dshAcNativeFields { display: flex; flex-direction: column; min-width: 0; }\n.dshAcNativeField { display: flex; flex-direction: column; gap: 6px; min-width: 0; padding: 12px 0; }\n.dshAcNativeHead { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-width: 0; }\n.dshAcNativeLabel { color: var(--dsh-ac-text); font-size: 13px; font-weight: 500; line-height: 19.5px; }\n.dshAcNativeHint { color: var(--dsh-ac-muted); font-size: 12px; line-height: 18px; }\n.dshAcNativeToggleRow { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-width: 0; }\n.dshAcNativeActions { display: inline-flex; align-items: center; flex: none; gap: 10px; }\n.dshAcNativeReset { padding: 0; border: 0; background: none; color: var(--dsh-ac-muted); font-size: 11px; white-space: nowrap; }\n.dshAcNativeReset:hover:not(:disabled) { color: var(--dsh-ac-text); text-decoration: underline; }\n.dshAcNativeSegment { display: block; min-width: 0; }\n.dshAcNativeSegment[data-disabled=true] { opacity: .5; pointer-events: none; }\n.dshAcNativeTextarea { box-sizing: border-box; width: 100%; min-height: 66px; resize: vertical; padding: 8px 12px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 12px; background: var(--dsw-alias-bg-layer-2, #353638); color: var(--dsh-ac-text); font: inherit; font-size: 13px; line-height: 19.5px; }\n.dshAcNativeTextarea::placeholder { color: var(--dsh-ac-muted); opacity: .7; }\n.dshAcNativeTextarea[aria-invalid=true] { border-color: var(--dsw-alias-state-error-primary); }\n.dshAcReadOnly { padding: 10px 0; color: var(--dsh-ac-muted); }\n.dshAcLayout { display: grid; grid-template-columns: 164px minmax(0, 1fr); min-height: 462px; }\n.dshAcNav { display: flex; flex-direction: column; gap: 4px; padding: 16px 18px 16px 0; position: sticky; top: 16px; align-self: start; }\n.dshAcNav > button { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 37px; padding: 8px 11px; border: 0; border-radius: 6px; text-align: left; background: none; color: var(--dsw-alias-label-secondary); }\n.dshAcNav > button:hover, .dshAcNav > button[aria-selected=true] { color: var(--dsh-ac-text); background: var(--dsw-alias-interactive-bg-hover); }\n.dshAcNav > button[aria-selected=true] { font-weight: 600; }\n.dshAcInvalidMark { color: var(--dsw-alias-state-error-primary); font-weight: 600; }\n.dshAcCategory { min-width: 0; padding: 20px 0 16px 26px; border-left: 1px solid var(--dsh-ac-line); }\n.dshAcCategoryHeading { padding-bottom: 14px; }\n.dshAcCategoryHeading h3 { font-size: 15px; font-weight: 620; }\n.dshAcCategoryHeading p { color: var(--dsh-ac-muted); font-size: 12px; margin-top: 3px; }\n.dshAcField { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 10px 24px; padding: 18px 0; border-bottom: 1px solid var(--dsh-ac-line); }\n.dshAcField:last-child { border-bottom: 0; }\n.dshAcFieldCopy { min-width: 0; }\n.dshAcLabel { display: block; font-size: 14px; font-weight: 480; color: var(--dsh-ac-text); }\n.dshAcHint { color: var(--dsh-ac-muted); font-size: 12px; line-height: 1.6; }\n.dshAcFieldCopy p { margin-top: 4px; }\n.dshAcFieldControl { display: flex; align-items: center; justify-content: flex-end; gap: 14px; }\n.dshAcReset { padding: 0; border: 0; background: none; color: var(--dsh-ac-muted); font-size: 11px !important; white-space: nowrap; }\n.dshAcReset:hover:not(:disabled) { color: var(--dsh-ac-text); text-decoration: underline; }\n.dshAcInput { border: 1px solid var(--dsh-ac-line); border-radius: 6px; background: var(--dsh-ac-bg); color: var(--dsh-ac-text); padding: 8px 11px; }\n.dshAcInput::placeholder { color: var(--dsh-ac-muted); opacity: .7; }\n.dshAcInput[aria-invalid=true] { border-color: var(--dsw-alias-state-error-primary); }\n.dshAcNumber { width: 132px; min-width: 0; font-variant-numeric: tabular-nums; }\n.dshAcFieldText { display: block; }\n.dshAcFieldText .dshAcFieldControl { margin-top: 10px; flex-direction: column-reverse; align-items: flex-end; gap: 6px; }\n.dshAcTextArea { display: block; width: 100%; min-height: 66px; resize: vertical; line-height: 1.6; }\n.dshAcInvalid, .dshAcFailed { color: var(--dsw-alias-state-error-primary); font-size: 12px; }\n.dshAcFooter { display: flex; justify-content: space-between; align-items: center; gap: 14px; margin-top: 24px; padding: 13px 0; border-top: 1px solid var(--dsh-ac-line); background: var(--dsh-ac-bg); }\n.dshAcFooter[data-dirty=true] { position: sticky; z-index: 8; bottom: 0; }\n.dshAcFooter > div { display: flex; align-items: center; gap: 8px; }\n.dshAcDiscard, .dshAcSave { padding: 7px 13px; border: 1px solid var(--dsh-ac-line); border-radius: 6px; font-size: 12px !important; background: var(--dsh-ac-bg); color: var(--dsh-ac-text); white-space: nowrap; }\n.dshAcSave { background: var(--dsh-ac-text); color: var(--dsh-ac-bg); border-color: var(--dsh-ac-text); }\n.dshAcDiscard:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }\n.dshAcSave:hover:not(:disabled) { opacity: .85; }\n.dshAcPanel { padding: 20px 0; border-top: 1px solid var(--dsh-ac-line); }\n.dshAcPanelHead { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 10px; }\n.dshAcPanelTitle { font-weight: 550; }\n.dshAcStats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin: 18px 0; }\n.dshAcStats dt { font-size: 11px; color: var(--dsh-ac-muted); }\n.dshAcStats dd { margin: 4px 0 0; font-size: 19px; font-weight: 550; font-variant-numeric: tabular-nums; }\n.dshAcCodes { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }\n.dshAcCode { font: 11px ui-monospace, SFMono-Regular, monospace; border: 1px solid var(--dsh-ac-line); border-radius: 4px; padding: 3px 6px; }\n.dshAcPauseList { list-style: none; margin: 0; padding: 0; }\n.dshAcPauseList li { display: flex; align-items: center; gap: 12px; padding: 10px 0; }\n.dshAcPauseId { flex: 1; font: 12px ui-monospace, SFMono-Regular, monospace; }\n.dshAcRecovery { display: grid; gap: 4px; min-width: 0; overflow-wrap: anywhere; }\n@container auto-continue-settings (max-width: 760px) {\n .dshAcLayout { grid-template-columns: 136px minmax(0, 1fr); }\n .dshAcCategory { padding-left: 20px; }\n .dshAcFieldControl { flex-direction: column-reverse; align-items: flex-end; gap: 6px; }\n}\n@container auto-continue-settings (max-width: 560px) {\n .dshAcLayout { display: block; min-height: 0; }\n .dshAcNav { flex-direction: row; overflow-x: auto; position: static; padding: 12px 0; border-bottom: 1px solid var(--dsh-ac-line); }\n .dshAcNav > button { flex: none; font-size: 12px; min-height: 34px; padding: 7px 10px; }\n .dshAcCategory { border-left: 0; padding: 20px 0; }\n .dshAcField { gap: 8px 14px; }\n .dshAcLabel { font-size: 13px; }\n .dshAcNumber { width: 98px; }\n .dshAcFooter { align-items: flex-start; flex-direction: column; gap: 10px; }\n .dshAcFooter > div { width: 100%; justify-content: flex-end; }\n}\n/* DS-Bot can remove the query container with display: contents. */\n@media (max-width: 640px) {\n .dshAcComposer { flex-direction: column; align-items: flex-start; width: min-content; }\n .dshAcComposer > .dshAcComposerLabel { white-space: normal; }\n}\n\n`;\n\n/** Inject the stylesheet once; a no-op outside a browser environment. */\nexport function injectStyles(): void {\n if (typeof document === 'undefined') return;\n if (document.querySelector('style[data-plugin-css=\"auto-continue/card\"]') !== null) return;\n const tag = document.createElement('style');\n tag.dataset.plugin = 'dsh-client-auto-continue';\n tag.dataset.pluginCss = 'auto-continue/card';\n tag.textContent = css;\n document.head.appendChild(tag);\n}\n", "import { en, ru, zh, type SettingsCardKey } from './locales.ts';\nimport { resolveLocale } from '../shared/core.ts';\n\ntype Permission = NotificationPermission | 'unsupported' | 'failed';\nexport type SettingsNotice = 'enabled' | 'disabled' | 'saved';\nlet pendingPermission: Promise<Permission> | undefined;\n\n/** Called directly by Save, before a network await can consume user activation. */\nexport function prepareSettingsNotification(enabled: boolean): Promise<Permission> {\n try {\n if (typeof Notification === 'undefined') return Promise.resolve('unsupported');\n if (!enabled || Notification.permission !== 'default') return Promise.resolve(Notification.permission);\n if (!pendingPermission) {\n pendingPermission = Notification.requestPermission()\n .catch((): Permission => 'failed')\n .finally(() => { pendingPermission = undefined; });\n }\n return pendingPermission;\n } catch {\n return Promise.resolve('failed');\n }\n}\n\n/** The save is already committed. Notification failures must never undo it. */\nexport function showSettingsNotification(notice: SettingsNotice, locale: string, permission: Permission): SettingsCardKey {\n const message: SettingsCardKey = `notification.${notice}`;\n if (permission !== 'granted') {\n // Turning alerts off must not ask for permission just to confirm the change.\n if (notice === 'disabled') return message;\n return permission === 'unsupported' ? 'notification.unsupported'\n : permission === 'failed' ? 'notification.failed' : 'notification.blocked';\n }\n try {\n const resolved = resolveLocale(locale);\n const copy = resolved === 'zh' ? zh : resolved === 'ru' ? ru : en;\n const notification = new Notification(copy['notification.title'], { body: copy[message] });\n notification.onclick = () => {\n try { globalThis.focus?.(); } catch { /* Focusing is best effort. */ }\n };\n return message;\n } catch {\n return notice === 'disabled' ? message : 'notification.failed';\n }\n}\n", "import { useEffect, useState } from 'react';\nimport type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots';\nimport type { SnapshotStore } from './dsh-store-compat.ts';\nimport { sessionMode, type SessionMode, type SessionPolicy } from '../shared/core.ts';\nimport { ModeMenu, type ModeMenuOption } from './mode-menu.tsx';\nimport { AutoContinueIcon } from './auto-continue-icon.tsx';\nimport { NativeToast, WarningIcon, hasNativeToast } from './native-toast.tsx';\n\nexport interface ComposerToggleState {\n visible: boolean;\n policy: SessionPolicy | undefined;\n /** The bridge dropped; `policy` is the last known one and stays on screen, read-only. */\n reconnecting: boolean;\n writable: boolean;\n saving: ReadonlySet<string>;\n failed: ReadonlySet<string>;\n}\n\nconst HOST_UNAVAILABLE_DELAY_MS = 3000;\n\nfunction HostUnavailableToast({ text }: { text: string }) {\n const [visible, setVisible] = useState(false);\n useEffect(() => {\n const timer = setTimeout(() => setVisible(true), HOST_UNAVAILABLE_DELAY_MS);\n return () => clearTimeout(timer);\n }, []);\n if (!hasNativeToast || !visible) return null;\n const Toast = NativeToast!;\n return <Toast text={text} icon={<WarningIcon />} onDone={() => setVisible(false)} />;\n}\n\nfunction SaveFailureToast({ text }: { text: string }) {\n const [visible, setVisible] = useState(true);\n if (!hasNativeToast || !visible) return null;\n const Toast = NativeToast!;\n return <Toast text={text} icon={<WarningIcon />} onDone={() => setVisible(false)} />;\n}\n\nexport interface ComposerToggleFace {\n hooks: { autoContinueComposer: SnapshotStore<ComposerToggleState> };\n sessionId: string;\n setMode: (mode: SessionMode) => void;\n}\n\nexport function AutoContinueComposerToggle(props: PropsLocale<'auto-continue'> & InjectFace<ComposerToggleFace>) {\n const state = props.useAutoContinueComposer((snapshot) => snapshot);\n if (!state.visible || !props.sessionId) return null;\n const failed = state.failed.has(props.sessionId);\n const saving = state.saving.has(props.sessionId);\n const policy = state.policy;\n // A child with no mode of its own shows what it actually inherits; the host\n // resolves that alongside the explicit modes so the control never reports the\n // profile default while recovery is disabled by the main conversation.\n const ownMode = sessionMode(policy?.modes ?? {}, props.sessionId);\n const mode: SessionMode = ownMode === 'default'\n ? policy?.inheritedModes?.[props.sessionId] ?? 'default'\n : ownMode;\n const disabled = !policy || !state.writable || saving;\n const title = props.t(!policy ? 'composer.unavailable' : state.reconnecting ? 'composer.reconnecting'\n : !state.writable ? 'chrome.readOnly' : saving ? 'composer.saving' : 'composer.scope');\n const modeName = props.t(`composer.${mode}`);\n const defaultName = policy\n ? `${props.t('composer.default')} (${props.t(`composer.${policy.defaultMode}`)})`\n : props.t('composer.default');\n const fullModeLabel = mode === 'default' ? defaultName : modeName;\n const modeTitle = `${props.t('composer.mode')}: ${fullModeLabel}`;\n const options: readonly ModeMenuOption[] = [\n { id: 'default', label: defaultName },\n { id: 'off', label: props.t('composer.off') },\n { id: 'recover', label: props.t('composer.recover') },\n { id: 'loop', label: props.t('composer.loop') },\n ];\n const enabled = !!policy && mode !== 'off';\n // Turning on writes `default`, unless that would just inherit Off again (a child of an Off main chat).\n const onMode: SessionMode = policy?.inheritedModes?.[props.sessionId] === 'off' ? 'recover' : 'default';\n // One 28px icon switch plus a chevron-only mode menu: the mode name lives in the\n // menu, the tooltip and the accessible name instead of taking composer width (#86).\n return (\n <div className=\"dshAcComposer\" title={title} aria-busy={saving || undefined}>\n <span className=\"dshAcComposerCore\">\n <button type=\"button\" role=\"switch\" className=\"dshAcIconBtn\" data-state={enabled ? 'on' : 'off'}\n data-stale={state.reconnecting || undefined} aria-checked={enabled}\n aria-label={`${props.t('composer.label')}: ${fullModeLabel}`} title={`${modeTitle}\\n${title}`}\n disabled={disabled} onClick={() => props.setMode(enabled ? 'off' : onMode)}>\n <AutoContinueIcon />\n </button>\n <ModeMenu mode={mode} options={options} label={modeName}\n ariaLabel={modeTitle} selectLabel={props.t('composer.mode')} title={modeTitle}\n disabled={disabled} onChange={props.setMode} />\n </span>\n {policy?.paused && <span className=\"dshAcComposerLabel\">{props.t('composer.paused')}</span>}\n {!policy && hasNativeToast && <HostUnavailableToast text={props.t('composer.unavailable')} />}\n {failed && hasNativeToast && <SaveFailureToast text={props.t('composer.saveFailed')} />}\n {failed && !hasNativeToast && <span className=\"dshAcComposerError\" role=\"status\">{props.t('composer.saveFailed')}</span>}\n </div>\n );\n}\n", "/**\n * Composer mode menu.\n *\n * Uses the host's own `Menu` and chevron primitives whenever the running DSH\n * exposes them, so the control looks and behaves like the composer's other\n * dropdowns (workspace permission, model picker). Legacy hosts, and the unit\n * tests' minimal module fixture, fall back to a native `<select>` over the\n * same compact label.\n */\nimport { useEffect, useState, type ComponentType, type ReactNode } from 'react';\nimport { isSessionMode, type SessionMode } from '../shared/core.ts';\n\nexport interface ModeMenuOption {\n id: SessionMode;\n label: string;\n}\n\ninterface MenuProps {\n open: boolean;\n anchor: ReactNode;\n items: readonly ModeMenuOption[];\n selectedId?: string;\n onSelect?: (id: string) => void;\n onClose?: () => void;\n side?: 'top' | 'bottom';\n portal?: boolean;\n}\n\ninterface ChevronProps {\n className?: string;\n}\n\nconst primitives = (() => {\n try {\n return require('@deepseek-ai/dsh-client-ui-primitives') as {\n Menu?: ComponentType<MenuProps>;\n IconChevronDownOutlineRegular?: ComponentType<ChevronProps>;\n };\n } catch {\n return {};\n }\n})();\n\nconst HostMenu = primitives.Menu;\nconst HostChevron = primitives.IconChevronDownOutlineRegular;\n\nfunction ChevronDown() {\n if (HostChevron) return <HostChevron />;\n return (\n <svg className=\"dshAcModeChevronFallback\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"m4.5 6.25 3.5 3.5 3.5-3.5\" />\n </svg>\n );\n}\n\nexport interface ModeMenuProps {\n mode: SessionMode;\n options: readonly ModeMenuOption[];\n /** Short label shown on the trigger, e.g. 跟随默认. */\n label: string;\n /** Accessible name including the resolved mode, e.g. 自动继续模式: 跟随默认 (仅故障恢复). */\n ariaLabel: string;\n /** Plain menu name used by the legacy select fallback. */\n selectLabel: string;\n title: string;\n disabled: boolean;\n onChange: (mode: SessionMode) => void;\n}\n\nexport function ModeMenu(props: ModeMenuProps) {\n const [open, setOpen] = useState(false);\n const expanded = open && !props.disabled;\n\n useEffect(() => {\n if (props.disabled) setOpen(false);\n }, [props.disabled]);\n\n const choose = (id: string) => {\n setOpen(false);\n if (isSessionMode(id) && id !== props.mode) props.onChange(id);\n };\n\n if (HostMenu) {\n return (\n <HostMenu open={expanded} side=\"top\" portal\n items={props.options} selectedId={props.mode}\n onSelect={choose} onClose={() => setOpen(false)}\n anchor={\n <button type=\"button\" className=\"dshAcModeTrigger\" disabled={props.disabled}\n aria-label={props.ariaLabel} aria-haspopup=\"menu\" aria-expanded={expanded}\n title={props.title} onClick={() => setOpen(value => !value)}>\n <span className=\"dshAcModeTriggerLabel\">{props.label}</span>\n <span className=\"dshAcModeChevron\" data-open={expanded} aria-hidden=\"true\"><ChevronDown /></span>\n </button>\n } />\n );\n }\n\n return (\n <span className=\"dshAcModeMenu\" data-disabled={props.disabled} title={props.title}>\n <span className=\"dshAcModeTriggerLabel\">{props.label}</span>\n <span className=\"dshAcModeChevron\" aria-hidden=\"true\"><ChevronDown /></span>\n <select className=\"dshAcComposerSelect\" aria-label={props.selectLabel} disabled={props.disabled}\n value={props.mode}\n onChange={event => { if (isSessionMode(event.target.value)) props.onChange(event.target.value); }}>\n {props.options.map(option => <option key={option.id} value={option.id}>{option.label}</option>)}\n </select>\n </span>\n );\n}\n", "/**\n * Auto-continue glyph: a single-stroke infinity loop.\n *\n * Deliberately not the host's refresh icon. Refresh reads as \"start over\",\n * auto-continue means \"keep going without stopping\" (#86). Drawn on a 16px grid\n * with a 2px margin so both loops stay distinct at 14px.\n */\nexport function AutoContinueIcon() {\n return (\n <svg className=\"dshAcGlyph\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M8 8C7 5.6 6.1 4.6 4.8 4.6C3.1 4.6 2 6.1 2 8C2 9.9 3.1 11.4 4.8 11.4C6.1 11.4 7 10.4 8 8C9 5.6 9.9 4.6 11.2 4.6C12.9 4.6 14 6.1 14 8C14 9.9 12.9 11.4 11.2 11.4C9.9 11.4 9 10.4 8 8Z\" />\n </svg>\n );\n}\n", "/**\n * DSH toast bridge.\n *\n * The composer reports a failed session-mode save with the host's own toast\n * instead of inline red text that shifts the input row. Hosts without the\n * primitive (older DSH, or the unit-test fixture) keep the inline fallback.\n */\nimport type { ComponentType, ReactNode } from 'react';\n\nexport interface ToastProps {\n text: string;\n icon?: ReactNode;\n tone?: 'success';\n onDone?: () => void;\n}\n\ninterface IconProps {\n className?: string;\n}\n\nconst primitives = (() => {\n try {\n return require('@deepseek-ai/dsh-client-ui-primitives') as {\n Toast?: ComponentType<ToastProps>;\n IconWarningOutlineRegular?: ComponentType<IconProps>;\n };\n } catch {\n return {};\n }\n})();\n\nexport const NativeToast = primitives.Toast;\nexport const hasNativeToast = typeof NativeToast === 'function';\n\nexport function WarningIcon() {\n const Icon = primitives.IconWarningOutlineRegular;\n if (Icon) return <Icon />;\n return (\n <svg className=\"dshAcToastIcon\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M8 2.3 14.3 13H1.7L8 2.3Z\" />\n <path d=\"M8 6.2v3.1M8 11.8v.1\" />\n </svg>\n );\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmBO,SAAS,cAAc,QAAqC;AACjE,MAAI,OAAO,WAAW,SAAU,QAAO;AACvC,MAAI,cAAc,KAAK,MAAM,EAAG,QAAO;AACvC,MAAI,cAAc,KAAK,MAAM,EAAG,QAAO;AACvC,SAAO;AACT;AAaO,IAAM,gBAAgB,CAAC,UAC5B,UAAU,aAAa,UAAU,SAAS,UAAU,aAAa,UAAU;AAEtE,SAAS,YAAY,OAAoC,WAAgC;AAC9F,SAAO,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,KAAK,cAAc,MAAM,SAAS,CAAC,IAAI,MAAM,SAAS,IAAK;AACzH;AAGO,IAAM,0BAA0B;AAAA,EACrC,IAAI;AAAA,IACF,cAAc;AAAA,IACd,uBAAuB;AAAA,IACvB,oBACE;AAAA,IACF,kBAAkB;AAAA,IAClB,yBACE;AAAA,IACF,kBAAkB;AAAA,IAClB,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AAAA,EACA,IAAI;AAAA,IACF,cAAc;AAAA,IACd,uBAAuB;AAAA,IACvB,oBACE;AAAA,IACF,kBAAkB;AAAA,IAClB,yBACE;AAAA,IACF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ACJ,QAAQ;AAAA,QACR,QAAQ,CAAC,cAAc,WAAW,eAAe,SAAS;AAAA,MAC5D;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAIA,MAAI,MAAM;AAAA,IAAO;AAAA,IAAwB,MACvC,IAAI,MAAM;AAAA,MACR;AAAA,QACE,MAAM;AAAA,QACN,KAAK;AAAA,QACL,QAAQ;AAAA,QACR,QAAQ,MAAM,WAAW,OAAO;AAAA,MAClC;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,MAAM;AAAA,IAAO;AAAA,IAAyB,MACxC,IAAI,MAAM;AAAA,MACR;AAAA,QACE,MAAM;AAAA,QACN,KAAK;AAAA,QACL,QAAQ;AAAA,QACR,QAAQ,MAAM,WAAW,OAAO;AAAA,MAClC;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": ["import_jsx_runtime", "state", "import_react", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "primitives", "import_jsx_runtime", "state"]
7
7
  }