From bc51acd00e900c5ed67add0ccf3da780edd94f64 Mon Sep 17 00:00:00 2001 From: wujunchen Date: Sun, 26 Apr 2026 18:27:28 +0800 Subject: [PATCH] fix: parse multiline sse events Change-Id: I9c013dbe6840a0892836eb5d71206c6fcde5ec78 --- main.js | 32 ++++++++++++++++++++------------ src/streaming.ts | 22 ++++++++++++++-------- tests/modules.test.js | 21 +++++++++++++++++---- 3 files changed, 51 insertions(+), 24 deletions(-) diff --git a/main.js b/main.js index 4d9eb10..bcebdbf 100644 --- a/main.js +++ b/main.js @@ -1,13 +1,13 @@ 'use strict'; -"use strict";var Lt=Object.create;var se=Object.defineProperty;var Ot=Object.getOwnPropertyDescriptor;var Bt=Object.getOwnPropertyNames;var _t=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var Ut=(r,t)=>{for(var e in t)se(r,e,{get:t[e],enumerable:!0})},lt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Bt(t))!Vt.call(r,i)&&i!==e&&se(r,i,{get:()=>t[i],enumerable:!(n=Ot(t,i))||n.enumerable});return r};var oe=(r,t,e)=>(e=r!=null?Lt(_t(r)):{},lt(t||!r||!r.__esModule?se(e,"default",{value:r,enumerable:!0}):e,r)),jt=r=>lt(se({},"__esModule",{value:!0}),r);var fr={};Ut(fr,{__test:()=>gr,default:()=>mr});module.exports=jt(fr);var d=require("obsidian");function J(r,t){if(!t)return-1;let e=h=>h.replace(/\s+/g," ").trim(),n=h=>{let f=[],p=[],g=!1;for(let b=0;b0;continue}g&&(f.push(" "),p.push(b),g=!1),f.push(ae),p.push(b)}return{text:f.join(""),map:p}},i=h=>{if(!h)return-1;let f=r.indexOf(h);if(f===-1)return-1;let p=0;for(let g=0;g=0||(a=i(t.trim()),a>=0))return a;for(let h of[60,40,25,15]){let f=t.trim().slice(0,h);if(a=i(f),a>=0)return a}let s=n(r),o=e(t).slice(0,30);if(!o)return-1;let c=s.text.indexOf(o);if(c===-1)return-1;let l=s.map[c];if(l==null)return-1;let u=0;for(let h=0;h{for(var e in t)se(r,e,{get:t[e],enumerable:!0})},lt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Bt(t))!Vt.call(r,i)&&i!==e&&se(r,i,{get:()=>t[i],enumerable:!(n=Ot(t,i))||n.enumerable});return r};var oe=(r,t,e)=>(e=r!=null?Lt(_t(r)):{},lt(t||!r||!r.__esModule?se(e,"default",{value:r,enumerable:!0}):e,r)),jt=r=>lt(se({},"__esModule",{value:!0}),r);var fr={};Ut(fr,{__test:()=>gr,default:()=>mr});module.exports=jt(fr);var d=require("obsidian");function J(r,t){if(!t)return-1;let e=p=>p.replace(/\s+/g," ").trim(),n=p=>{let f=[],h=[],g=!1;for(let b=0;b0;continue}g&&(f.push(" "),h.push(b),g=!1),f.push(ae),h.push(b)}return{text:f.join(""),map:h}},i=p=>{if(!p)return-1;let f=r.indexOf(p);if(f===-1)return-1;let h=0;for(let g=0;g=0||(a=i(t.trim()),a>=0))return a;for(let p of[60,40,25,15]){let f=t.trim().slice(0,p);if(a=i(f),a>=0)return a}let s=n(r),o=e(t).slice(0,30);if(!o)return-1;let c=s.text.indexOf(o);if(c===-1)return-1;let u=s.map[c];if(u==null)return-1;let l=0;for(let p=0;p --version` \u9A8C\u8BC1 spawn \u80FD\u627E\u5230\u4E8C\u8FDB\u5236",backendTestFailed:"\u2717 \u540E\u7AEF\u6D4B\u8BD5\u5931\u8D25\uFF1A{error}",settingExportFolderName:"\u5BFC\u51FA\u6587\u4EF6\u5939",settingExportFolderDesc:"\u5BF9\u7167\u7B14\u8BB0\u751F\u6210\u4F4D\u7F6E\uFF08\u76F8\u5BF9 Vault \u6839\uFF09",cacheHeader:"\u7F13\u5B58",settingMaxCacheName:"\u6700\u5927\u7F13\u5B58\u7BC7\u6570",settingMaxCacheDesc:"\u8D85\u8FC7\u4E0A\u9650\u540E\u6309\u6700\u8FD1\u8BBF\u95EE\u65F6\u95F4\u6DD8\u6C70\u6700\u65E7\u7684\u7B14\u8BB0\u7F13\u5B58\uFF1B\u7F13\u5B58\u4FDD\u5B58\u5728\u63D2\u4EF6\u76EE\u5F55\u7684 cache.json",cachePruned:"\u5DF2\u6DD8\u6C70 {count} \u6761\u65E7\u7F13\u5B58",cachedNotesName:"\u5DF2\u7F13\u5B58\u7B14\u8BB0\uFF1A{count} \u7BC7",cachedNotesDesc:"\u7F13\u5B58\u4EE5\u6E90\u7B14\u8BB0 SHA1 + \u751F\u6210\u914D\u7F6E\u6307\u7EB9\u4F5C\u4E3A\u5931\u6548\u952E\uFF0C\u6E90\u7B14\u8BB0\u6216\u6A21\u578B\u914D\u7F6E\u4FEE\u6539\u540E\u4F1A\u663E\u793A stale \u63D0\u793A",clearAllCacheButton:"\u6E05\u9664\u6240\u6709\u7F13\u5B58",settingStreamingName:"\u6D41\u5F0F\u8F93\u51FA",settingStreamingDesc:"\u542F\u7528\u540E\u751F\u6210\u65F6\u5B9E\u65F6\u663E\u793A LLM \u8F93\u51FA\u8FDB\u5EA6\uFF08\u4EC5 OpenAI Chat \u548C Anthropic \u683C\u5F0F\u652F\u6301\uFF09",settingStreamingTimeoutName:"\u6D41\u5F0F\u8D85\u65F6 (ms)",settingStreamingTimeoutDesc:"\u5355\u6B21\u6D41\u5F0F\u8BF7\u6C42\u7684\u8D85\u65F6\u65F6\u95F4\uFF1B\u4F4E\u4E8E 1000ms \u6216\u975E\u6CD5\u503C\u4F1A\u6062\u590D\u9ED8\u8BA4\u503C",cmdBatchGenerate:"\u6279\u91CF\u751F\u6210\u5BF9\u7167\u7B14\u8BB0\uFF08\u5F53\u524D\u6587\u4EF6\u5939\uFF09",batchSelectFolder:"\u8BF7\u8F93\u5165\u8981\u6279\u91CF\u5904\u7406\u7684\u6587\u4EF6\u5939\u8DEF\u5F84\uFF08\u7559\u7A7A\u4E3A Vault \u6839\u76EE\u5F55\uFF09",batchFolderPrompt:"\u6587\u4EF6\u5939\u8DEF\u5F84",batchAlreadyRunning:"\u6279\u91CF\u751F\u6210\u6B63\u5728\u8FD0\u884C",batchCancelRequested:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u6279\u91CF\u751F\u6210\uFF1B\u5F53\u524D\u6587\u4EF6\u7ED3\u675F\u540E\u505C\u6B62",batchInvalidFolderInput:"\u6587\u4EF6\u5939\u8DEF\u5F84\u65E0\u6548\uFF1A{path}",batchFolderNotFound:"\u6587\u4EF6\u5939\u4E0D\u5B58\u5728\uFF1A{path}",batchNoMarkdown:"\u8BE5\u6587\u4EF6\u5939\u4E0B\u6CA1\u6709 Markdown \u6587\u4EF6",batchProgress:"\u6279\u91CF\u751F\u6210\uFF1A{current}/{total}",batchDone:"\u6279\u91CF\u751F\u6210\u5B8C\u6210\uFF1A\u5171\u5904\u7406 {processed}/{total} \u7BC7\uFF0C\u8DF3\u8FC7\u7F13\u5B58 {skipped} \u7BC7",batchCancelled:"\u6279\u91CF\u751F\u6210\u5DF2\u53D6\u6D88\uFF1A\u5DF2\u5904\u7406 {processed}/{total} \u7BC7\uFF0C\u8DF3\u8FC7\u7F13\u5B58 {skipped} \u7BC7"},en:{appTitle:"Parallel Reader",settingsTitle:"Parallel Reader Settings",emptyOpenNote:"Open a note, then run:",emptyNoCache:"This note has no cached parallel notes. Run:",commandGenerate:"Parallel Reader: Generate notes for current note",displayName:"Parallel Reader",ribbonOpen:"Open Parallel Reader pane",cmdRun:"Generate parallel notes for current note (cache first)",cmdRegen:"Regenerate parallel notes (bypass cache)",cmdOpenView:"Open Parallel Reader pane",cmdExport:"Export current parallel notes to Vault",cmdCopyMarkdown:"Copy current parallel notes as Markdown",cmdCancel:"Cancel current parallel-note generation",cmdClearCurrent:"Clear cache for current note",cmdClearAll:"Clear all caches",cmdCardPrev:"Focus previous summary card",cmdCardNext:"Focus next summary card",cmdCardJump:"Jump current summary card to source",actionCancel:"Cancel generation",actionRegenerate:"Regenerate",actionCopyAll:"Copy all Markdown",actionExport:"Export to Vault",staleBanner:"The source note or generation settings changed. This is stale cache.",loadingDefault:"Generating parallel notes...",loadingGenerating:"Parallel Reader: asking the LLM to read and segment the full note...",loadingSubtitle:"You can keep reading. Cards will refresh when generation finishes.",errorTitle:"Generation failed",emptyCard:"(not generated)",anchorMismatch:"Anchor did not match; scroll sync is unavailable",menuCopyMarkdown:"Copy Markdown",menuCopyPlain:"Copy plain text",menuCopyAnchor:"Copy anchor quote",menuJumpSource:"Jump to source",menuEditCard:"Edit this card",menuDeleteCard:"Delete this card",copiedMarkdown:"Copied Markdown",copiedPlain:"Copied plain text",copiedAnchor:"Copied anchor quote",copiedAllMarkdown:"Copied all Markdown",copyFailed:"Copy failed: {error}",actionFailed:"{label} failed: {error}",exported:"Exported \u2192 {path}",noCurrentNote:"No current note",cacheClearedFile:"Cleared cache: {name}",cacheClearedAll:"Cleared {count} cache entries",noCancelableJob:"No cancellable generation job",cancelRequested:"Cancel requested",cancelRequestedApiInFlight:"Cancel requested. The in-flight API request cannot be aborted immediately; its result will be ignored.",fileMenuGenerate:"Generate parallel notes",fileMenuRegen:"Regenerate parallel notes",fileMenuClear:"Clear parallel-note cache",noExportContent:"No parallel notes to export",noCopyContent:"No parallel notes to copy",noActiveCard:"No active summary card to jump",viewOpenFailed:"Could not open the Parallel Reader pane",confirmRegenerateEditedCards:"These parallel-reader cards were edited manually. Regenerating will overwrite those edits. Continue?",regenerateCancelled:"Regeneration cancelled",cardDeleted:"Deleted this card",cardSaved:"Saved this card",editCardTitle:"Edit summary card",editCardTitleField:"Title",editCardGistField:"Gist",editCardBulletsField:"Bullets (one per line)",editCardCancel:"Cancel",editCardSave:"Save",openNoteFirst:"Open a note first",alreadyGenerating:"This note is already being generated",emptyNote:"The note is empty",longNoteTruncated:"Long note: only the first {count} characters will be sent to the model",generatingNotice:"Parallel Reader: asking the LLM to read and segment the full note...",noCardsReturned:"LLM returned no cards",generationDone:"Generated {count} sections{suffix}",unanchoredSuffix:" (\u26A0 {count} anchors unmatched)",cancelled:"Generation cancelled",cancelledError:"Generation cancelled",generationFailed:"Generation failed{kind}: {error}",errorCustomProviderBaseUrlRequired:"Custom provider requires an API Base URL.",errorApiBaseUrlMissing:"API Base URL is not set. Choose a provider or enter a custom base URL in settings.",errorModelMissing:"Model is not set. Enter a model ID in settings.",errorApiKeyMissing:"API key is not set. Enter an API Key in settings{hint}.",errorApiKeyEnvHint:" or set environment variable {envVar}",errorLlmNonJson:`LLM returned non-JSON: {excerpt}`,errorCustomHeadersJsonParse:"Custom headers JSON parse failed: {error}",errorCustomHeadersJsonObject:"Custom headers JSON must be an object",errorCustomHeadersLineFormat:"Custom headers lines must use `Header-Name: value`",errorProviderNonJson:`{label} returned non-JSON: -{excerpt}`,errorProviderRequestFailed:"{label} request failed: {error}",errorProviderApiStatus:"{label} API returned HTTP {status}: {excerpt}",noEditor:"Could not find the source note editor",settingUiLanguageName:"UI language",settingUiLanguageDesc:"Controls plugin UI, commands, and notices. Auto follows Obsidian/system language.",settingBackendName:"Backend",settingBackendDesc:"Backend for generating bullets: CLI reuses local login; API supports OpenAI, Anthropic, Gemini, and compatible proxies.",settingCliPathName:"CLI path (optional)",settingCliPathDesc:"Leave blank to auto-detect common paths. Obsidian launched from the GUI may not inherit shell PATH.",settingCliPathPlaceholder:"Example: /Users/you/bin/codex",settingCliTimeoutName:"CLI timeout (ms)",apiProviderHeader:"API Provider",settingProviderPresetName:"Provider preset",settingProviderPresetDesc:"OpenClaw-style provider/model setup: presets define protocol, base URL, and auth defaults.",settingApiFormatName:"API format",settingApiFormatDesc:"Wire protocol for the provider. OpenAI-compatible proxies usually use Chat Completions.",settingBaseUrlName:"Base URL",settingBaseUrlDesc:"Provider root URL, without /chat/completions. Blank uses the preset default.",settingApiKeyName:"API Key",settingApiKeyDesc:"Can be blank for local Ollama/LM Studio; most hosted providers require a key.",settingApiKeyEnvName:"API key env var",settingApiKeyEnvDesc:"Optional. Obsidian GUI may not inherit shell env; direct API Key is usually more reliable.",settingAuthTypeName:"Auth type",settingAuthTypeDesc:"Auto uses provider preset. Custom proxies can use Bearer, x-api-key, or none.",settingHeadersName:"Extra headers",settingHeadersDesc:"Optional. JSON object or one `Header: value` per line, useful for Cloudflare AI Gateway.",settingMaxTokensName:"Max output tokens",settingModelName:"Model",settingModelDescApi:"Model ID for API calls. Supports OpenClaw-style provider/model; matching provider prefixes are stripped.",settingModelDescCli:"Passed as --model for Claude Code. Usually ignored by Codex, which uses its default config.",settingMaxInputName:"Max input characters",settingMaxInputDesc:"Longer notes are truncated before sending to the model. Raise this for long-context models.",promptHeader:"Prompt",settingPromptLanguageName:"Output language",settingPromptLanguageDesc:"Controls title/gist/bullets language. Anchor is always copied verbatim from source.",settingCardRangeName:"Card count range",settingCardRangeDesc:"The model adapts segmentation within this range.",settingCustomPromptName:"Custom system prompt",settingCustomPromptDesc:"Optional. Variables: {minCards}, {maxCards}, {languageInstruction}, {schema}, {example}",settingCustomPromptPlaceholder:"Leave blank to use built-in prompt",settingTestBackendName:"Test current backend",settingTestBackendDescApi:"Sends a minimal LLM request to validate API settings.",settingTestBackendDescCli:"Runs ` --version` to verify the binary can be spawned.",backendTestFailed:"\u2717 Backend test failed: {error}",settingExportFolderName:"Export folder",settingExportFolderDesc:"Parallel-note output location, relative to the Vault root.",cacheHeader:"Cache",settingMaxCacheName:"Max cached notes",settingMaxCacheDesc:"Prunes least-recently accessed note caches above this limit. Cache is stored in plugin cache.json.",cachePruned:"Pruned {count} old cache entries",cachedNotesName:"Cached notes: {count}",cachedNotesDesc:"Cache is invalidated by source SHA1 and generation settings fingerprint.",clearAllCacheButton:"Clear all caches",settingStreamingName:"Streaming output",settingStreamingDesc:"Show real-time LLM output progress during generation (OpenAI Chat and Anthropic formats only)",settingStreamingTimeoutName:"Streaming timeout (ms)",settingStreamingTimeoutDesc:"Timeout for one streaming request; invalid values or values below 1000ms use the default",cmdBatchGenerate:"Batch generate parallel notes (current folder)",batchSelectFolder:"Enter the folder path to batch-process (leave blank for Vault root)",batchFolderPrompt:"Folder path",batchAlreadyRunning:"Batch generation is already running",batchCancelRequested:"Batch cancellation requested; it will stop after the current note",batchInvalidFolderInput:"Invalid folder path: {path}",batchFolderNotFound:"Folder not found: {path}",batchNoMarkdown:"No Markdown files found in that folder",batchProgress:"Batch generating: {current}/{total}",batchDone:"Batch complete: processed {processed}/{total}, skipped {skipped} (cached)",batchCancelled:"Batch cancelled: processed {processed}/{total}, skipped {skipped} (cached)"}};function Gt(r){let t=r?.uiLanguage;return t==="zh"||t==="en"?t:String((typeof navigator<"u"?navigator:null)?.language||"").toLowerCase().startsWith("zh")?"zh":"en"}function w(r,t,e){let n=Gt(r),i=ce[n]||ce.en,a=ce.en[t]||ce.zh[t]||t,s=i[t]||a;return String(s).replace(/\{([a-zA-Z0-9_]+)\}/g,(o,c)=>e&&Object.hasOwn(e,c)?String(e[c]):o)}var Me=1e5,Ht=2,V=2,U=100,Jt=1e3,$={zh:"\u4E2D\u6587",en:"English",auto:"Auto-detect"},Ne={auto:"Auto",zh:"\u4E2D\u6587",en:"English"},y={uiLanguage:"auto",backend:"api",cliPath:"",apiProvider:"anthropic",apiFormat:"anthropic-messages",apiBaseUrl:"",apiKey:"",apiKeyEnvVar:"",apiAuthType:"auto",apiHeaders:"",apiMaxTokens:4096,maxDocChars:Me,maxCacheEntries:U,promptLanguage:"zh",minCards:5,maxCards:15,customSystemPrompt:"",model:"claude-sonnet-4-6",exportFolder:"Reading/Articles",cliTimeoutMs:12e4,streaming:!0,streamingTimeoutMs:12e4},T={"anthropic-messages":{label:"Anthropic Messages",defaultBaseUrl:"https://api.anthropic.com/v1",defaultAuthType:"x-api-key"},"openai-chat":{label:"OpenAI Chat Completions",defaultBaseUrl:"https://api.openai.com/v1",defaultAuthType:"bearer",tokenLimitField:"max_tokens"},"openai-responses":{label:"OpenAI Responses",defaultBaseUrl:"https://api.openai.com/v1",defaultAuthType:"bearer"},"google-generative-ai":{label:"Google Gemini generateContent",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta",defaultAuthType:"x-goog-api-key"}},Ie={auto:"Auto",bearer:"Authorization: Bearer","x-api-key":"x-api-key","x-goog-api-key":"x-goog-api-key","api-key":"api-key",none:"None"},R={anthropic:{label:"Anthropic",format:"anthropic-messages",baseUrl:"https://api.anthropic.com/v1",authType:"x-api-key",envVar:"ANTHROPIC_API_KEY",model:"claude-sonnet-4-6"},openai:{label:"OpenAI",format:"openai-chat",baseUrl:"https://api.openai.com/v1",authType:"bearer",envVar:"OPENAI_API_KEY",tokenLimitField:"max_completion_tokens",model:"gpt-5.1"},"openai-responses":{label:"OpenAI Responses",format:"openai-responses",baseUrl:"https://api.openai.com/v1",authType:"bearer",envVar:"OPENAI_API_KEY",modelPrefix:"openai",model:"gpt-5.1"},google:{label:"Google Gemini",format:"google-generative-ai",baseUrl:"https://generativelanguage.googleapis.com/v1beta",authType:"x-goog-api-key",envVar:"GEMINI_API_KEY",model:"gemini-3-pro-preview"},openrouter:{label:"OpenRouter",format:"openai-chat",baseUrl:"https://openrouter.ai/api/v1",authType:"bearer",envVar:"OPENROUTER_API_KEY",model:""},groq:{label:"Groq",format:"openai-chat",baseUrl:"https://api.groq.com/openai/v1",authType:"bearer",envVar:"GROQ_API_KEY",model:""},deepseek:{label:"DeepSeek",format:"openai-chat",baseUrl:"https://api.deepseek.com",authType:"bearer",envVar:"DEEPSEEK_API_KEY",model:"deepseek-chat"},moonshot:{label:"Moonshot / Kimi",format:"openai-chat",baseUrl:"https://api.moonshot.ai/v1",authType:"bearer",envVar:"MOONSHOT_API_KEY",model:"kimi-k2.5"},qianfan:{label:"Baidu Qianfan",format:"openai-chat",baseUrl:"https://qianfan.baidubce.com/v2",authType:"bearer",envVar:"QIANFAN_API_KEY",model:"deepseek-v3.2"},minimax:{label:"MiniMax (Anthropic-compatible)",format:"anthropic-messages",baseUrl:"https://api.minimax.io/anthropic",authType:"bearer",envVar:"MINIMAX_API_KEY",model:"MiniMax-M2.1"},xai:{label:"xAI",format:"openai-chat",baseUrl:"https://api.x.ai/v1",authType:"bearer",envVar:"XAI_API_KEY",model:""},mistral:{label:"Mistral",format:"openai-chat",baseUrl:"https://api.mistral.ai/v1",authType:"bearer",envVar:"MISTRAL_API_KEY",model:""},cerebras:{label:"Cerebras",format:"openai-chat",baseUrl:"https://api.cerebras.ai/v1",authType:"bearer",envVar:"CEREBRAS_API_KEY",model:""},zai:{label:"Z.AI / GLM",format:"openai-chat",baseUrl:"https://api.z.ai/api/paas/v4",authType:"bearer",envVar:"ZAI_API_KEY",model:""},ollama:{label:"Ollama (local)",format:"openai-chat",baseUrl:"http://127.0.0.1:11434/v1",authType:"none",envVar:"",model:""},lmstudio:{label:"LM Studio (local)",format:"openai-chat",baseUrl:"http://127.0.0.1:1234/v1",authType:"none",envVar:"",model:""},"custom-openai":{label:"Custom OpenAI-compatible",format:"openai-chat",baseUrl:"",authType:"bearer",envVar:"",model:""},"custom-anthropic":{label:"Custom Anthropic-compatible",format:"anthropic-messages",baseUrl:"",authType:"x-api-key",envVar:"",model:""}};function _(r){return pt.default.createHash("sha1").update(r,"utf8").digest("hex")}function Re(r){return Array.isArray(r)?"["+r.map(Re).join(",")+"]":r&&typeof r=="object"?"{"+Object.keys(r).sort().map(t=>JSON.stringify(t)+":"+Re(r[t])).join(",")+"}":JSON.stringify(r)}function De(r){return r==="api"||r==="anthropic-api"}function x(r){return R[r.apiProvider]||R.anthropic}function P(r){let t=x(r),e=(r.apiFormat||t.format||"").trim();return T[e]?e:t.format}function F(r){let t=P(r),e=x(r),n=(r.apiBaseUrl||"").trim();if(n)return n.replace(/\/+$/,"");if((r.apiProvider||"").startsWith("custom-"))throw new Error(w(r,"errorCustomProviderBaseUrlRequired"));let i=(e.baseUrl||T[t].defaultBaseUrl||"").trim();if(!i)throw new Error(w(r,"errorApiBaseUrlMissing"));return i.replace(/\/+$/,"")}function Le(r){let t=(r.apiAuthType||"auto").trim();if(t&&t!=="auto")return t;let e=x(r),n=P(r);return e.authType||T[n].defaultAuthType||"bearer"}function ht(r){let t=(r.apiKey||"").trim();if(t)return t;let e=(r.apiKeyEnvVar||x(r).envVar||"").trim();return e&&process.env?.[e]?String(process.env[e]).trim():""}function I(r){let t=(r.model||"").trim();if(!t)throw new Error(w(r,"errorModelMissing"));let e=x(r),n=[r.apiProvider,e.modelPrefix].map(a=>(a||"").trim()).filter(Boolean),i=t.toLowerCase();for(let a of n){let s=a.toLowerCase();if(i.startsWith(s+"/"))return t.slice(a.length+1).trim()}return t}function Oe(r,t){let e=x(r),n=R[t]||R.anthropic,i=(r.model||"").trim(),a=!i||i===y.model||!!e.model&&i===e.model;r.apiProvider=t,r.apiFormat=n.format,r.apiBaseUrl=n.baseUrl,r.apiAuthType=n.authType||"auto",r.apiKeyEnvVar=n.envVar||"",a&&(r.model=n.model||"")}function le(r){Ne[r.uiLanguage]||(r.uiLanguage=y.uiLanguage),(!r.apiProvider||!R[r.apiProvider])&&(r.apiProvider="anthropic");let t=x(r);(!r.apiFormat||!T[r.apiFormat])&&(r.apiFormat=t.format),(!r.apiAuthType||!Ie[r.apiAuthType])&&(r.apiAuthType="auto"),r.backend==="anthropic-api"&&(r.apiProvider=r.apiProvider||"anthropic",r.apiFormat=r.apiFormat||"anthropic-messages",r.apiBaseUrl=r.apiBaseUrl||R.anthropic.baseUrl,r.apiAuthType=r.apiAuthType||"x-api-key",r.apiKeyEnvVar=r.apiKeyEnvVar||"ANTHROPIC_API_KEY");let e=Number(r.apiMaxTokens);(!Number.isFinite(e)||e<=0)&&(r.apiMaxTokens=y.apiMaxTokens);let n=Number(r.maxDocChars);return(!Number.isFinite(n)||n<1e3)&&(r.maxDocChars=y.maxDocChars),r.maxCacheEntries=mt(r.maxCacheEntries),$[r.promptLanguage]||(r.promptLanguage=y.promptLanguage),r.minCards=ut(r.minCards,y.minCards),r.maxCards=ut(r.maxCards,y.maxCards),r.maxCardsdt(s)-dt(c)||a.localeCompare(o)).slice(0,n.length-e).map(([a])=>a);for(let a of i)delete r[a];return i}function q(r){let t=le(Object.assign({},y,r||{})),e=De(t.backend),n=x(t),i=P(t),a=e?(t.apiBaseUrl||n.baseUrl||T[i]?.defaultBaseUrl||"").trim().replace(/\/+$/,""):"";return _(Re({cacheSchemaVersion:V,promptVersion:Ht,maxDocChars:Number(t.maxDocChars)||y.maxDocChars,promptLanguage:t.promptLanguage,minCards:t.minCards,maxCards:t.maxCards,customSystemPromptHash:_(t.customSystemPrompt||""),backend:t.backend,model:t.model,apiProvider:e?t.apiProvider:"",apiFormat:e?i:"",apiBaseUrl:a,apiAuthType:e?Le(t):"",apiHeadersHash:e?_(t.apiHeaders||""):"",apiMaxTokens:e?Number(t.apiMaxTokens)||y.apiMaxTokens:0,structuredOutputVersion:1}))}function j(r,t,e){return!!r&&r.schemaVersion===V&&r.contentHash===_(t)&&r.settingsHash===q(e)}function de(r){return(r||"").trim().split("/").map(t=>t.trim()).filter(t=>t&&t!=="."&&t!=="..").join("/")}function Be(r){return(r||"").split("/").map(t=>t.trim()).some(t=>t==="."||t==="..")}function _e(r,t){let e=de(r);return Be(r)?{valid:!1,reason:"unsafe",folderPath:e}:e&&!t(e)?{valid:!1,reason:"missing",folderPath:e}:{valid:!0,reason:"ok",folderPath:e}}function $t(r,t){return t?r.parent?.path===t:!r.path.includes("/")}function Ve(r,t){let e=de(t);return r.filter(n=>$t(n,e))}function Ue(r,t){return{current:r+1,total:t}}function je(r){return{total:r,processed:0,skipped:0}}function Ge(r){return{...r,processed:r.processed+1}}function He(r){return{...r,processed:r.processed+1,skipped:r.skipped+1}}function Je(r,t,e){return!!r&&j(r,t,e)}function $e(){return{cancelled:!1,currentPath:""}}function Ke(r,t){return r.currentPath=t,r}function pe(r){return!r||r.cancelled?!1:(r.cancelled=!0,!0)}function he(r,t){return r?{...r,lastAccessedAt:t||new Date().toISOString()}:null}function me(r){return JSON.stringify({version:1,entries:r||{}})}function qe(r,t){return!!t&&!!r&&typeof r.updatedAt=="string"&&r.updatedAt.trim().length>0}var z=class{constructor(t,e,n,i){this.adapter=t;this.configDir=e;this.pluginId=n;this.getSettings=i;this.cache={};this._timer=null;this._dirty=!1}filePath(){return`${this.configDir}/plugins/${this.pluginId}/cache.json`}async ensureDir(){let t=`${this.configDir}/plugins/${this.pluginId}`;try{if(typeof this.adapter.exists=="function"&&await this.adapter.exists(t))return;await this.adapter.mkdir(t)}catch{}}async readFile(){try{let t=await this.adapter.read(this.filePath()),e=JSON.parse(t);if(e&&typeof e=="object"&&e.entries&&typeof e.entries=="object")return e.entries}catch(t){let e=t instanceof Error?t.message:String(t);/not found|does not exist|ENOENT/i.test(e)||console.warn("[parallel-reader] failed to read cache.json",t)}return{}}async writeFile(){await this.ensureDir(),await this.adapter.write(this.filePath(),me(this.cache))}async load(){this.cache=await this.readFile(),this.prune().length>0&&await this.writeFile()}prune(){let t=this.getSettings();return ue(this.cache,t?.maxCacheEntries||U)}async pruneIfNeeded(){let t=this.prune();return t.length>0&&await this.save(),t}async save(){this._timer&&(clearTimeout(this._timer),this._timer=null),this.prune(),await this.writeFile(),this._dirty=!1}scheduleSave(t=5e3){this._dirty=!0,!this._timer&&(this._timer=setTimeout(()=>{this._timer=null,this._dirty&&this.save().catch(e=>console.error("[parallel-reader] failed to save cache",e))},t))}async flush(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._dirty&&await this.save()}get(t){return this.cache[t]||null}async touch(t){let e=he(this.cache[t]||null);return e?(this.cache[t]=e,this.scheduleSave(),e):null}async move(t,e){if(typeof t!="string"||typeof e!="string"||!t.trim()||!e.trim())return!1;if(t===e)return Object.hasOwn(this.cache,t);let n=this.cache[t];if(!n||Object.hasOwn(this.cache,e))return!1;let i={...this.cache,[e]:n};return delete i[t],this.cache=i,await this.save(),!0}async put(t,e,n,i){let a=new Date().toISOString();this.cache[t]={schemaVersion:V,contentHash:_(e),settingsHash:q(i||this.getSettings()),cards:n,generatedAt:a,lastAccessedAt:a},await this.save()}async replaceCards(t,e){let n=this.cache[t];if(!n)return!1;let i=new Date().toISOString();return this.cache[t]={...n,cards:(e||[]).map(a=>({title:a.title,anchor:a.anchor,gist:a.gist,bullets:a.bullets||[]})),updatedAt:i,lastAccessedAt:i},await this.save(),!0}async delete(t){this.cache[t]&&(delete this.cache[t],await this.save())}async clear(){this.cache={},await this.save()}};function ge(r,t){let e=Array.isArray(r)?r.slice():[];return!Number.isInteger(t)||t<0||t>=e.length||e.splice(t,1),e}function fe(r,t,e){if(!Number.isInteger(r)||!Number.isInteger(t)||t<=0||!Number.isInteger(e)||e<0||r<0||r>=t)return e;let n=t-1;return n<=0?-1:r=n.length||(n[t]=Object.assign({},n[t],e||{})),n}var bt=require("child_process"),wt=oe(require("fs")),be=oe(require("os")),v=oe(require("path"));var G=class extends Error{constructor(t){super("\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0"),this.name="GenerationJobAlreadyRunningError",this.code="already-running",this.key=t}},k=class extends Error{constructor(t){super("\u751F\u6210\u5DF2\u53D6\u6D88"),this.name="GenerationJobCancelledError",this.code="cancelled",this.key=t}},ze=class{constructor(t){this.key=t,this.phase="queued",this.cancelled=!1,this.startedAt=new Date().toISOString(),this.updatedAt=this.startedAt,this._cancelHandlers=[]}setPhase(t){this.phase=t,this.updatedAt=new Date().toISOString()}onCancel(t){if(typeof t=="function"){if(this.cancelled){t();return}this._cancelHandlers.push(t)}}cancel(){if(this.cancelled)return!1;this.cancelled=!0,this.setPhase("cancelled");for(let t of this._cancelHandlers.splice(0))try{t()}catch{}return!0}throwIfCancelled(){if(this.cancelled)throw new k(this.key)}},W=class{constructor(){this.jobs=new Map}get(t){return this.jobs.get(t)||null}isRunning(t){return this.jobs.has(t)}async start(t,e){if(this.jobs.has(t))throw new G(t);let n=new ze(t);this.jobs.set(t,n);try{n.setPhase("running");let i=await e(n);return n.throwIfCancelled(),i}catch(i){throw n.cancelled&&!(i instanceof k)?new k(t):i}finally{this.jobs.delete(t)}}cancel(t){let e=this.jobs.get(t);return e?e.cancel():!1}};function We(r){if(r instanceof k)return"cancelled";let t=r;if(t?.code==="cancelled")return"cancelled";let e=String(t?.message||r);return/api key|unauthorized|401|403|认证|权限/i.test(e)?"auth":/timeout|超时|timed out/i.test(e)?"timeout":/429|rate limit|too many requests/i.test(e)?"rate-limit":/非 JSON|json_schema|schema|structured/i.test(e)?"schema":/model 未设置|base url|配置|config/i.test(e)?"config":"unknown"}var Y="record_parallel_reader_cards";function Kt(r){let t=[],e=-1,n=0,i=!1,a=!1;for(let s=0;s0&&n--,n===0&&e>=0&&(t.push(r.slice(e,s+1)),e=-1))}return t}function Ye(r){let t=(r||"").trim();if(!t)return t;try{return JSON.parse(t),t}catch{}let e=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(e){let i=e[1].trim();try{return JSON.parse(i),i}catch{}}let n=Kt(t);n.sort((i,a)=>a.length-i.length);for(let i of n)try{return JSON.parse(i),i}catch{}return t}function S(r,t){let e=Ye(r),n;try{n=JSON.parse(e)}catch{throw new Error(w(t||null,"errorLlmNonJson",{excerpt:(r||"").slice(0,500)}))}return X(n)}function X(r){return(r&&Array.isArray(r.cards)?r.cards:[]).filter(e=>!!e&&typeof e=="object").map(e=>({title:typeof e.title=="string"?e.title:"(\u65E0\u6807\u9898)",anchor:typeof e.anchor=="string"?e.anchor:"",gist:typeof e.gist=="string"?e.gist:"",bullets:Array.isArray(e.bullets)?e.bullets.filter(n=>typeof n=="string"):[]}))}function Z(r){let t={type:"object",properties:{title:{type:"string"},anchor:{type:"string"},gist:{type:"string"},bullets:{type:"array",items:{type:"string"}}},required:["title","anchor","gist","bullets"]},e={type:"object",properties:{cards:{type:"array",items:t}},required:["cards"]};return r&&(t.additionalProperties=!1,e.additionalProperties=!1),e}function gt(){return{type:"json_schema",json_schema:{name:"parallel_reader_cards",strict:!0,schema:Z(!0)}}}function ft(){return{format:{type:"json_schema",name:"parallel_reader_cards",strict:!0,schema:Z(!0)}}}function yt(){return{name:Y,description:"Return the generated Parallel Reader summary cards.",input_schema:Z(!0)}}function D(r,t){if(t?.trim())return t.trim();let e=be.default.homedir(),n=process.platform==="win32",i=n?[".cmd",".exe",""]:[""],a=n?[v.default.join(e,"AppData","Roaming","npm"),v.default.join(e,"AppData","Local","Programs","claude-code"),v.default.join(e,"AppData","Local","Programs","codex"),v.default.join(e,".claude","local"),v.default.join(e,".codex","bin"),v.default.join(e,".bun","bin"),v.default.join(e,"scoop","shims"),"C:\\Program Files\\nodejs"]:[v.default.join(e,"bin"),v.default.join(e,".local","bin"),v.default.join(e,".claude","local"),v.default.join(e,".codex","bin"),v.default.join(e,".bun","bin"),v.default.join(e,".npm-global","bin"),v.default.join(e,".cargo","bin"),"/opt/homebrew/bin","/usr/local/bin"];for(let s of a)for(let o of i){let c=v.default.join(s,r+o);try{if(wt.default.existsSync(c))return c}catch{}}return r}function L(r,t,e,n,i,a=bt.spawn){return new Promise((s,o)=>{let c,l=!1,u=null,h=C=>{l||(l=!0,u&&clearTimeout(u),o(C))},f=C=>{l||(l=!0,u&&clearTimeout(u),s(C))};try{c=a(r,t,{stdio:["pipe","pipe","pipe"],env:{...process.env,PATH:[process.env.PATH||"","/usr/local/bin","/opt/homebrew/bin",v.default.join(be.default.homedir(),".local/bin"),v.default.join(be.default.homedir(),".claude/local")].filter(Boolean).join(":")}})}catch(C){return o(new Error(`Failed to start ${r}: ${C.message}`))}let p="",g="";if(u=setTimeout(()=>{try{c.kill("SIGKILL")}catch{}h(new Error(`CLI timed out (${n}ms)`))},n),i&&i.onCancel(()=>{try{c.kill("SIGKILL")}catch{}h(new k(i.key))}),!c.stdout||!c.stderr||!c.stdin){h(new Error("CLI process streams are unavailable"));return}let b=c.stdout,ae=c.stderr,Fe=c.stdin;if(b.on("data",C=>{p+=C.toString("utf8")}),ae.on("data",C=>{g+=C.toString("utf8")}),c.on("error",C=>{h(new Error(`CLI startup error: ${C.message}. Try setting an absolute CLI path.`))}),c.on("close",C=>{if(!l){if(C!==0)return h(new Error(`CLI exited with code ${C} +{excerpt}`,errorProviderRequestFailed:"{label} request failed: {error}",errorProviderApiStatus:"{label} API returned HTTP {status}: {excerpt}",noEditor:"Could not find the source note editor",settingUiLanguageName:"UI language",settingUiLanguageDesc:"Controls plugin UI, commands, and notices. Auto follows Obsidian/system language.",settingBackendName:"Backend",settingBackendDesc:"Backend for generating bullets: CLI reuses local login; API supports OpenAI, Anthropic, Gemini, and compatible proxies.",settingCliPathName:"CLI path (optional)",settingCliPathDesc:"Leave blank to auto-detect common paths. Obsidian launched from the GUI may not inherit shell PATH.",settingCliPathPlaceholder:"Example: /Users/you/bin/codex",settingCliTimeoutName:"CLI timeout (ms)",apiProviderHeader:"API Provider",settingProviderPresetName:"Provider preset",settingProviderPresetDesc:"OpenClaw-style provider/model setup: presets define protocol, base URL, and auth defaults.",settingApiFormatName:"API format",settingApiFormatDesc:"Wire protocol for the provider. OpenAI-compatible proxies usually use Chat Completions.",settingBaseUrlName:"Base URL",settingBaseUrlDesc:"Provider root URL, without /chat/completions. Blank uses the preset default.",settingApiKeyName:"API Key",settingApiKeyDesc:"Can be blank for local Ollama/LM Studio; most hosted providers require a key.",settingApiKeyEnvName:"API key env var",settingApiKeyEnvDesc:"Optional. Obsidian GUI may not inherit shell env; direct API Key is usually more reliable.",settingAuthTypeName:"Auth type",settingAuthTypeDesc:"Auto uses provider preset. Custom proxies can use Bearer, x-api-key, or none.",settingHeadersName:"Extra headers",settingHeadersDesc:"Optional. JSON object or one `Header: value` per line, useful for Cloudflare AI Gateway.",settingMaxTokensName:"Max output tokens",settingModelName:"Model",settingModelDescApi:"Model ID for API calls. Supports OpenClaw-style provider/model; matching provider prefixes are stripped.",settingModelDescCli:"Passed as --model for Claude Code. Usually ignored by Codex, which uses its default config.",settingMaxInputName:"Max input characters",settingMaxInputDesc:"Longer notes are truncated before sending to the model. Raise this for long-context models.",promptHeader:"Prompt",settingPromptLanguageName:"Output language",settingPromptLanguageDesc:"Controls title/gist/bullets language. Anchor is always copied verbatim from source.",settingCardRangeName:"Card count range",settingCardRangeDesc:"The model adapts segmentation within this range.",settingCustomPromptName:"Custom system prompt",settingCustomPromptDesc:"Optional. Variables: {minCards}, {maxCards}, {languageInstruction}, {schema}, {example}",settingCustomPromptPlaceholder:"Leave blank to use built-in prompt",settingTestBackendName:"Test current backend",settingTestBackendDescApi:"Sends a minimal LLM request to validate API settings.",settingTestBackendDescCli:"Runs ` --version` to verify the binary can be spawned.",backendTestFailed:"\u2717 Backend test failed: {error}",settingExportFolderName:"Export folder",settingExportFolderDesc:"Parallel-note output location, relative to the Vault root.",cacheHeader:"Cache",settingMaxCacheName:"Max cached notes",settingMaxCacheDesc:"Prunes least-recently accessed note caches above this limit. Cache is stored in plugin cache.json.",cachePruned:"Pruned {count} old cache entries",cachedNotesName:"Cached notes: {count}",cachedNotesDesc:"Cache is invalidated by source SHA1 and generation settings fingerprint.",clearAllCacheButton:"Clear all caches",settingStreamingName:"Streaming output",settingStreamingDesc:"Show real-time LLM output progress during generation (OpenAI Chat and Anthropic formats only)",settingStreamingTimeoutName:"Streaming timeout (ms)",settingStreamingTimeoutDesc:"Timeout for one streaming request; invalid values or values below 1000ms use the default",cmdBatchGenerate:"Batch generate parallel notes (current folder)",batchSelectFolder:"Enter the folder path to batch-process (leave blank for Vault root)",batchFolderPrompt:"Folder path",batchAlreadyRunning:"Batch generation is already running",batchCancelRequested:"Batch cancellation requested; it will stop after the current note",batchInvalidFolderInput:"Invalid folder path: {path}",batchFolderNotFound:"Folder not found: {path}",batchNoMarkdown:"No Markdown files found in that folder",batchProgress:"Batch generating: {current}/{total}",batchDone:"Batch complete: processed {processed}/{total}, skipped {skipped} (cached)",batchCancelled:"Batch cancelled: processed {processed}/{total}, skipped {skipped} (cached)"}};function Gt(r){let t=r?.uiLanguage;return t==="zh"||t==="en"?t:String((typeof navigator<"u"?navigator:null)?.language||"").toLowerCase().startsWith("zh")?"zh":"en"}function w(r,t,e){let n=Gt(r),i=ce[n]||ce.en,a=ce.en[t]||ce.zh[t]||t,s=i[t]||a;return String(s).replace(/\{([a-zA-Z0-9_]+)\}/g,(o,c)=>e&&Object.hasOwn(e,c)?String(e[c]):o)}var Me=1e5,Ht=2,V=2,U=100,Jt=1e3,$={zh:"\u4E2D\u6587",en:"English",auto:"Auto-detect"},Ne={auto:"Auto",zh:"\u4E2D\u6587",en:"English"},y={uiLanguage:"auto",backend:"api",cliPath:"",apiProvider:"anthropic",apiFormat:"anthropic-messages",apiBaseUrl:"",apiKey:"",apiKeyEnvVar:"",apiAuthType:"auto",apiHeaders:"",apiMaxTokens:4096,maxDocChars:Me,maxCacheEntries:U,promptLanguage:"zh",minCards:5,maxCards:15,customSystemPrompt:"",model:"claude-sonnet-4-6",exportFolder:"Reading/Articles",cliTimeoutMs:12e4,streaming:!0,streamingTimeoutMs:12e4},T={"anthropic-messages":{label:"Anthropic Messages",defaultBaseUrl:"https://api.anthropic.com/v1",defaultAuthType:"x-api-key"},"openai-chat":{label:"OpenAI Chat Completions",defaultBaseUrl:"https://api.openai.com/v1",defaultAuthType:"bearer",tokenLimitField:"max_tokens"},"openai-responses":{label:"OpenAI Responses",defaultBaseUrl:"https://api.openai.com/v1",defaultAuthType:"bearer"},"google-generative-ai":{label:"Google Gemini generateContent",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta",defaultAuthType:"x-goog-api-key"}},Ie={auto:"Auto",bearer:"Authorization: Bearer","x-api-key":"x-api-key","x-goog-api-key":"x-goog-api-key","api-key":"api-key",none:"None"},R={anthropic:{label:"Anthropic",format:"anthropic-messages",baseUrl:"https://api.anthropic.com/v1",authType:"x-api-key",envVar:"ANTHROPIC_API_KEY",model:"claude-sonnet-4-6"},openai:{label:"OpenAI",format:"openai-chat",baseUrl:"https://api.openai.com/v1",authType:"bearer",envVar:"OPENAI_API_KEY",tokenLimitField:"max_completion_tokens",model:"gpt-5.1"},"openai-responses":{label:"OpenAI Responses",format:"openai-responses",baseUrl:"https://api.openai.com/v1",authType:"bearer",envVar:"OPENAI_API_KEY",modelPrefix:"openai",model:"gpt-5.1"},google:{label:"Google Gemini",format:"google-generative-ai",baseUrl:"https://generativelanguage.googleapis.com/v1beta",authType:"x-goog-api-key",envVar:"GEMINI_API_KEY",model:"gemini-3-pro-preview"},openrouter:{label:"OpenRouter",format:"openai-chat",baseUrl:"https://openrouter.ai/api/v1",authType:"bearer",envVar:"OPENROUTER_API_KEY",model:""},groq:{label:"Groq",format:"openai-chat",baseUrl:"https://api.groq.com/openai/v1",authType:"bearer",envVar:"GROQ_API_KEY",model:""},deepseek:{label:"DeepSeek",format:"openai-chat",baseUrl:"https://api.deepseek.com",authType:"bearer",envVar:"DEEPSEEK_API_KEY",model:"deepseek-chat"},moonshot:{label:"Moonshot / Kimi",format:"openai-chat",baseUrl:"https://api.moonshot.ai/v1",authType:"bearer",envVar:"MOONSHOT_API_KEY",model:"kimi-k2.5"},qianfan:{label:"Baidu Qianfan",format:"openai-chat",baseUrl:"https://qianfan.baidubce.com/v2",authType:"bearer",envVar:"QIANFAN_API_KEY",model:"deepseek-v3.2"},minimax:{label:"MiniMax (Anthropic-compatible)",format:"anthropic-messages",baseUrl:"https://api.minimax.io/anthropic",authType:"bearer",envVar:"MINIMAX_API_KEY",model:"MiniMax-M2.1"},xai:{label:"xAI",format:"openai-chat",baseUrl:"https://api.x.ai/v1",authType:"bearer",envVar:"XAI_API_KEY",model:""},mistral:{label:"Mistral",format:"openai-chat",baseUrl:"https://api.mistral.ai/v1",authType:"bearer",envVar:"MISTRAL_API_KEY",model:""},cerebras:{label:"Cerebras",format:"openai-chat",baseUrl:"https://api.cerebras.ai/v1",authType:"bearer",envVar:"CEREBRAS_API_KEY",model:""},zai:{label:"Z.AI / GLM",format:"openai-chat",baseUrl:"https://api.z.ai/api/paas/v4",authType:"bearer",envVar:"ZAI_API_KEY",model:""},ollama:{label:"Ollama (local)",format:"openai-chat",baseUrl:"http://127.0.0.1:11434/v1",authType:"none",envVar:"",model:""},lmstudio:{label:"LM Studio (local)",format:"openai-chat",baseUrl:"http://127.0.0.1:1234/v1",authType:"none",envVar:"",model:""},"custom-openai":{label:"Custom OpenAI-compatible",format:"openai-chat",baseUrl:"",authType:"bearer",envVar:"",model:""},"custom-anthropic":{label:"Custom Anthropic-compatible",format:"anthropic-messages",baseUrl:"",authType:"x-api-key",envVar:"",model:""}};function _(r){return pt.default.createHash("sha1").update(r,"utf8").digest("hex")}function Re(r){return Array.isArray(r)?"["+r.map(Re).join(",")+"]":r&&typeof r=="object"?"{"+Object.keys(r).sort().map(t=>JSON.stringify(t)+":"+Re(r[t])).join(",")+"}":JSON.stringify(r)}function De(r){return r==="api"||r==="anthropic-api"}function x(r){return R[r.apiProvider]||R.anthropic}function P(r){let t=x(r),e=(r.apiFormat||t.format||"").trim();return T[e]?e:t.format}function F(r){let t=P(r),e=x(r),n=(r.apiBaseUrl||"").trim();if(n)return n.replace(/\/+$/,"");if((r.apiProvider||"").startsWith("custom-"))throw new Error(w(r,"errorCustomProviderBaseUrlRequired"));let i=(e.baseUrl||T[t].defaultBaseUrl||"").trim();if(!i)throw new Error(w(r,"errorApiBaseUrlMissing"));return i.replace(/\/+$/,"")}function Le(r){let t=(r.apiAuthType||"auto").trim();if(t&&t!=="auto")return t;let e=x(r),n=P(r);return e.authType||T[n].defaultAuthType||"bearer"}function ht(r){let t=(r.apiKey||"").trim();if(t)return t;let e=(r.apiKeyEnvVar||x(r).envVar||"").trim();return e&&process.env?.[e]?String(process.env[e]).trim():""}function I(r){let t=(r.model||"").trim();if(!t)throw new Error(w(r,"errorModelMissing"));let e=x(r),n=[r.apiProvider,e.modelPrefix].map(a=>(a||"").trim()).filter(Boolean),i=t.toLowerCase();for(let a of n){let s=a.toLowerCase();if(i.startsWith(s+"/"))return t.slice(a.length+1).trim()}return t}function Oe(r,t){let e=x(r),n=R[t]||R.anthropic,i=(r.model||"").trim(),a=!i||i===y.model||!!e.model&&i===e.model;r.apiProvider=t,r.apiFormat=n.format,r.apiBaseUrl=n.baseUrl,r.apiAuthType=n.authType||"auto",r.apiKeyEnvVar=n.envVar||"",a&&(r.model=n.model||"")}function le(r){Ne[r.uiLanguage]||(r.uiLanguage=y.uiLanguage),(!r.apiProvider||!R[r.apiProvider])&&(r.apiProvider="anthropic");let t=x(r);(!r.apiFormat||!T[r.apiFormat])&&(r.apiFormat=t.format),(!r.apiAuthType||!Ie[r.apiAuthType])&&(r.apiAuthType="auto"),r.backend==="anthropic-api"&&(r.apiProvider=r.apiProvider||"anthropic",r.apiFormat=r.apiFormat||"anthropic-messages",r.apiBaseUrl=r.apiBaseUrl||R.anthropic.baseUrl,r.apiAuthType=r.apiAuthType||"x-api-key",r.apiKeyEnvVar=r.apiKeyEnvVar||"ANTHROPIC_API_KEY");let e=Number(r.apiMaxTokens);(!Number.isFinite(e)||e<=0)&&(r.apiMaxTokens=y.apiMaxTokens);let n=Number(r.maxDocChars);return(!Number.isFinite(n)||n<1e3)&&(r.maxDocChars=y.maxDocChars),r.maxCacheEntries=mt(r.maxCacheEntries),$[r.promptLanguage]||(r.promptLanguage=y.promptLanguage),r.minCards=ut(r.minCards,y.minCards),r.maxCards=ut(r.maxCards,y.maxCards),r.maxCardsdt(s)-dt(c)||a.localeCompare(o)).slice(0,n.length-e).map(([a])=>a);for(let a of i)delete r[a];return i}function q(r){let t=le(Object.assign({},y,r||{})),e=De(t.backend),n=x(t),i=P(t),a=e?(t.apiBaseUrl||n.baseUrl||T[i]?.defaultBaseUrl||"").trim().replace(/\/+$/,""):"";return _(Re({cacheSchemaVersion:V,promptVersion:Ht,maxDocChars:Number(t.maxDocChars)||y.maxDocChars,promptLanguage:t.promptLanguage,minCards:t.minCards,maxCards:t.maxCards,customSystemPromptHash:_(t.customSystemPrompt||""),backend:t.backend,model:t.model,apiProvider:e?t.apiProvider:"",apiFormat:e?i:"",apiBaseUrl:a,apiAuthType:e?Le(t):"",apiHeadersHash:e?_(t.apiHeaders||""):"",apiMaxTokens:e?Number(t.apiMaxTokens)||y.apiMaxTokens:0,structuredOutputVersion:1}))}function j(r,t,e){return!!r&&r.schemaVersion===V&&r.contentHash===_(t)&&r.settingsHash===q(e)}function de(r){return(r||"").trim().split("/").map(t=>t.trim()).filter(t=>t&&t!=="."&&t!=="..").join("/")}function Be(r){return(r||"").split("/").map(t=>t.trim()).some(t=>t==="."||t==="..")}function _e(r,t){let e=de(r);return Be(r)?{valid:!1,reason:"unsafe",folderPath:e}:e&&!t(e)?{valid:!1,reason:"missing",folderPath:e}:{valid:!0,reason:"ok",folderPath:e}}function $t(r,t){return t?r.parent?.path===t:!r.path.includes("/")}function Ve(r,t){let e=de(t);return r.filter(n=>$t(n,e))}function Ue(r,t){return{current:r+1,total:t}}function je(r){return{total:r,processed:0,skipped:0}}function Ge(r){return{...r,processed:r.processed+1}}function He(r){return{...r,processed:r.processed+1,skipped:r.skipped+1}}function Je(r,t,e){return!!r&&j(r,t,e)}function $e(){return{cancelled:!1,currentPath:""}}function Ke(r,t){return r.currentPath=t,r}function pe(r){return!r||r.cancelled?!1:(r.cancelled=!0,!0)}function he(r,t){return r?{...r,lastAccessedAt:t||new Date().toISOString()}:null}function me(r){return JSON.stringify({version:1,entries:r||{}})}function qe(r,t){return!!t&&!!r&&typeof r.updatedAt=="string"&&r.updatedAt.trim().length>0}var z=class{constructor(t,e,n,i){this.adapter=t;this.configDir=e;this.pluginId=n;this.getSettings=i;this.cache={};this._timer=null;this._dirty=!1}filePath(){return`${this.configDir}/plugins/${this.pluginId}/cache.json`}async ensureDir(){let t=`${this.configDir}/plugins/${this.pluginId}`;try{if(typeof this.adapter.exists=="function"&&await this.adapter.exists(t))return;await this.adapter.mkdir(t)}catch{}}async readFile(){try{let t=await this.adapter.read(this.filePath()),e=JSON.parse(t);if(e&&typeof e=="object"&&e.entries&&typeof e.entries=="object")return e.entries}catch(t){let e=t instanceof Error?t.message:String(t);/not found|does not exist|ENOENT/i.test(e)||console.warn("[parallel-reader] failed to read cache.json",t)}return{}}async writeFile(){await this.ensureDir(),await this.adapter.write(this.filePath(),me(this.cache))}async load(){this.cache=await this.readFile(),this.prune().length>0&&await this.writeFile()}prune(){let t=this.getSettings();return ue(this.cache,t?.maxCacheEntries||U)}async pruneIfNeeded(){let t=this.prune();return t.length>0&&await this.save(),t}async save(){this._timer&&(clearTimeout(this._timer),this._timer=null),this.prune(),await this.writeFile(),this._dirty=!1}scheduleSave(t=5e3){this._dirty=!0,!this._timer&&(this._timer=setTimeout(()=>{this._timer=null,this._dirty&&this.save().catch(e=>console.error("[parallel-reader] failed to save cache",e))},t))}async flush(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._dirty&&await this.save()}get(t){return this.cache[t]||null}async touch(t){let e=he(this.cache[t]||null);return e?(this.cache[t]=e,this.scheduleSave(),e):null}async move(t,e){if(typeof t!="string"||typeof e!="string"||!t.trim()||!e.trim())return!1;if(t===e)return Object.hasOwn(this.cache,t);let n=this.cache[t];if(!n||Object.hasOwn(this.cache,e))return!1;let i={...this.cache,[e]:n};return delete i[t],this.cache=i,await this.save(),!0}async put(t,e,n,i){let a=new Date().toISOString();this.cache[t]={schemaVersion:V,contentHash:_(e),settingsHash:q(i||this.getSettings()),cards:n,generatedAt:a,lastAccessedAt:a},await this.save()}async replaceCards(t,e){let n=this.cache[t];if(!n)return!1;let i=new Date().toISOString();return this.cache[t]={...n,cards:(e||[]).map(a=>({title:a.title,anchor:a.anchor,gist:a.gist,bullets:a.bullets||[]})),updatedAt:i,lastAccessedAt:i},await this.save(),!0}async delete(t){this.cache[t]&&(delete this.cache[t],await this.save())}async clear(){this.cache={},await this.save()}};function ge(r,t){let e=Array.isArray(r)?r.slice():[];return!Number.isInteger(t)||t<0||t>=e.length||e.splice(t,1),e}function fe(r,t,e){if(!Number.isInteger(r)||!Number.isInteger(t)||t<=0||!Number.isInteger(e)||e<0||r<0||r>=t)return e;let n=t-1;return n<=0?-1:r=n.length||(n[t]=Object.assign({},n[t],e||{})),n}var bt=require("child_process"),wt=oe(require("fs")),be=oe(require("os")),v=oe(require("path"));var G=class extends Error{constructor(t){super("\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0"),this.name="GenerationJobAlreadyRunningError",this.code="already-running",this.key=t}},k=class extends Error{constructor(t){super("\u751F\u6210\u5DF2\u53D6\u6D88"),this.name="GenerationJobCancelledError",this.code="cancelled",this.key=t}},ze=class{constructor(t){this.key=t,this.phase="queued",this.cancelled=!1,this.startedAt=new Date().toISOString(),this.updatedAt=this.startedAt,this._cancelHandlers=[]}setPhase(t){this.phase=t,this.updatedAt=new Date().toISOString()}onCancel(t){if(typeof t=="function"){if(this.cancelled){t();return}this._cancelHandlers.push(t)}}cancel(){if(this.cancelled)return!1;this.cancelled=!0,this.setPhase("cancelled");for(let t of this._cancelHandlers.splice(0))try{t()}catch{}return!0}throwIfCancelled(){if(this.cancelled)throw new k(this.key)}},W=class{constructor(){this.jobs=new Map}get(t){return this.jobs.get(t)||null}isRunning(t){return this.jobs.has(t)}async start(t,e){if(this.jobs.has(t))throw new G(t);let n=new ze(t);this.jobs.set(t,n);try{n.setPhase("running");let i=await e(n);return n.throwIfCancelled(),i}catch(i){throw n.cancelled&&!(i instanceof k)?new k(t):i}finally{this.jobs.delete(t)}}cancel(t){let e=this.jobs.get(t);return e?e.cancel():!1}};function We(r){if(r instanceof k)return"cancelled";let t=r;if(t?.code==="cancelled")return"cancelled";let e=String(t?.message||r);return/api key|unauthorized|401|403|认证|权限/i.test(e)?"auth":/timeout|超时|timed out/i.test(e)?"timeout":/429|rate limit|too many requests/i.test(e)?"rate-limit":/非 JSON|json_schema|schema|structured/i.test(e)?"schema":/model 未设置|base url|配置|config/i.test(e)?"config":"unknown"}var Y="record_parallel_reader_cards";function Kt(r){let t=[],e=-1,n=0,i=!1,a=!1;for(let s=0;s0&&n--,n===0&&e>=0&&(t.push(r.slice(e,s+1)),e=-1))}return t}function Ye(r){let t=(r||"").trim();if(!t)return t;try{return JSON.parse(t),t}catch{}let e=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(e){let i=e[1].trim();try{return JSON.parse(i),i}catch{}}let n=Kt(t);n.sort((i,a)=>a.length-i.length);for(let i of n)try{return JSON.parse(i),i}catch{}return t}function S(r,t){let e=Ye(r),n;try{n=JSON.parse(e)}catch{throw new Error(w(t||null,"errorLlmNonJson",{excerpt:(r||"").slice(0,500)}))}return X(n)}function X(r){return(r&&Array.isArray(r.cards)?r.cards:[]).filter(e=>!!e&&typeof e=="object").map(e=>({title:typeof e.title=="string"?e.title:"(\u65E0\u6807\u9898)",anchor:typeof e.anchor=="string"?e.anchor:"",gist:typeof e.gist=="string"?e.gist:"",bullets:Array.isArray(e.bullets)?e.bullets.filter(n=>typeof n=="string"):[]}))}function Z(r){let t={type:"object",properties:{title:{type:"string"},anchor:{type:"string"},gist:{type:"string"},bullets:{type:"array",items:{type:"string"}}},required:["title","anchor","gist","bullets"]},e={type:"object",properties:{cards:{type:"array",items:t}},required:["cards"]};return r&&(t.additionalProperties=!1,e.additionalProperties=!1),e}function gt(){return{type:"json_schema",json_schema:{name:"parallel_reader_cards",strict:!0,schema:Z(!0)}}}function ft(){return{format:{type:"json_schema",name:"parallel_reader_cards",strict:!0,schema:Z(!0)}}}function yt(){return{name:Y,description:"Return the generated Parallel Reader summary cards.",input_schema:Z(!0)}}function D(r,t){if(t?.trim())return t.trim();let e=be.default.homedir(),n=process.platform==="win32",i=n?[".cmd",".exe",""]:[""],a=n?[v.default.join(e,"AppData","Roaming","npm"),v.default.join(e,"AppData","Local","Programs","claude-code"),v.default.join(e,"AppData","Local","Programs","codex"),v.default.join(e,".claude","local"),v.default.join(e,".codex","bin"),v.default.join(e,".bun","bin"),v.default.join(e,"scoop","shims"),"C:\\Program Files\\nodejs"]:[v.default.join(e,"bin"),v.default.join(e,".local","bin"),v.default.join(e,".claude","local"),v.default.join(e,".codex","bin"),v.default.join(e,".bun","bin"),v.default.join(e,".npm-global","bin"),v.default.join(e,".cargo","bin"),"/opt/homebrew/bin","/usr/local/bin"];for(let s of a)for(let o of i){let c=v.default.join(s,r+o);try{if(wt.default.existsSync(c))return c}catch{}}return r}function L(r,t,e,n,i,a=bt.spawn){return new Promise((s,o)=>{let c,u=!1,l=null,p=C=>{u||(u=!0,l&&clearTimeout(l),o(C))},f=C=>{u||(u=!0,l&&clearTimeout(l),s(C))};try{c=a(r,t,{stdio:["pipe","pipe","pipe"],env:{...process.env,PATH:[process.env.PATH||"","/usr/local/bin","/opt/homebrew/bin",v.default.join(be.default.homedir(),".local/bin"),v.default.join(be.default.homedir(),".claude/local")].filter(Boolean).join(":")}})}catch(C){return o(new Error(`Failed to start ${r}: ${C.message}`))}let h="",g="";if(l=setTimeout(()=>{try{c.kill("SIGKILL")}catch{}p(new Error(`CLI timed out (${n}ms)`))},n),i&&i.onCancel(()=>{try{c.kill("SIGKILL")}catch{}p(new k(i.key))}),!c.stdout||!c.stderr||!c.stdin){p(new Error("CLI process streams are unavailable"));return}let b=c.stdout,ae=c.stderr,Fe=c.stdin;if(b.on("data",C=>{h+=C.toString("utf8")}),ae.on("data",C=>{g+=C.toString("utf8")}),c.on("error",C=>{p(new Error(`CLI startup error: ${C.message}. Try setting an absolute CLI path.`))}),c.on("close",C=>{if(!u){if(C!==0)return p(new Error(`CLI exited with code ${C} stderr: -${g.slice(0,1e3)}`));f({stdout:p,stderr:g})}}),e)try{Fe.write(e),Fe.end()}catch{}else try{Fe.end()}catch{}})}async function Ct(r,t,e,n){let i=D("claude",e.cliPath),a=["-p","--output-format","json","--append-system-prompt",r,"--disallowed-tools","Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,TodoWrite,Task"],{stdout:s}=await L(i,a,t,e.cliTimeoutMs,n),o="";try{let c=JSON.parse(s);if(Array.isArray(c)){let l=c.find(u=>u.type==="result");l&&typeof l.result=="string"&&(o=l.result)}else c&&typeof c=="object"&&(o=c.result||c.content||"")}catch{throw new Error(`claude CLI returned unexpected output: +${g.slice(0,1e3)}`));f({stdout:h,stderr:g})}}),e)try{Fe.write(e),Fe.end()}catch{}else try{Fe.end()}catch{}})}async function Ct(r,t,e,n){let i=D("claude",e.cliPath),a=["-p","--output-format","json","--append-system-prompt",r,"--disallowed-tools","Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,TodoWrite,Task"],{stdout:s}=await L(i,a,t,e.cliTimeoutMs,n),o="";try{let c=JSON.parse(s);if(Array.isArray(c)){let u=c.find(l=>l.type==="result");u&&typeof u.result=="string"&&(o=u.result)}else c&&typeof c=="object"&&(o=c.result||c.content||"")}catch{throw new Error(`claude CLI returned unexpected output: `+s.slice(0,500))}if(!o)throw new Error(`claude CLI returned no result. Output: `+s.slice(0,500));return S(o,e)}async function vt(r,t,e,n){let i=D("codex",e.cliPath),a=`<> ${r} @@ -82,14 +82,22 @@ ${a}`}function Xt(r,t,e,n,i){return r==="en"?`Non-overridable output contract: [Document truncated]`:` -[\u6587\u6863\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]`):r,c='{"cards":[{"title":"...","anchor":"...","gist":"...","bullets":["...","..."]}]}',l=zt(n),u={minCards:i,maxCards:a,languageInstruction:s,schema:c,example:l},h=Wt(t.customSystemPrompt,u).trim(),f=Xt(n,i,a,s,c),p=Yt(n,i,a,s,c,l),g=h?`${h} +[\u6587\u6863\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]`):r,c='{"cards":[{"title":"...","anchor":"...","gist":"...","bullets":["...","..."]}]}',u=zt(n),l={minCards:i,maxCards:a,languageInstruction:s,schema:c,example:u},p=Wt(t.customSystemPrompt,l).trim(),f=Xt(n,i,a,s,c),h=Yt(n,i,a,s,c,u),g=p?`${p} -${f}`:p,b=n==="en"?`Source document: +${f}`:h,b=n==="en"?`Source document: ${o}`:`\u4EE5\u4E0B\u662F\u9700\u8981\u5904\u7406\u7684\u6587\u6863\u5168\u6587\uFF1A -${o}`;return{system:g,user:b}}function Xe(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.map(t=>{if(typeof t=="string")return t;if(t&&typeof t=="object"){let e=t;return typeof e.text=="string"?e.text:typeof e.output_text=="string"?e.output_text:""}return""}).join("");if(r&&typeof r=="object"){let t=r;return typeof t.text=="string"?t.text:typeof t.output_text=="string"?t.output_text:""}return""}function xt(r){if(typeof r.output_text=="string")return r.output_text;let t=[],e=n=>{if(n&&typeof n!="string"){if(Array.isArray(n)){n.forEach(e);return}if(typeof n=="object"){let i=n;typeof i.text=="string"&&t.push(i.text),typeof i.output_text=="string"&&t.push(i.output_text),i.type==="output_text"&&typeof i.content=="string"&&t.push(i.content),i.content&&e(i.content),i.output&&e(i.output)}}};return e(r.output),t.join("")}function At(r,t){let n=(Array.isArray(r?.content)?r.content:[]).find(i=>i&&i.type==="tool_use"&&i.name===Y);return n?typeof n.input=="string"?S(n.input,t):n.input&&typeof n.input=="object"?X(n.input):[]:null}function Pt(r){return(Array.isArray(r.content)?r.content:[]).map(e=>Xe(e)).join("").trim()}function St(r){let e=(Array.isArray(r.choices)?r.choices:[])[0]||{},n=e.message;return Xe(n?.content??e.text??"").trim()}function Tt(r){let n=((Array.isArray(r.candidates)?r.candidates:[])[0]||{}).content;return(Array.isArray(n?.parts)?n.parts:[]).map(a=>Xe(a)).join("").trim()}function Zt(r){return r.choices?.[0]?.delta?.content||""}function Qt(r){return r.type==="content_block_delta"&&r.delta?.text||""}function Q(r){switch(r){case"openai-chat":return Zt;case"anthropic-messages":return Qt;default:return null}}function Ze(r,t){let e=[],n=r.split(` -`),i=n.pop()??"";for(let a of n){let s=a.trim();if(!s||s==="data: [DONE]"||s.startsWith("event:")||!s.startsWith("data:"))continue;let o=s.slice(s.startsWith("data: ")?6:5);try{let c=JSON.parse(o),l=t(c);l&&e.push(l)}catch{}}return{deltas:e,rest:i}}async function er(r,t,e,n,i,a,s){let o=await globalThis.fetch(r,{method:"POST",headers:t,body:JSON.stringify(e),signal:a});if(!o.ok){let f=await o.text();throw new Error(w(s||null,"errorProviderApiStatus",{label:"Streaming",status:o.status,excerpt:f.slice(0,500)}))}if(!o.body)throw new Error("Response has no body for streaming");let c=o.body.getReader(),l=new TextDecoder,u="",h="";try{for(;;){let{done:f,value:p}=await c.read();if(f)break;h+=l.decode(p,{stream:!0});let g=Ze(h,n);h=g.rest;for(let b of g.deltas)u+=b;g.deltas.length>0&&i?.({accumulated:u,done:!1})}}finally{c.releaseLock()}return i?.({accumulated:u,done:!0}),u}async function Qe(r,t,e,n,i,a,s){if(typeof globalThis.fetch!="function")throw new Error("Streaming requires fetch API");let o=s?.streamingTimeoutMs??12e4,c=new AbortController;a&&(a.aborted?c.abort():a.addEventListener("abort",()=>c.abort(),{once:!0}));let l=null,u=new Promise((h,f)=>{l=setTimeout(()=>{c.abort(),f(new Error(`Streaming timed out after ${o}ms`))},o)});try{return await Promise.race([er(r,t,e,n,i,c.signal,s),u])}finally{l!==null&&clearTimeout(l)}}function Et(r){let t=Q(r);if(!t)throw new Error(`Streaming not supported for format: ${r}`);return t}function re(r,t){let e=r.replace(/\/+$/,"");for(let n of t)if(e.endsWith(n))return e;return e+t[0]}function tr(r,t){let e=(r||"").trim();if(!e)return{};if(e.startsWith("{")){let i;try{i=JSON.parse(e)}catch(s){throw new Error(w(t||null,"errorCustomHeadersJsonParse",{error:s.message}))}if(!i||typeof i!="object"||Array.isArray(i))throw new Error(w(t||null,"errorCustomHeadersJsonObject"));let a={};for(let[s,o]of Object.entries(i))typeof o=="string"&&s.trim()&&(a[s.trim()]=o);return a}let n={};for(let i of e.split(/\r?\n/)){let a=i.trim();if(!a||a.startsWith("#"))continue;let s=a.indexOf(":");if(s<=0)throw new Error(w(t||null,"errorCustomHeadersLineFormat"));let o=a.slice(0,s).trim(),c=a.slice(s+1).trim();o&&(n[o]=c)}return n}function rr(r){let t=Le(r);if(t==="none")return{};let e=ht(r);if(!e){let n=(r.apiKeyEnvVar||x(r).envVar||"").trim(),i=n?w(r,"errorApiKeyEnvHint",{envVar:n}):"";throw new Error(w(r,"errorApiKeyMissing",{hint:i}))}return t==="bearer"?{authorization:`Bearer ${e}`}:t==="x-api-key"?{"x-api-key":e}:t==="x-goog-api-key"?{"x-goog-api-key":e}:t==="api-key"?{"api-key":e}:{authorization:`Bearer ${e}`}}function H(r,t){return{"content-type":"application/json",...rr(r),...t||{},...tr(r.apiHeaders,r)}}function nr(r,t,e){if(r.json&&typeof r.json=="object")return r.json;try{return JSON.parse(r.text||"{}")}catch{throw new Error(w(e||null,"errorProviderNonJson",{label:t,excerpt:(r.text||"").slice(0,500)}))}}async function kt(r,t,e,n,i,a){let s;try{s=await r({url:e,method:"POST",headers:n,body:JSON.stringify(i),throw:!1})}catch(o){throw new Error(w(a||null,"errorProviderRequestFailed",{label:t,error:o.message||String(o)}))}if(s.status>=400)throw new Error(w(a||null,"errorProviderApiStatus",{label:t,status:s.status,excerpt:(s.text||"").slice(0,500)}));return nr(s,t,a)}function ir(r){let t=String(r?.message??r);return/(?:API (?:400|404|422):|API returned HTTP (?:400|404|422)|API 返回 HTTP (?:400|404|422))/.test(t)?/response_format|json_schema|responseJsonSchema|responseMimeType|tools?|tool_choice|unsupported|unrecognized|unknown|schema/i.test(t):!1}async function xe(r,t,e,n,i,a,s){try{return await kt(r,t,e,n,i,s)}catch(o){if(!a||!ir(o))throw o;return console.warn(`[parallel-reader] ${t} structured output rejected; retrying without structured output`,o),kt(r,t+" fallback",e,n,a,s)}}function et(r){let t=x(r),e=T[P(r)];return t.tokenLimitField||e?.tokenLimitField||"max_tokens"}function ee(r,t,e,n){let i=!n||n.structured!==!1,a={model:I(e),max_tokens:Number(e.apiMaxTokens)||4096,system:r,messages:[{role:"user",content:t}]};return i&&(a.tools=[yt()],a.tool_choice={type:"tool",name:Y}),a}function te(r,t,e,n){let i=!n||n.structured!==!1,a={model:I(e),messages:[{role:"system",content:r},{role:"user",content:t}]};return a[et(e)]=Number(e.apiMaxTokens)||4096,i&&(a.response_format=gt()),a}function Ce(r,t,e,n){let i=!n||n.structured!==!1,a={model:I(e),instructions:r,input:t,max_output_tokens:Number(e.apiMaxTokens)||4096};return i&&(a.text=ft()),a}function ve(r,t,e,n){let i=!n||n.structured!==!1,a={temperature:0,maxOutputTokens:Number(e.apiMaxTokens)||4096};return i&&(a.responseMimeType="application/json",a.responseJsonSchema=Z(!1)),{systemInstruction:{parts:[{text:r}]},contents:[{role:"user",parts:[{text:t}]}],generationConfig:a}}async function ar(r,t,e,n){let i=re(F(n),["/messages"]),a=await xe(r,"Anthropic-compatible",i,H(n,{"anthropic-version":"2023-06-01"}),ee(t,e,n),ee(t,e,n,{structured:!1}),n),s=At(a,n);return s||S(Pt(a),n)}async function sr(r,t,e,n){let i=re(F(n),["/chat/completions"]),a=await xe(r,"OpenAI-compatible Chat",i,H(n),te(t,e,n),te(t,e,n,{structured:!1}),n);return S(St(a),n)}async function or(r,t,e,n){let i=re(F(n),["/responses"]),a=await xe(r,"OpenAI Responses",i,H(n),Ce(t,e,n),Ce(t,e,n,{structured:!1}),n);return S(xt(a).trim(),n)}async function cr(r,t,e,n){let i=encodeURIComponent(I(n)),a=F(n);/:generateContent(?:\?|$)/.test(a)||(a=`${a.replace(/\/+$/,"")}/models/${i}:generateContent`);let s=H(n),o=await xe(r,"Google Gemini",a,s,ve(t,e,n),ve(t,e,n,{structured:!1}),n);return S(Tt(o),n)}async function ne(r,t,e,n){switch(P(n)){case"openai-chat":return sr(r,t,e,n);case"openai-responses":return or(r,t,e,n);case"google-generative-ai":return cr(r,t,e,n);default:return ar(r,t,e,n)}}function Ae(r){if(!r.streaming)return!1;let t=P(r);return!!Q(t)}async function lr(r,t,e,n,i){let a=re(F(e),["/chat/completions"]),s=H(e),o=te(r,t,e,{structured:!1});o.stream=!0;let c=Et("openai-chat"),l=await Qe(a,s,o,c,n,i,e);return S(l.trim(),e)}async function ur(r,t,e,n,i){let a=re(F(e),["/messages"]),s=H(e,{"anthropic-version":"2023-06-01"}),o=ee(r,t,e,{structured:!1});o.stream=!0;let c=Et("anthropic-messages"),l=await Qe(a,s,o,c,n,i,e);return S(l.trim(),e)}async function Ft(r,t,e,n,i){let a=P(e);switch(a){case"openai-chat":return lr(r,t,e,n,i);case"anthropic-messages":return ur(r,t,e,n,i);default:throw new Error(`Streaming not supported for format: ${a}`)}}async function Rt(r,t){await ne(r,'\u53EA\u8F93\u51FA JSON\uFF1A{"cards":[]}','\u8FDE\u901A\u6027\u6D4B\u8BD5\uFF1A\u8BF7\u539F\u6837\u8F93\u51FA {"cards":[]}',t);let e=P(t);return`${x(t).label} / ${T[e].label}`}async function tt(r,t,e,n){let{system:i,user:a}=we(r,t),s;switch(t.backend){case"claude-code":s=await Ct(i,a,t,e);break;case"codex":s=await vt(i,a,t,e);break;default:{if(Ae(t)){let l=new AbortController;e.onCancel(()=>l.abort()),s=await Ft(i,a,t,n,l.signal)}else s=await ne(Mt.requestUrl,i,a,t);break}}let o=s.map(c=>({title:c.title,level:2,anchor:c.anchor,gist:c.gist,startLine:J(r,c.anchor),bullets:c.bullets}));return o.sort((c,l)=>c.startLine<0&&l.startLine<0?0:c.startLine<0?1:l.startLine<0?-1:c.startLine-l.startLine),o}function rt(r,t){return t?.phase==="generating"&&r&&De(r.backend)?"cancelRequestedApiInFlight":"cancelRequested"}function nt(r){let t=[`## ${r.title}`];if(r.anchor){let e=r.anchor.replace(/\s+/g," ").trim();t.push(`> ${e}`)}return r.gist&&t.push(r.gist),r.bullets&&r.bullets.length>0&&t.push(r.bullets.map(e=>`- ${e}`).join(` +${o}`;return{system:g,user:b}}function Xe(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.map(t=>{if(typeof t=="string")return t;if(t&&typeof t=="object"){let e=t;return typeof e.text=="string"?e.text:typeof e.output_text=="string"?e.output_text:""}return""}).join("");if(r&&typeof r=="object"){let t=r;return typeof t.text=="string"?t.text:typeof t.output_text=="string"?t.output_text:""}return""}function xt(r){if(typeof r.output_text=="string")return r.output_text;let t=[],e=n=>{if(n&&typeof n!="string"){if(Array.isArray(n)){n.forEach(e);return}if(typeof n=="object"){let i=n;typeof i.text=="string"&&t.push(i.text),typeof i.output_text=="string"&&t.push(i.output_text),i.type==="output_text"&&typeof i.content=="string"&&t.push(i.content),i.content&&e(i.content),i.output&&e(i.output)}}};return e(r.output),t.join("")}function At(r,t){let n=(Array.isArray(r?.content)?r.content:[]).find(i=>i&&i.type==="tool_use"&&i.name===Y);return n?typeof n.input=="string"?S(n.input,t):n.input&&typeof n.input=="object"?X(n.input):[]:null}function Pt(r){return(Array.isArray(r.content)?r.content:[]).map(e=>Xe(e)).join("").trim()}function St(r){let e=(Array.isArray(r.choices)?r.choices:[])[0]||{},n=e.message;return Xe(n?.content??e.text??"").trim()}function Tt(r){let n=((Array.isArray(r.candidates)?r.candidates:[])[0]||{}).content;return(Array.isArray(n?.parts)?n.parts:[]).map(a=>Xe(a)).join("").trim()}function Zt(r){return r.choices?.[0]?.delta?.content||""}function Qt(r){return r.type==="content_block_delta"&&r.delta?.text||""}function Q(r){switch(r){case"openai-chat":return Zt;case"anthropic-messages":return Qt;default:return null}}function Ze(r,t){let e=[],n=r.replace(/\r\n/g,` +`),i=n.split(` + +`),a=n.endsWith(` + +`)?"":i.pop()??"",s=n.endsWith(` + +`)?i.slice(0,-1):i;for(let o of s){let c=[];for(let l of o.split(` +`)){if(!l.startsWith("data:"))continue;let p=l.slice(l.startsWith("data: ")?6:5);c.push(p)}if(c.length===0)continue;let u=c.join(` +`);if(u.trim()!=="[DONE]")try{let l=JSON.parse(u),p=t(l);p&&e.push(p)}catch{}}return{deltas:e,rest:a}}async function er(r,t,e,n,i,a,s){let o=await globalThis.fetch(r,{method:"POST",headers:t,body:JSON.stringify(e),signal:a});if(!o.ok){let f=await o.text();throw new Error(w(s||null,"errorProviderApiStatus",{label:"Streaming",status:o.status,excerpt:f.slice(0,500)}))}if(!o.body)throw new Error("Response has no body for streaming");let c=o.body.getReader(),u=new TextDecoder,l="",p="";try{for(;;){let{done:f,value:h}=await c.read();if(f)break;p+=u.decode(h,{stream:!0});let g=Ze(p,n);p=g.rest;for(let b of g.deltas)l+=b;g.deltas.length>0&&i?.({accumulated:l,done:!1})}}finally{c.releaseLock()}return i?.({accumulated:l,done:!0}),l}async function Qe(r,t,e,n,i,a,s){if(typeof globalThis.fetch!="function")throw new Error("Streaming requires fetch API");let o=s?.streamingTimeoutMs??12e4,c=new AbortController;a&&(a.aborted?c.abort():a.addEventListener("abort",()=>c.abort(),{once:!0}));let u=null,l=new Promise((p,f)=>{u=setTimeout(()=>{c.abort(),f(new Error(`Streaming timed out after ${o}ms`))},o)});try{return await Promise.race([er(r,t,e,n,i,c.signal,s),l])}finally{u!==null&&clearTimeout(u)}}function Et(r){let t=Q(r);if(!t)throw new Error(`Streaming not supported for format: ${r}`);return t}function re(r,t){let e=r.replace(/\/+$/,"");for(let n of t)if(e.endsWith(n))return e;return e+t[0]}function tr(r,t){let e=(r||"").trim();if(!e)return{};if(e.startsWith("{")){let i;try{i=JSON.parse(e)}catch(s){throw new Error(w(t||null,"errorCustomHeadersJsonParse",{error:s.message}))}if(!i||typeof i!="object"||Array.isArray(i))throw new Error(w(t||null,"errorCustomHeadersJsonObject"));let a={};for(let[s,o]of Object.entries(i))typeof o=="string"&&s.trim()&&(a[s.trim()]=o);return a}let n={};for(let i of e.split(/\r?\n/)){let a=i.trim();if(!a||a.startsWith("#"))continue;let s=a.indexOf(":");if(s<=0)throw new Error(w(t||null,"errorCustomHeadersLineFormat"));let o=a.slice(0,s).trim(),c=a.slice(s+1).trim();o&&(n[o]=c)}return n}function rr(r){let t=Le(r);if(t==="none")return{};let e=ht(r);if(!e){let n=(r.apiKeyEnvVar||x(r).envVar||"").trim(),i=n?w(r,"errorApiKeyEnvHint",{envVar:n}):"";throw new Error(w(r,"errorApiKeyMissing",{hint:i}))}return t==="bearer"?{authorization:`Bearer ${e}`}:t==="x-api-key"?{"x-api-key":e}:t==="x-goog-api-key"?{"x-goog-api-key":e}:t==="api-key"?{"api-key":e}:{authorization:`Bearer ${e}`}}function H(r,t){return{"content-type":"application/json",...rr(r),...t||{},...tr(r.apiHeaders,r)}}function nr(r,t,e){if(r.json&&typeof r.json=="object")return r.json;try{return JSON.parse(r.text||"{}")}catch{throw new Error(w(e||null,"errorProviderNonJson",{label:t,excerpt:(r.text||"").slice(0,500)}))}}async function kt(r,t,e,n,i,a){let s;try{s=await r({url:e,method:"POST",headers:n,body:JSON.stringify(i),throw:!1})}catch(o){throw new Error(w(a||null,"errorProviderRequestFailed",{label:t,error:o.message||String(o)}))}if(s.status>=400)throw new Error(w(a||null,"errorProviderApiStatus",{label:t,status:s.status,excerpt:(s.text||"").slice(0,500)}));return nr(s,t,a)}function ir(r){let t=String(r?.message??r);return/(?:API (?:400|404|422):|API returned HTTP (?:400|404|422)|API 返回 HTTP (?:400|404|422))/.test(t)?/response_format|json_schema|responseJsonSchema|responseMimeType|tools?|tool_choice|unsupported|unrecognized|unknown|schema/i.test(t):!1}async function xe(r,t,e,n,i,a,s){try{return await kt(r,t,e,n,i,s)}catch(o){if(!a||!ir(o))throw o;return console.warn(`[parallel-reader] ${t} structured output rejected; retrying without structured output`,o),kt(r,t+" fallback",e,n,a,s)}}function et(r){let t=x(r),e=T[P(r)];return t.tokenLimitField||e?.tokenLimitField||"max_tokens"}function ee(r,t,e,n){let i=!n||n.structured!==!1,a={model:I(e),max_tokens:Number(e.apiMaxTokens)||4096,system:r,messages:[{role:"user",content:t}]};return i&&(a.tools=[yt()],a.tool_choice={type:"tool",name:Y}),a}function te(r,t,e,n){let i=!n||n.structured!==!1,a={model:I(e),messages:[{role:"system",content:r},{role:"user",content:t}]};return a[et(e)]=Number(e.apiMaxTokens)||4096,i&&(a.response_format=gt()),a}function Ce(r,t,e,n){let i=!n||n.structured!==!1,a={model:I(e),instructions:r,input:t,max_output_tokens:Number(e.apiMaxTokens)||4096};return i&&(a.text=ft()),a}function ve(r,t,e,n){let i=!n||n.structured!==!1,a={temperature:0,maxOutputTokens:Number(e.apiMaxTokens)||4096};return i&&(a.responseMimeType="application/json",a.responseJsonSchema=Z(!1)),{systemInstruction:{parts:[{text:r}]},contents:[{role:"user",parts:[{text:t}]}],generationConfig:a}}async function ar(r,t,e,n){let i=re(F(n),["/messages"]),a=await xe(r,"Anthropic-compatible",i,H(n,{"anthropic-version":"2023-06-01"}),ee(t,e,n),ee(t,e,n,{structured:!1}),n),s=At(a,n);return s||S(Pt(a),n)}async function sr(r,t,e,n){let i=re(F(n),["/chat/completions"]),a=await xe(r,"OpenAI-compatible Chat",i,H(n),te(t,e,n),te(t,e,n,{structured:!1}),n);return S(St(a),n)}async function or(r,t,e,n){let i=re(F(n),["/responses"]),a=await xe(r,"OpenAI Responses",i,H(n),Ce(t,e,n),Ce(t,e,n,{structured:!1}),n);return S(xt(a).trim(),n)}async function cr(r,t,e,n){let i=encodeURIComponent(I(n)),a=F(n);/:generateContent(?:\?|$)/.test(a)||(a=`${a.replace(/\/+$/,"")}/models/${i}:generateContent`);let s=H(n),o=await xe(r,"Google Gemini",a,s,ve(t,e,n),ve(t,e,n,{structured:!1}),n);return S(Tt(o),n)}async function ne(r,t,e,n){switch(P(n)){case"openai-chat":return sr(r,t,e,n);case"openai-responses":return or(r,t,e,n);case"google-generative-ai":return cr(r,t,e,n);default:return ar(r,t,e,n)}}function Ae(r){if(!r.streaming)return!1;let t=P(r);return!!Q(t)}async function lr(r,t,e,n,i){let a=re(F(e),["/chat/completions"]),s=H(e),o=te(r,t,e,{structured:!1});o.stream=!0;let c=Et("openai-chat"),u=await Qe(a,s,o,c,n,i,e);return S(u.trim(),e)}async function ur(r,t,e,n,i){let a=re(F(e),["/messages"]),s=H(e,{"anthropic-version":"2023-06-01"}),o=ee(r,t,e,{structured:!1});o.stream=!0;let c=Et("anthropic-messages"),u=await Qe(a,s,o,c,n,i,e);return S(u.trim(),e)}async function Ft(r,t,e,n,i){let a=P(e);switch(a){case"openai-chat":return lr(r,t,e,n,i);case"anthropic-messages":return ur(r,t,e,n,i);default:throw new Error(`Streaming not supported for format: ${a}`)}}async function Rt(r,t){await ne(r,'\u53EA\u8F93\u51FA JSON\uFF1A{"cards":[]}','\u8FDE\u901A\u6027\u6D4B\u8BD5\uFF1A\u8BF7\u539F\u6837\u8F93\u51FA {"cards":[]}',t);let e=P(t);return`${x(t).label} / ${T[e].label}`}async function tt(r,t,e,n){let{system:i,user:a}=we(r,t),s;switch(t.backend){case"claude-code":s=await Ct(i,a,t,e);break;case"codex":s=await vt(i,a,t,e);break;default:{if(Ae(t)){let u=new AbortController;e.onCancel(()=>u.abort()),s=await Ft(i,a,t,n,u.signal)}else s=await ne(Mt.requestUrl,i,a,t);break}}let o=s.map(c=>({title:c.title,level:2,anchor:c.anchor,gist:c.gist,startLine:J(r,c.anchor),bullets:c.bullets}));return o.sort((c,u)=>c.startLine<0&&u.startLine<0?0:c.startLine<0?1:u.startLine<0?-1:c.startLine-u.startLine),o}function rt(r,t){return t?.phase==="generating"&&r&&De(r.backend)?"cancelRequestedApiInFlight":"cancelRequested"}function nt(r){let t=[`## ${r.title}`];if(r.anchor){let e=r.anchor.replace(/\s+/g," ").trim();t.push(`> ${e}`)}return r.gist&&t.push(r.gist),r.bullets&&r.bullets.length>0&&t.push(r.bullets.map(e=>`- ${e}`).join(` `)),t.join(` `)}function Nt(r){return[r.title,r.gist||"",...(r.bullets||[]).map(t=>"\u2022 "+t)].filter(Boolean).join(` @@ -98,6 +106,6 @@ ${o}`;return{system:g,user:b}}function Xe(r){if(typeof r=="string")return r;if(A `)}function Pe(r,t,e){if(!Number.isFinite(t)||t<=0)return-1;let n=Math.floor(t),i=e<0?-1:1;return r<0||r>=n?i<0?n-1:0:Math.min(n-1,Math.max(0,r+i))}function Se(r,t){if(!Array.isArray(r)||t<0||t>=r.length)return-1;let e=Number(r[t]?.startLine);return Number.isFinite(e)&&e>=0?e:-1}function it(r,t=80,e=.1){let n=Number(r?.top)||0,i=Math.max(0,Number(r?.height)||0),a=Math.min(Number(t)||0,i*e);return n+Math.max(0,a)}function dr(r){return typeof requestAnimationFrame=="function"?requestAnimationFrame(r):setTimeout(()=>r(Date.now()),16)}function pr(r){if(typeof cancelAnimationFrame=="function"){cancelAnimationFrame(r);return}clearTimeout(r)}function at(r,t=dr,e=pr){let n=null,i=()=>{n===null&&(n=t(()=>{n=null,r()}))};return i.cancel=()=>{n!==null&&(e(n),n=null)},i}var m=require("obsidian");async function hr(r){if(r.backend==="claude-code"){let t=D("claude",r.cliPath),{stdout:e}=await L(t,["--version"],"",1e4);return`claude @ ${t} ${e.trim()}`}if(r.backend==="codex"){let t=D("codex",r.cliPath),{stdout:e}=await L(t,["--version"],"",1e4);return`codex @ ${t} ${e.trim()}`}return Rt(m.requestUrl,r)}var Te=class extends m.PluginSettingTab{constructor(t,e){super(t,e),this.plugin=e}display(){let{containerEl:t}=this,e=(a,s)=>this.plugin.t(a,s);t.empty(),new m.Setting(t).setName(e("settingsTitle")).setHeading(),new m.Setting(t).setName(e("settingUiLanguageName")).setDesc(e("settingUiLanguageDesc")).addDropdown(a=>{for(let[s,o]of Object.entries(Ne))a.addOption(s,o);return a.setValue(this.plugin.settings.uiLanguage||y.uiLanguage).onChange(async s=>{this.plugin.settings.uiLanguage=s,await this.plugin.saveSettings(),this.display()})}),new m.Setting(t).setName(e("settingBackendName")).setDesc(e("settingBackendDesc")).addDropdown(a=>a.addOption("api","API / provider").addOption("claude-code","Claude Code CLI").addOption("codex","Codex CLI").setValue(this.plugin.settings.backend).onChange(async s=>{this.plugin.settings.backend=s,s==="api"&&!this.plugin.settings.apiBaseUrl&&Oe(this.plugin.settings,this.plugin.settings.apiProvider||"anthropic"),await this.plugin.saveSettings(),this.display()}));let n=this.plugin.settings.backend==="claude-code"||this.plugin.settings.backend==="codex";if(n&&new m.Setting(t).setName(e("settingCliPathName")).setDesc(e("settingCliPathDesc")).addText(a=>a.setPlaceholder(e("settingCliPathPlaceholder")).setValue(this.plugin.settings.cliPath).onChange(s=>{this.plugin.settings.cliPath=s.trim(),this.plugin.saveSettingsDebounced()})),n||new m.Setting(t).setName(e("apiProviderHeader")).setHeading(),!n){let a=x(this.plugin.settings);new m.Setting(t).setName(e("settingProviderPresetName")).setDesc(e("settingProviderPresetDesc")).addDropdown(s=>{for(let[o,c]of Object.entries(R))s.addOption(o,c.label);return s.setValue(this.plugin.settings.apiProvider).onChange(async o=>{Oe(this.plugin.settings,o),await this.plugin.saveSettings(),this.display()})}),new m.Setting(t).setName(e("settingApiFormatName")).setDesc(e("settingApiFormatDesc")).addDropdown(s=>{for(let[o,c]of Object.entries(T))s.addOption(o,c.label);return s.setValue(P(this.plugin.settings)).onChange(async o=>{this.plugin.settings.apiFormat=o,await this.plugin.saveSettings(),this.display()})}),new m.Setting(t).setName(e("settingBaseUrlName")).setDesc(e("settingBaseUrlDesc")).addText(s=>s.setPlaceholder((this.plugin.settings.apiProvider||"").startsWith("custom-")?"https://your-provider.example/v1":a.baseUrl||T[P(this.plugin.settings)].defaultBaseUrl).setValue(this.plugin.settings.apiBaseUrl).onChange(o=>{this.plugin.settings.apiBaseUrl=o.trim(),this.plugin.saveSettingsDebounced()})),new m.Setting(t).setName(e("settingApiKeyName")).setDesc(e("settingApiKeyDesc")).addText(s=>(s.inputEl.type="password",s.setPlaceholder("sk-...").setValue(this.plugin.settings.apiKey).onChange(o=>{this.plugin.settings.apiKey=o.trim(),this.plugin.saveSettingsDebounced()}))),new m.Setting(t).setName(e("settingApiKeyEnvName")).setDesc(e("settingApiKeyEnvDesc")).addText(s=>s.setPlaceholder(a.envVar||"OPENAI_API_KEY").setValue(this.plugin.settings.apiKeyEnvVar).onChange(o=>{this.plugin.settings.apiKeyEnvVar=o.trim(),this.plugin.saveSettingsDebounced()})),new m.Setting(t).setName(e("settingAuthTypeName")).setDesc(e("settingAuthTypeDesc")).addDropdown(s=>{for(let[o,c]of Object.entries(Ie))s.addOption(o,c);return s.setValue(this.plugin.settings.apiAuthType||"auto").onChange(async o=>{this.plugin.settings.apiAuthType=o,await this.plugin.saveSettings()})}),new m.Setting(t).setName(e("settingHeadersName")).setDesc(e("settingHeadersDesc")).addTextArea(s=>s.setPlaceholder("cf-aig-authorization: Bearer ...").setValue(this.plugin.settings.apiHeaders).onChange(o=>{this.plugin.settings.apiHeaders=o,this.plugin.saveSettingsDebounced()})),new m.Setting(t).setName(e("settingMaxTokensName")).addText(s=>s.setValue(String(this.plugin.settings.apiMaxTokens)).onChange(o=>{let c=parseInt(o,10);!Number.isNaN(c)&&c>0&&(this.plugin.settings.apiMaxTokens=c,this.plugin.saveSettingsDebounced())})),new m.Setting(t).setName(e("settingStreamingName")).setDesc(e("settingStreamingDesc")).addToggle(s=>s.setValue(this.plugin.settings.streaming??!0).onChange(async o=>{this.plugin.settings.streaming=o,await this.plugin.saveSettings()})),new m.Setting(t).setName(e("settingStreamingTimeoutName")).setDesc(e("settingStreamingTimeoutDesc")).addText(s=>s.setPlaceholder(String(y.streamingTimeoutMs)).setValue(String(this.plugin.settings.streamingTimeoutMs||y.streamingTimeoutMs)).onChange(o=>{this.plugin.settings.streamingTimeoutMs=K(o),this.plugin.saveSettingsDebounced()}))}new m.Setting(t).setName(e("settingModelName")).setDesc(e(n?"settingModelDescCli":"settingModelDescApi")).addText(a=>a.setPlaceholder(n?y.model:x(this.plugin.settings).model||"model-id").setValue(this.plugin.settings.model).onChange(s=>{this.plugin.settings.model=s.trim()||(n?y.model:""),this.plugin.saveSettingsDebounced()})),new m.Setting(t).setName(e("settingMaxInputName")).setDesc(e("settingMaxInputDesc")).addText(a=>a.setValue(String(this.plugin.settings.maxDocChars||y.maxDocChars)).onChange(s=>{let o=parseInt(s,10);!Number.isNaN(o)&&o>=1e3&&(this.plugin.settings.maxDocChars=o,this.plugin.saveSettingsDebounced())})),new m.Setting(t).setName(e("promptHeader")).setHeading(),new m.Setting(t).setName(e("settingPromptLanguageName")).setDesc(e("settingPromptLanguageDesc")).addDropdown(a=>{for(let[s,o]of Object.entries($))a.addOption(s,o);return a.setValue(this.plugin.settings.promptLanguage||y.promptLanguage).onChange(async s=>{this.plugin.settings.promptLanguage=s,await this.plugin.saveSettings()})}),new m.Setting(t).setName(e("settingCardRangeName")).setDesc(e("settingCardRangeDesc")).addText(a=>a.setPlaceholder("min").setValue(String(this.plugin.settings.minCards||y.minCards)).onChange(s=>{let o=parseInt(s,10);!Number.isNaN(o)&&o>0&&(this.plugin.settings.minCards=o,this.plugin.settings.maxCardsa.setPlaceholder("max").setValue(String(this.plugin.settings.maxCards||y.maxCards)).onChange(s=>{let o=parseInt(s,10);!Number.isNaN(o)&&o>0&&(this.plugin.settings.maxCards=Math.max(o,this.plugin.settings.minCards||y.minCards),this.plugin.saveSettingsDebounced())})),new m.Setting(t).setName(e("settingCustomPromptName")).setDesc(e("settingCustomPromptDesc")).addTextArea(a=>(a.inputEl.rows=8,a.setPlaceholder(e("settingCustomPromptPlaceholder")).setValue(this.plugin.settings.customSystemPrompt||"").onChange(s=>{this.plugin.settings.customSystemPrompt=s,this.plugin.saveSettingsDebounced()}))),new m.Setting(t).setName(e("settingTestBackendName")).setDesc(e(n?"settingTestBackendDescCli":"settingTestBackendDescApi")).addButton(a=>a.setButtonText("Test").onClick(async()=>{try{let s=await hr(this.plugin.settings);new m.Notice(`\u2713 ${s.slice(0,180)}`,8e3)}catch(s){new m.Notice(e("backendTestFailed",{error:s.message}),1e4)}})),new m.Setting(t).setName(e("settingExportFolderName")).setDesc(e("settingExportFolderDesc")).addText(a=>a.setValue(this.plugin.settings.exportFolder).onChange(s=>{this.plugin.settings.exportFolder=s.trim()||y.exportFolder,this.plugin.saveSettingsDebounced()})),new m.Setting(t).setName(e("cacheHeader")).setHeading(),new m.Setting(t).setName(e("settingMaxCacheName")).setDesc(e("settingMaxCacheDesc")).addText(a=>{a.setValue(String(this.plugin.settings.maxCacheEntries||U));let s=async()=>{let o=parseInt(a.getValue(),10);if(Number.isFinite(o)&&o>0){this.plugin.settings.maxCacheEntries=o,await this.plugin.saveSettings();let c=await this.plugin.pruneCacheIfNeeded();c.length>0&&new m.Notice(e("cachePruned",{count:c.length})),this.display()}};return a.inputEl.addEventListener("change",()=>{s()}),a.inputEl.addEventListener("keydown",o=>{o.key==="Enter"&&a.inputEl.blur()}),a});let i=Object.keys(this.plugin.cache).length;new m.Setting(t).setName(e("cachedNotesName",{count:i})).setDesc(e("cachedNotesDesc")).addButton(a=>a.setButtonText(e("clearAllCacheButton")).setWarning().onClick(async()=>{let s=Object.keys(this.plugin.cache).length;await this.plugin.cacheClear(),new m.Notice(e("cacheClearedAll",{count:s})),this.display()}))}};var E=require("obsidian");function M(r,t,e,n){let i=r.createEl("button",{cls:"parallel-reader-icon-button",attr:{type:"button","aria-label":e}});return i.title=e,typeof E.setIcon=="function"?(0,E.setIcon)(i,t):i.textContent=e,i.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Promise.resolve(n()).catch(s=>{console.error(s),new E.Notice(`${e} failed: ${s instanceof Error?s.message:String(s)}`)})}),i}function N(r,t,e,n,i){let a=r.createEl("button",{cls:i||"parallel-reader-text-button",attr:{type:"button"}});return t&&typeof E.setIcon=="function"&&(0,E.setIcon)(a,t),a.createSpan({text:e}),a.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Promise.resolve(n()).catch(o=>{console.error(o),new E.Notice(`${e} failed: ${o instanceof Error?o.message:String(o)}`)})}),a}async function O(r,t){try{await navigator.clipboard.writeText(r),new E.Notice(t)}catch(e){new E.Notice(`Copy failed: ${e instanceof Error?e.message:String(e)}`)}}function st(r){return String(r||"").split("/").map(t=>t.trim()).filter(t=>!!t&&t!==".."&&t!==".").join("/")}function ot(r){let t=st(r);if(!t)return[];let e=t.split("/");return e.map((n,i)=>e.slice(0,i+1).join("/"))}async function It(r,t){for(let e of ot(t))if(!r.vault.getAbstractFileByPath(e))try{await r.vault.createFolder(e)}catch(n){if(!r.vault.getAbstractFileByPath(e))throw n}}var A=require("obsidian");var Dt=require("obsidian");var ke=class extends Dt.Modal{constructor(t,e,n,i){super(t),this.plugin=e,this.card=n||{},this.onSave=i}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:this.plugin.t("editCardTitle")});let e=this.createLabeledInput(t,this.plugin.t("editCardTitleField"),this.card.title||""),n=this.createLabeledTextarea(t,this.plugin.t("editCardGistField"),this.card.gist||"",3),i=this.createLabeledTextarea(t,this.plugin.t("editCardBulletsField"),(this.card.bullets||[]).join(` -`),8),a=t.createDiv({cls:"parallel-reader-modal-actions"});N(a,null,this.plugin.t("editCardCancel"),()=>this.close(),"parallel-reader-text-button"),N(a,null,this.plugin.t("editCardSave"),async()=>{await this.onSave({title:e.value.trim()||this.card.title||"",gist:n.value.trim(),bullets:i.value.split(/\r?\n/).map(s=>s.trim()).filter(Boolean)}),this.close()},"parallel-reader-text-button")}createLabeledInput(t,e,n){let i=t.createDiv({cls:"parallel-reader-modal-field"});i.createEl("label",{text:e});let a=i.createEl("input",{attr:{type:"text"}});return a.value=n,a}createLabeledTextarea(t,e,n,i){let a=t.createDiv({cls:"parallel-reader-modal-field"});a.createEl("label",{text:e});let s=a.createEl("textarea");return s.rows=i,s.value=n,s}};var B="parallel-reader-view",Ee=class extends A.ItemView{constructor(e,n){super(e);this.stale=!1;this.loadingMessage="";this.errorMessage="";this.plugin=n,this.sections=[],this.sourceFile=null,this.cards=[],this.activeIdx=-1}getViewType(){return B}getDisplayText(){return this.plugin.t("displayName")}getIcon(){return"book-open"}onOpen(){let e=this.containerEl.children[1];return e.empty(),e.addClass("parallel-reader-container"),e.setAttr("tabindex","0"),e.addEventListener("keydown",n=>this.handleKeydown(n)),this.renderEmpty(),this.focusSummaryPane(),Promise.resolve()}onClose(){return Promise.resolve()}renderEmpty(){this.sourceFile=null,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let e=this.containerEl.children[1];e.empty();let n=e.createDiv({cls:"parallel-reader-empty"});n.createEl("h3",{text:this.plugin.t("appTitle")}),n.createEl("p",{text:this.plugin.t("emptyOpenNote")}),n.createEl("code",{text:this.plugin.t("commandGenerate")})}focusSummaryPane(){let e=this.containerEl.children[1];return!e||typeof e.focus!="function"?!1:(e.focus({preventScroll:!0}),!0)}loadFor(e,n,i){this.sourceFile=e,this.sections=n,this.stale=!!i,this.loadingMessage="",this.errorMessage="",this.render()}renderLoading(e,n){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage=n||this.plugin.t("loadingDefault"),this.errorMessage="",this.render()}renderStreamingPreview(e,n){this.sourceFile?.path!==e.path&&(this.sourceFile=e);let i=this.containerEl.children[1],a=i.querySelector(".parallel-reader-streaming-preview");if(a){let f=a.querySelector("pre");f&&(f.textContent=n.slice(-2e3));let p=a.querySelector(".parallel-reader-stream-counter");p&&(p.textContent=`${n.length} chars`);return}i.empty();let o=i.createDiv({cls:"parallel-reader-header"}).createDiv({cls:"parallel-reader-header-row"});o.createEl("div",{text:e.basename,cls:"parallel-reader-title"});let c=o.createDiv({cls:"parallel-reader-actions"});M(c,"square",this.plugin.t("actionCancel"),()=>{this.plugin.cancelGenerationForFile(e)});let l=i.createDiv({cls:"parallel-reader-state parallel-reader-loading parallel-reader-streaming-preview"});l.createDiv({cls:"parallel-reader-spinner"});let u=l.createEl("div",{cls:"parallel-reader-state-title"});u.createSpan({text:this.plugin.t("loadingGenerating")+" "}),u.createSpan({cls:"parallel-reader-stream-counter",text:`${n.length} chars`});let h=l.createEl("pre",{cls:"parallel-reader-stream-text"});h.textContent=n.slice(-2e3)}renderError(e,n){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage=n||this.plugin.t("errorTitle"),this.render()}renderEmptyWithHint(e){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let n=this.containerEl.children[1];n.empty();let i=n.createDiv({cls:"parallel-reader-empty"});i.createEl("h3",{text:e.basename}),i.createEl("p",{text:this.plugin.t("emptyNoCache")}),i.createEl("code",{text:this.plugin.t("commandGenerate")})}render(){let e=this.containerEl.children[1];e.empty();let i=e.createDiv({cls:"parallel-reader-header"}).createDiv({cls:"parallel-reader-header-row"});i.createEl("div",{text:this.sourceFile?.basename||"",cls:"parallel-reader-title"});let a=i.createDiv({cls:"parallel-reader-actions"});if(this.sourceFile&&(this.plugin.isGeneratingFile(this.sourceFile)?M(a,"square",this.plugin.t("actionCancel"),()=>{this.plugin.cancelGenerationForFile(this.sourceFile)}):M(a,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0)),M(a,"copy",this.plugin.t("actionCopyAll"),()=>this.plugin.copyCurrentViewMarkdown()),M(a,"download",this.plugin.t("actionExport"),()=>this.exportToVault())),this.stale){let c=e.createDiv({cls:"parallel-reader-stale-banner"});c.createSpan({text:this.plugin.t("staleBanner")}),N(c,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-stale-button")}if(this.loadingMessage){let c=e.createDiv({cls:"parallel-reader-state parallel-reader-loading"});c.createDiv({cls:"parallel-reader-spinner"}),c.createEl("div",{text:this.loadingMessage,cls:"parallel-reader-state-title"}),c.createEl("div",{text:this.plugin.t("loadingSubtitle"),cls:"parallel-reader-state-subtitle"});return}if(this.errorMessage){let c=e.createDiv({cls:"parallel-reader-state parallel-reader-error"});c.createEl("div",{text:this.plugin.t("errorTitle"),cls:"parallel-reader-state-title"}),c.createEl("div",{text:this.errorMessage,cls:"parallel-reader-state-subtitle"}),N(c,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-text-button");return}let s=e.createDiv({cls:"parallel-reader-cards"});this.cards=[];let o=this.sourceFile?.path||"";this.sections.forEach((c,l)=>{let u=s.createDiv({cls:"parallel-reader-card"});u.dataset.idx=String(l),c.startLine<0&&u.addClass("parallel-reader-card-unanchored");let h=u.createEl("div",{cls:"parallel-reader-card-title"});if(h.createSpan({text:c.title}),c.startLine<0&&h.createEl("span",{text:" \u26A0",cls:"parallel-reader-warn",title:this.plugin.t("anchorMismatch")}),c.gist){let p=u.createEl("div",{cls:"parallel-reader-gist"});A.MarkdownRenderer.render(this.app,c.gist,p,o,this).catch(()=>{p.setText(c.gist)})}let f=c.bullets||[];if(f.length>0){let p=u.createEl("div",{cls:"parallel-reader-bullets-md"}),g=f.map(b=>`- ${b}`).join(` -`);A.MarkdownRenderer.render(this.app,g,p,o,this).catch(()=>{p.setText(g)})}else c.gist||u.createEl("div",{cls:"parallel-reader-empty-li",text:this.plugin.t("emptyCard")});u.addEventListener("click",p=>{let g=window.getSelection();if(g&&g.toString().length>0)return;let b=p.target;b&&b.tagName==="A"||c.startLine>=0&&this.plugin.scrollEditorToLine(c.startLine,this.sourceFile)}),u.addEventListener("contextmenu",p=>{p.preventDefault();let g=new A.Menu;g.addItem(b=>b.setTitle(this.plugin.t("menuCopyMarkdown")).setIcon("copy").onClick(()=>O(nt(c),this.plugin.t("copiedMarkdown")))),g.addItem(b=>b.setTitle(this.plugin.t("menuCopyPlain")).setIcon("clipboard-copy").onClick(()=>O(Nt(c),this.plugin.t("copiedPlain")))),c.anchor&&g.addItem(b=>b.setTitle(this.plugin.t("menuCopyAnchor")).setIcon("quote-glyph").onClick(()=>O(c.anchor,this.plugin.t("copiedAnchor")))),g.addSeparator(),c.startLine>=0&&g.addItem(b=>b.setTitle(this.plugin.t("menuJumpSource")).setIcon("arrow-right").onClick(()=>this.plugin.scrollEditorToLine(c.startLine,this.sourceFile))),g.addSeparator(),g.addItem(b=>b.setTitle(this.plugin.t("menuEditCard")).setIcon("pencil").onClick(()=>this.openEditCardModal(l))),g.addItem(b=>b.setTitle(this.plugin.t("menuDeleteCard")).setIcon("trash").onClick(()=>this.deleteCard(l))),g.showAtMouseEvent(p)}),this.cards.push(u)}),this.activeIdx>=0&&this.cards[this.activeIdx]&&this.cards[this.activeIdx].addClass("is-active")}setActiveSection(e){e!==this.activeIdx&&(this.activeIdx>=0&&this.cards[this.activeIdx]&&this.cards[this.activeIdx].removeClass("is-active"),this.activeIdx=e,e>=0&&this.cards[e]&&(this.cards[e].addClass("is-active"),this.cards[e].scrollIntoView({block:"nearest",behavior:"smooth"})))}moveActiveSection(e){let n=Pe(this.activeIdx,this.sections.length,e);return this.setActiveSection(n),this.focusSummaryPane(),n}jumpToActiveSection(){let e=Se(this.sections,this.activeIdx);return e<0||!this.sourceFile?-1:(this.plugin.scrollEditorToLine(e,this.sourceFile),e)}handleKeydown(e){if(e.altKey&&e.key==="ArrowUp"){e.preventDefault(),this.moveActiveSection(-1);return}if(e.altKey&&e.key==="ArrowDown"){e.preventDefault(),this.moveActiveSection(1);return}!e.altKey&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&e.key==="Enter"&&this.jumpToActiveSection()>=0&&e.preventDefault()}async deleteCard(e){if(!this.sourceFile)return!1;let n=ge(this.sections,e);if(n.length===this.sections.length)return!1;let i=this.sections.length;return this.sections=n,this.activeIdx=fe(e,i,this.activeIdx),await this.plugin.cacheReplaceCards(this.sourceFile.path,n),this.render(),new A.Notice(this.plugin.t("cardDeleted")),!0}openEditCardModal(e){return!this.sourceFile||!this.sections[e]?!1:(new ke(this.app,this.plugin,this.sections[e],async n=>{await this.updateCard(e,n)}).open(),!0)}async updateCard(e,n){if(!this.sourceFile)return!1;let i=ye(this.sections,e,n);return i.length!==this.sections.length?!1:(this.sections=i,await this.plugin.cacheReplaceCards(this.sourceFile.path,i),this.render(),new A.Notice(this.plugin.t("cardSaved")),!0)}async exportToVault(){if(!this.sourceFile)return;let e=st(this.plugin.settings.exportFolder),n=`${this.sourceFile.basename} - ${this.plugin.t("displayName")}.md`,i=`${e}/${n}`,a=["---",`source: [[${this.sourceFile.basename}]]`,`generated: ${new Date().toISOString().slice(0,10)}`,"tool: parallel-reader","---","",ie(`${this.sourceFile.basename} \xB7 ${this.plugin.t("displayName")}`,this.sections),""].join(` -`),s=this.plugin.app;await It(s,e);let o=s.vault.getAbstractFileByPath(i);o instanceof A.TFile?await s.vault.modify(o,a):await s.vault.create(i,a),new A.Notice(this.plugin.t("exported",{path:i}))}};var ct=class extends d.Plugin{constructor(){super(...arguments);this.activeBatch=null;this._scrollDispose=null;this._settingsSaveTimer=null}get cache(){return this.cacheManager.cache}t(e,n){return w(this.settings||y,e,n)}async onload(){await this.loadSettings(),this.jobs=new W,this.addRibbonIcon("book-open",this.t("ribbonOpen"),async()=>{let e=this.getActiveView();await this.ensureView()&&e?.file&&await this.syncViewToFile(e.file)}),this.registerView(B,e=>new Ee(e,this)),this.addCommand({id:"run",name:this.t("cmdRun"),callback:()=>this.runForActiveFile(!1)}),this.addCommand({id:"regen",name:this.t("cmdRegen"),callback:()=>this.runForActiveFile(!0)}),this.addCommand({id:"open-view",name:this.t("cmdOpenView"),callback:async()=>{let e=this.getActiveView();await this.ensureView()&&e?.file&&this.syncViewToFile(e.file)}}),this.addCommand({id:"export-current",name:this.t("cmdExport"),callback:()=>this.exportCurrentView()}),this.addCommand({id:"copy-current-markdown",name:this.t("cmdCopyMarkdown"),callback:()=>this.copyCurrentViewMarkdown()}),this.addCommand({id:"cancel-current",name:this.t("cmdCancel"),callback:()=>this.cancelActiveGeneration()}),this.addCommand({id:"clear-current",name:this.t("cmdClearCurrent"),callback:async()=>{let e=this.getActiveView();if(!e?.file)return new d.Notice(this.t("noCurrentNote"));await this.cacheManager.delete(e.file.path),new d.Notice(this.t("cacheClearedFile",{name:e.file.basename}))}}),this.addCommand({id:"clear-all",name:this.t("cmdClearAll"),callback:async()=>{let e=Object.keys(this.cacheManager.cache).length;await this.cacheManager.clear(),new d.Notice(this.t("cacheClearedAll",{count:e}))}}),this.addCommand({id:"card-prev",name:this.t("cmdCardPrev"),callback:()=>this.moveActiveCard(-1)}),this.addCommand({id:"card-next",name:this.t("cmdCardNext"),callback:()=>this.moveActiveCard(1)}),this.addCommand({id:"card-jump",name:this.t("cmdCardJump"),callback:()=>this.jumpActiveCard()}),this.addCommand({id:"batch-generate",name:this.t("cmdBatchGenerate"),callback:()=>this.runBatchForFolder()}),this.addSettingTab(new Te(this.app,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.bindScrollSync())),this.registerEvent(this.app.workspace.on("file-open",e=>{e&&this.syncViewToFile(e)})),this.registerEvent(this.app.workspace.on("file-menu",(e,n)=>this.addFileMenuItems(e,n))),this.registerEvent(this.app.vault.on("rename",(e,n)=>{e instanceof d.TFile&&this.handleFileRename(e,n)})),this.registerEvent(this.app.vault.on("delete",e=>{e instanceof d.TFile&&this.handleFileDelete(e)})),this.bindScrollSync()}onunload(){this.flushSettingsSave(),this.flushCacheSave()}async loadSettings(){let n=(await this.loadData()||{}).settings||{};this.settings=le(Object.assign({},y,n)),this.cacheManager=new z(this.app.vault.adapter,this.app.vault.configDir,this.manifest?.id||"parallel-reader",()=>this.settings),await this.cacheManager.load()}async saveSettings(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null),await this.saveData({settings:this.settings})}saveSettingsDebounced(e=400){this._settingsSaveTimer&&clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=setTimeout(()=>{this._settingsSaveTimer=null,this.saveSettings().catch(n=>console.error("[parallel-reader] failed to save settings",n))},e)}async flushSettingsSave(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null,await this.saveSettings())}cacheTouch(e){return this.cacheManager.touch(e)}scheduleCacheSave(e=5e3){this.cacheManager.scheduleSave(e)}async flushCacheSave(){await this.cacheManager.flush()}async cacheReplaceCards(e,n){return this.cacheManager.replaceCards(e,n)}async cacheClear(){return this.cacheManager.clear()}async pruneCacheIfNeeded(){return this.cacheManager.pruneIfNeeded()}async ensureView(){let{workspace:e}=this.app,n=e.getLeavesOfType(B)[0];if(!n){let i=e.getRightLeaf(!1);if(!i)return new d.Notice(this.t("viewOpenFailed")),null;n=i,await n.setViewState({type:B,active:!0})}return await e.revealLeaf(n),n.view}getActiveView(){return this.app.workspace.getActiveViewOfType(d.MarkdownView)}getParallelView(){return this.app.workspace.getLeavesOfType(B)[0]?.view}moveActiveCard(e){let n=this.getParallelView();return n?.sections.length?n.moveActiveSection(e):(new d.Notice(this.t("noActiveCard")),-1)}jumpActiveCard(){let e=this.getParallelView();return!e||e.jumpToActiveSection()<0?(new d.Notice(this.t("noActiveCard")),!1):!0}isGeneratingFile(e){return!!e&&!!e.path&&this.jobs.isRunning(e.path)}cancelGenerationForFile(e){if(!e?.path)return new d.Notice(this.t("noCancelableJob")),!1;let n=this.jobs.get(e.path),i=rt(this.settings,n),a=this.jobs.cancel(e.path);return a&&this.activeBatch?.currentPath===e.path&&pe(this.activeBatch),new d.Notice(a?this.t(i):this.t("noCancelableJob")),a}requestBatchCancellation(){return pe(this.activeBatch)}viewIsShowingFile(e,n){return!!e&&!!n&&e.sourceFile?.path===n.path}activeFileStillMatches(e){let n=this.getActiveView();return!n?.file||n.file.path===e.path}cancelActiveGeneration(){if(this.requestBatchCancellation()){let i=this.activeBatch?.currentPath;i&&this.jobs.cancel(i),new d.Notice(this.t("batchCancelRequested"));return}let e=this.getActiveView();if(e?.file&&this.cancelGenerationForFile(e.file))return;let n=this.getParallelView();n?.sourceFile?this.cancelGenerationForFile(n.sourceFile):new d.Notice(this.t("noCancelableJob"))}confirmRegenerateEditedCards(){return new Promise(e=>{let n=this.t("confirmRegenerateEditedCards"),i=new d.Modal(this.app);i.titleEl.setText(this.t("displayName")),i.contentEl.createEl("p",{text:n});let a=i.contentEl.createDiv({cls:"modal-button-container"});a.createEl("button",{text:"Cancel"}).addEventListener("click",()=>{i.close(),e(!1)}),a.createEl("button",{text:"OK",cls:"mod-cta"}).addEventListener("click",()=>{i.close(),e(!0)}),i.onClose=()=>e(!1),i.open()})}addFileMenuItems(e,n){!(n instanceof d.TFile)||!n.path.endsWith(".md")||(e.addSeparator(),e.addItem(i=>i.setTitle(this.t("fileMenuGenerate")).setIcon("book-open").onClick(()=>this.runForFile(n,!1))),e.addItem(i=>i.setTitle(this.t("fileMenuRegen")).setIcon("refresh-cw").onClick(()=>this.runForFile(n,!0))),this.cacheManager.get(n.path)&&e.addItem(i=>i.setTitle(this.t("fileMenuClear")).setIcon("trash").onClick(async()=>{await this.cacheManager.delete(n.path),new d.Notice(this.t("cacheClearedFile",{name:n.basename}))})))}async handleFileRename(e,n){if(!(e instanceof d.TFile)||!n)return;let i=n.endsWith(".md"),a=e.path.endsWith(".md");if(!i&&!a)return;if(i&&!a){await this.cacheManager.delete(n);let o=this.getParallelView();o&&o.sourceFile?.path===n&&o.renderEmpty();return}if(!i)return;await this.cacheManager.move(n,e.path);let s=this.getParallelView();s?.sourceFile&&(s.sourceFile.path===n||s.sourceFile.path===e.path)&&(s.sourceFile=e,await this.syncViewToFile(e))}async handleFileDelete(e){if(!(e instanceof d.TFile))return;await this.cacheManager.delete(e.path);let n=this.getParallelView();n?.sourceFile?.path===e.path&&n.renderEmpty()}async exportCurrentView(){let e=this.getActiveView(),n=await this.ensureView();if(n){if((!n.sourceFile||!n.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!n.sourceFile||!n.sections.length){new d.Notice(this.t("noExportContent"));return}await n.exportToVault()}}async copyCurrentViewMarkdown(){let e=this.getActiveView(),n=await this.ensureView();if(n){if((!n.sourceFile||!n.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!n.sourceFile||!n.sections.length){new d.Notice(this.t("noCopyContent"));return}await O(ie(`${n.sourceFile.basename} \xB7 ${this.t("displayName")}`,n.sections),this.t("copiedAllMarkdown"))}}async runForActiveFile(e){let n=this.getActiveView();if(!n?.file){new d.Notice(this.t("openNoteFirst"));return}return this.runForFile(n.file,e)}async runForFile(e,n){if(!e){new d.Notice(this.t("openNoteFirst"));return}if(this.jobs.isRunning(e.path)){new d.Notice(this.t("alreadyGenerating"));return}if(qe(this.cacheManager.get(e.path),n)&&!await this.confirmRegenerateEditedCards()){new d.Notice(this.t("regenerateCancelled"));return}let i=null;return this.jobs.start(e.path,async a=>{a.setPhase("reading");let s=await this.app.vault.read(e);if(a.throwIfCancelled(),!s.trim()){new d.Notice(this.t("emptyNote"));return}if(i=await this.ensureView(),!i)return;if(a.throwIfCancelled(),a.setPhase("cache-check"),!n){let p=this.cacheManager.get(e.path);if(p&&j(p,s,this.settings)){await this.cacheTouch(e.path),this.activeFileStillMatches(e)&&await i.loadFor(e,this.resolveCardAnchors(s,p.cards),!1);return}}await i.renderLoading(e,this.t("loadingGenerating"));let o=Number(this.settings.maxDocChars)||y.maxDocChars;s.length>o&&new d.Notice(this.t("longNoteTruncated",{count:o})),new d.Notice(this.t("generatingNotice")),a.setPhase("generating");let c=i,l=c?p=>{!p.done&&this.viewIsShowingFile(c,e)&&c.renderStreamingPreview(e,p.accumulated)}:void 0,u=await tt(s,this.settings,a,l);if(a.throwIfCancelled(),u.length===0){new d.Notice(this.t("noCardsReturned"));return}let h=u.map(p=>({title:p.title,anchor:p.anchor,gist:p.gist,bullets:p.bullets}));a.setPhase("saving"),await this.cacheManager.put(e.path,s,h,this.settings),a.throwIfCancelled(),this.viewIsShowingFile(i,e)&&await i.loadFor(e,u,!1);let f=u.filter(p=>p.startLine<0).length;new d.Notice(this.t("generationDone",{count:u.length,suffix:f?this.t("unanchoredSuffix",{count:f}):""}))}).catch(async a=>{if(a instanceof G){new d.Notice(a.message);return}if(a instanceof k){i&&this.viewIsShowingFile(i,e)&&await i.renderError(e,this.t("cancelledError")),new d.Notice(this.t("cancelled"));return}let s=We(a);console.error(a),i&&this.viewIsShowingFile(i,e)&&await i.renderError(e,a.message||String(a)),new d.Notice(this.t("generationFailed",{kind:s==="unknown"?"":` (${s})`,error:a.message||a}))})}async runBatchForFolder(){if(this.activeBatch){new d.Notice(this.t("batchAlreadyRunning"));return}let e=this,n=await new Promise(l=>{class u extends d.Modal{onOpen(){this.contentEl.createEl("p",{text:e.t("batchSelectFolder")}),this.input=this.contentEl.createEl("input",{type:"text"}),this.input.placeholder=e.t("batchFolderPrompt"),this.input.style.width="100%",this.input.addEventListener("keydown",f=>{f.key==="Enter"&&(l(this.input.value.trim()),this.close())}),this.contentEl.createEl("button",{text:"OK"}).addEventListener("click",()=>{l(this.input.value.trim()),this.close()})}onClose(){l(null)}}new u(e.app).open()});if(n===null)return;let i=_e(n,l=>{let u=this.app.vault.getAbstractFileByPath(l);return!!u&&!(u instanceof d.TFile)});if(!i.valid){let l=i.reason==="unsafe"?"batchInvalidFolderInput":"batchFolderNotFound";new d.Notice(this.t(l,{path:i.folderPath||n}));return}let a=Ve(this.app.vault.getMarkdownFiles(),i.folderPath);if(a.length===0){new d.Notice(this.t("batchNoMarkdown"));return}let s=$e();this.activeBatch=s;let o=je(a.length);try{for(let l=0;l({title:a.title,level:2,anchor:a.anchor,gist:a.gist,startLine:J(e,a.anchor),bullets:a.bullets||[]}));return i.sort((a,s)=>a.startLine<0&&s.startLine<0?0:a.startLine<0?1:s.startLine<0?-1:a.startLine-s.startLine),i}async syncViewToFile(e){if(!e?.path?.endsWith(".md"))return;let n=this.app.workspace.getLeavesOfType(B);if(n.length===0)return;let i=n[0].view;if(!i||!this.activeFileStillMatches(e))return;let a=this.cacheManager.get(e.path);if(!a){await i.loadFor(e,[],!1),i.renderEmptyWithHint(e);return}let s=await this.app.vault.read(e);if(!this.activeFileStillMatches(e))return;let o=!j(a,s,this.settings);await this.cacheTouch(e.path),await i.loadFor(e,this.resolveCardAnchors(s,a.cards),o)}bindScrollSync(){this._scrollDispose&&(this._scrollDispose(),this._scrollDispose=null);let e=this.getActiveView();if(!e)return;let n=e.editor,i=n&&n.cm,a=i?.scrollDOM?i.scrollDOM:e.contentEl.querySelector(".cm-scroller");if(!a)return;let s=at(()=>this.handleEditorScroll(e));a.addEventListener("scroll",s,{passive:!0}),this._scrollDispose=()=>{s.cancel(),a.removeEventListener("scroll",s)}}handleEditorScroll(e){let n=this.getParallelView();if(!n||!e.file||n.sourceFile?.path!==e.file.path)return;let i=e.editor,a=i&&i.cm;if(!a?.scrollDOM)return;let s=a.scrollDOM.getBoundingClientRect(),o=it(s),c=0;try{let u=a.posAtCoords({x:s.left+20,y:o});u!=null&&(c=a.state.doc.lineAt(u).number-1)}catch{return}let l=-1;for(let u=0;uthis.close(),"parallel-reader-text-button"),N(a,null,this.plugin.t("editCardSave"),async()=>{await this.onSave({title:e.value.trim()||this.card.title||"",gist:n.value.trim(),bullets:i.value.split(/\r?\n/).map(s=>s.trim()).filter(Boolean)}),this.close()},"parallel-reader-text-button")}createLabeledInput(t,e,n){let i=t.createDiv({cls:"parallel-reader-modal-field"});i.createEl("label",{text:e});let a=i.createEl("input",{attr:{type:"text"}});return a.value=n,a}createLabeledTextarea(t,e,n,i){let a=t.createDiv({cls:"parallel-reader-modal-field"});a.createEl("label",{text:e});let s=a.createEl("textarea");return s.rows=i,s.value=n,s}};var B="parallel-reader-view",Ee=class extends A.ItemView{constructor(e,n){super(e);this.stale=!1;this.loadingMessage="";this.errorMessage="";this.plugin=n,this.sections=[],this.sourceFile=null,this.cards=[],this.activeIdx=-1}getViewType(){return B}getDisplayText(){return this.plugin.t("displayName")}getIcon(){return"book-open"}onOpen(){let e=this.containerEl.children[1];return e.empty(),e.addClass("parallel-reader-container"),e.setAttr("tabindex","0"),e.addEventListener("keydown",n=>this.handleKeydown(n)),this.renderEmpty(),this.focusSummaryPane(),Promise.resolve()}onClose(){return Promise.resolve()}renderEmpty(){this.sourceFile=null,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let e=this.containerEl.children[1];e.empty();let n=e.createDiv({cls:"parallel-reader-empty"});n.createEl("h3",{text:this.plugin.t("appTitle")}),n.createEl("p",{text:this.plugin.t("emptyOpenNote")}),n.createEl("code",{text:this.plugin.t("commandGenerate")})}focusSummaryPane(){let e=this.containerEl.children[1];return!e||typeof e.focus!="function"?!1:(e.focus({preventScroll:!0}),!0)}loadFor(e,n,i){this.sourceFile=e,this.sections=n,this.stale=!!i,this.loadingMessage="",this.errorMessage="",this.render()}renderLoading(e,n){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage=n||this.plugin.t("loadingDefault"),this.errorMessage="",this.render()}renderStreamingPreview(e,n){this.sourceFile?.path!==e.path&&(this.sourceFile=e);let i=this.containerEl.children[1],a=i.querySelector(".parallel-reader-streaming-preview");if(a){let f=a.querySelector("pre");f&&(f.textContent=n.slice(-2e3));let h=a.querySelector(".parallel-reader-stream-counter");h&&(h.textContent=`${n.length} chars`);return}i.empty();let o=i.createDiv({cls:"parallel-reader-header"}).createDiv({cls:"parallel-reader-header-row"});o.createEl("div",{text:e.basename,cls:"parallel-reader-title"});let c=o.createDiv({cls:"parallel-reader-actions"});M(c,"square",this.plugin.t("actionCancel"),()=>{this.plugin.cancelGenerationForFile(e)});let u=i.createDiv({cls:"parallel-reader-state parallel-reader-loading parallel-reader-streaming-preview"});u.createDiv({cls:"parallel-reader-spinner"});let l=u.createEl("div",{cls:"parallel-reader-state-title"});l.createSpan({text:this.plugin.t("loadingGenerating")+" "}),l.createSpan({cls:"parallel-reader-stream-counter",text:`${n.length} chars`});let p=u.createEl("pre",{cls:"parallel-reader-stream-text"});p.textContent=n.slice(-2e3)}renderError(e,n){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage=n||this.plugin.t("errorTitle"),this.render()}renderEmptyWithHint(e){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let n=this.containerEl.children[1];n.empty();let i=n.createDiv({cls:"parallel-reader-empty"});i.createEl("h3",{text:e.basename}),i.createEl("p",{text:this.plugin.t("emptyNoCache")}),i.createEl("code",{text:this.plugin.t("commandGenerate")})}render(){let e=this.containerEl.children[1];e.empty();let i=e.createDiv({cls:"parallel-reader-header"}).createDiv({cls:"parallel-reader-header-row"});i.createEl("div",{text:this.sourceFile?.basename||"",cls:"parallel-reader-title"});let a=i.createDiv({cls:"parallel-reader-actions"});if(this.sourceFile&&(this.plugin.isGeneratingFile(this.sourceFile)?M(a,"square",this.plugin.t("actionCancel"),()=>{this.plugin.cancelGenerationForFile(this.sourceFile)}):M(a,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0)),M(a,"copy",this.plugin.t("actionCopyAll"),()=>this.plugin.copyCurrentViewMarkdown()),M(a,"download",this.plugin.t("actionExport"),()=>this.exportToVault())),this.stale){let c=e.createDiv({cls:"parallel-reader-stale-banner"});c.createSpan({text:this.plugin.t("staleBanner")}),N(c,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-stale-button")}if(this.loadingMessage){let c=e.createDiv({cls:"parallel-reader-state parallel-reader-loading"});c.createDiv({cls:"parallel-reader-spinner"}),c.createEl("div",{text:this.loadingMessage,cls:"parallel-reader-state-title"}),c.createEl("div",{text:this.plugin.t("loadingSubtitle"),cls:"parallel-reader-state-subtitle"});return}if(this.errorMessage){let c=e.createDiv({cls:"parallel-reader-state parallel-reader-error"});c.createEl("div",{text:this.plugin.t("errorTitle"),cls:"parallel-reader-state-title"}),c.createEl("div",{text:this.errorMessage,cls:"parallel-reader-state-subtitle"}),N(c,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-text-button");return}let s=e.createDiv({cls:"parallel-reader-cards"});this.cards=[];let o=this.sourceFile?.path||"";this.sections.forEach((c,u)=>{let l=s.createDiv({cls:"parallel-reader-card"});l.dataset.idx=String(u),c.startLine<0&&l.addClass("parallel-reader-card-unanchored");let p=l.createEl("div",{cls:"parallel-reader-card-title"});if(p.createSpan({text:c.title}),c.startLine<0&&p.createEl("span",{text:" \u26A0",cls:"parallel-reader-warn",title:this.plugin.t("anchorMismatch")}),c.gist){let h=l.createEl("div",{cls:"parallel-reader-gist"});A.MarkdownRenderer.render(this.app,c.gist,h,o,this).catch(()=>{h.setText(c.gist)})}let f=c.bullets||[];if(f.length>0){let h=l.createEl("div",{cls:"parallel-reader-bullets-md"}),g=f.map(b=>`- ${b}`).join(` +`);A.MarkdownRenderer.render(this.app,g,h,o,this).catch(()=>{h.setText(g)})}else c.gist||l.createEl("div",{cls:"parallel-reader-empty-li",text:this.plugin.t("emptyCard")});l.addEventListener("click",h=>{let g=window.getSelection();if(g&&g.toString().length>0)return;let b=h.target;b&&b.tagName==="A"||c.startLine>=0&&this.plugin.scrollEditorToLine(c.startLine,this.sourceFile)}),l.addEventListener("contextmenu",h=>{h.preventDefault();let g=new A.Menu;g.addItem(b=>b.setTitle(this.plugin.t("menuCopyMarkdown")).setIcon("copy").onClick(()=>O(nt(c),this.plugin.t("copiedMarkdown")))),g.addItem(b=>b.setTitle(this.plugin.t("menuCopyPlain")).setIcon("clipboard-copy").onClick(()=>O(Nt(c),this.plugin.t("copiedPlain")))),c.anchor&&g.addItem(b=>b.setTitle(this.plugin.t("menuCopyAnchor")).setIcon("quote-glyph").onClick(()=>O(c.anchor,this.plugin.t("copiedAnchor")))),g.addSeparator(),c.startLine>=0&&g.addItem(b=>b.setTitle(this.plugin.t("menuJumpSource")).setIcon("arrow-right").onClick(()=>this.plugin.scrollEditorToLine(c.startLine,this.sourceFile))),g.addSeparator(),g.addItem(b=>b.setTitle(this.plugin.t("menuEditCard")).setIcon("pencil").onClick(()=>this.openEditCardModal(u))),g.addItem(b=>b.setTitle(this.plugin.t("menuDeleteCard")).setIcon("trash").onClick(()=>this.deleteCard(u))),g.showAtMouseEvent(h)}),this.cards.push(l)}),this.activeIdx>=0&&this.cards[this.activeIdx]&&this.cards[this.activeIdx].addClass("is-active")}setActiveSection(e){e!==this.activeIdx&&(this.activeIdx>=0&&this.cards[this.activeIdx]&&this.cards[this.activeIdx].removeClass("is-active"),this.activeIdx=e,e>=0&&this.cards[e]&&(this.cards[e].addClass("is-active"),this.cards[e].scrollIntoView({block:"nearest",behavior:"smooth"})))}moveActiveSection(e){let n=Pe(this.activeIdx,this.sections.length,e);return this.setActiveSection(n),this.focusSummaryPane(),n}jumpToActiveSection(){let e=Se(this.sections,this.activeIdx);return e<0||!this.sourceFile?-1:(this.plugin.scrollEditorToLine(e,this.sourceFile),e)}handleKeydown(e){if(e.altKey&&e.key==="ArrowUp"){e.preventDefault(),this.moveActiveSection(-1);return}if(e.altKey&&e.key==="ArrowDown"){e.preventDefault(),this.moveActiveSection(1);return}!e.altKey&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&e.key==="Enter"&&this.jumpToActiveSection()>=0&&e.preventDefault()}async deleteCard(e){if(!this.sourceFile)return!1;let n=ge(this.sections,e);if(n.length===this.sections.length)return!1;let i=this.sections.length;return this.sections=n,this.activeIdx=fe(e,i,this.activeIdx),await this.plugin.cacheReplaceCards(this.sourceFile.path,n),this.render(),new A.Notice(this.plugin.t("cardDeleted")),!0}openEditCardModal(e){return!this.sourceFile||!this.sections[e]?!1:(new ke(this.app,this.plugin,this.sections[e],async n=>{await this.updateCard(e,n)}).open(),!0)}async updateCard(e,n){if(!this.sourceFile)return!1;let i=ye(this.sections,e,n);return i.length!==this.sections.length?!1:(this.sections=i,await this.plugin.cacheReplaceCards(this.sourceFile.path,i),this.render(),new A.Notice(this.plugin.t("cardSaved")),!0)}async exportToVault(){if(!this.sourceFile)return;let e=st(this.plugin.settings.exportFolder),n=`${this.sourceFile.basename} - ${this.plugin.t("displayName")}.md`,i=`${e}/${n}`,a=["---",`source: [[${this.sourceFile.basename}]]`,`generated: ${new Date().toISOString().slice(0,10)}`,"tool: parallel-reader","---","",ie(`${this.sourceFile.basename} \xB7 ${this.plugin.t("displayName")}`,this.sections),""].join(` +`),s=this.plugin.app;await It(s,e);let o=s.vault.getAbstractFileByPath(i);o instanceof A.TFile?await s.vault.modify(o,a):await s.vault.create(i,a),new A.Notice(this.plugin.t("exported",{path:i}))}};var ct=class extends d.Plugin{constructor(){super(...arguments);this.activeBatch=null;this._scrollDispose=null;this._settingsSaveTimer=null}get cache(){return this.cacheManager.cache}t(e,n){return w(this.settings||y,e,n)}async onload(){await this.loadSettings(),this.jobs=new W,this.addRibbonIcon("book-open",this.t("ribbonOpen"),async()=>{let e=this.getActiveView();await this.ensureView()&&e?.file&&await this.syncViewToFile(e.file)}),this.registerView(B,e=>new Ee(e,this)),this.addCommand({id:"run",name:this.t("cmdRun"),callback:()=>this.runForActiveFile(!1)}),this.addCommand({id:"regen",name:this.t("cmdRegen"),callback:()=>this.runForActiveFile(!0)}),this.addCommand({id:"open-view",name:this.t("cmdOpenView"),callback:async()=>{let e=this.getActiveView();await this.ensureView()&&e?.file&&this.syncViewToFile(e.file)}}),this.addCommand({id:"export-current",name:this.t("cmdExport"),callback:()=>this.exportCurrentView()}),this.addCommand({id:"copy-current-markdown",name:this.t("cmdCopyMarkdown"),callback:()=>this.copyCurrentViewMarkdown()}),this.addCommand({id:"cancel-current",name:this.t("cmdCancel"),callback:()=>this.cancelActiveGeneration()}),this.addCommand({id:"clear-current",name:this.t("cmdClearCurrent"),callback:async()=>{let e=this.getActiveView();if(!e?.file)return new d.Notice(this.t("noCurrentNote"));await this.cacheManager.delete(e.file.path),new d.Notice(this.t("cacheClearedFile",{name:e.file.basename}))}}),this.addCommand({id:"clear-all",name:this.t("cmdClearAll"),callback:async()=>{let e=Object.keys(this.cacheManager.cache).length;await this.cacheManager.clear(),new d.Notice(this.t("cacheClearedAll",{count:e}))}}),this.addCommand({id:"card-prev",name:this.t("cmdCardPrev"),callback:()=>this.moveActiveCard(-1)}),this.addCommand({id:"card-next",name:this.t("cmdCardNext"),callback:()=>this.moveActiveCard(1)}),this.addCommand({id:"card-jump",name:this.t("cmdCardJump"),callback:()=>this.jumpActiveCard()}),this.addCommand({id:"batch-generate",name:this.t("cmdBatchGenerate"),callback:()=>this.runBatchForFolder()}),this.addSettingTab(new Te(this.app,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.bindScrollSync())),this.registerEvent(this.app.workspace.on("file-open",e=>{e&&this.syncViewToFile(e)})),this.registerEvent(this.app.workspace.on("file-menu",(e,n)=>this.addFileMenuItems(e,n))),this.registerEvent(this.app.vault.on("rename",(e,n)=>{e instanceof d.TFile&&this.handleFileRename(e,n)})),this.registerEvent(this.app.vault.on("delete",e=>{e instanceof d.TFile&&this.handleFileDelete(e)})),this.bindScrollSync()}onunload(){this.flushSettingsSave(),this.flushCacheSave()}async loadSettings(){let n=(await this.loadData()||{}).settings||{};this.settings=le(Object.assign({},y,n)),this.cacheManager=new z(this.app.vault.adapter,this.app.vault.configDir,this.manifest?.id||"parallel-reader",()=>this.settings),await this.cacheManager.load()}async saveSettings(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null),await this.saveData({settings:this.settings})}saveSettingsDebounced(e=400){this._settingsSaveTimer&&clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=setTimeout(()=>{this._settingsSaveTimer=null,this.saveSettings().catch(n=>console.error("[parallel-reader] failed to save settings",n))},e)}async flushSettingsSave(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null,await this.saveSettings())}cacheTouch(e){return this.cacheManager.touch(e)}scheduleCacheSave(e=5e3){this.cacheManager.scheduleSave(e)}async flushCacheSave(){await this.cacheManager.flush()}async cacheReplaceCards(e,n){return this.cacheManager.replaceCards(e,n)}async cacheClear(){return this.cacheManager.clear()}async pruneCacheIfNeeded(){return this.cacheManager.pruneIfNeeded()}async ensureView(){let{workspace:e}=this.app,n=e.getLeavesOfType(B)[0];if(!n){let i=e.getRightLeaf(!1);if(!i)return new d.Notice(this.t("viewOpenFailed")),null;n=i,await n.setViewState({type:B,active:!0})}return await e.revealLeaf(n),n.view}getActiveView(){return this.app.workspace.getActiveViewOfType(d.MarkdownView)}getParallelView(){return this.app.workspace.getLeavesOfType(B)[0]?.view}moveActiveCard(e){let n=this.getParallelView();return n?.sections.length?n.moveActiveSection(e):(new d.Notice(this.t("noActiveCard")),-1)}jumpActiveCard(){let e=this.getParallelView();return!e||e.jumpToActiveSection()<0?(new d.Notice(this.t("noActiveCard")),!1):!0}isGeneratingFile(e){return!!e&&!!e.path&&this.jobs.isRunning(e.path)}cancelGenerationForFile(e){if(!e?.path)return new d.Notice(this.t("noCancelableJob")),!1;let n=this.jobs.get(e.path),i=rt(this.settings,n),a=this.jobs.cancel(e.path);return a&&this.activeBatch?.currentPath===e.path&&pe(this.activeBatch),new d.Notice(a?this.t(i):this.t("noCancelableJob")),a}requestBatchCancellation(){return pe(this.activeBatch)}viewIsShowingFile(e,n){return!!e&&!!n&&e.sourceFile?.path===n.path}activeFileStillMatches(e){let n=this.getActiveView();return!n?.file||n.file.path===e.path}cancelActiveGeneration(){if(this.requestBatchCancellation()){let i=this.activeBatch?.currentPath;i&&this.jobs.cancel(i),new d.Notice(this.t("batchCancelRequested"));return}let e=this.getActiveView();if(e?.file&&this.cancelGenerationForFile(e.file))return;let n=this.getParallelView();n?.sourceFile?this.cancelGenerationForFile(n.sourceFile):new d.Notice(this.t("noCancelableJob"))}confirmRegenerateEditedCards(){return new Promise(e=>{let n=this.t("confirmRegenerateEditedCards"),i=new d.Modal(this.app);i.titleEl.setText(this.t("displayName")),i.contentEl.createEl("p",{text:n});let a=i.contentEl.createDiv({cls:"modal-button-container"});a.createEl("button",{text:"Cancel"}).addEventListener("click",()=>{i.close(),e(!1)}),a.createEl("button",{text:"OK",cls:"mod-cta"}).addEventListener("click",()=>{i.close(),e(!0)}),i.onClose=()=>e(!1),i.open()})}addFileMenuItems(e,n){!(n instanceof d.TFile)||!n.path.endsWith(".md")||(e.addSeparator(),e.addItem(i=>i.setTitle(this.t("fileMenuGenerate")).setIcon("book-open").onClick(()=>this.runForFile(n,!1))),e.addItem(i=>i.setTitle(this.t("fileMenuRegen")).setIcon("refresh-cw").onClick(()=>this.runForFile(n,!0))),this.cacheManager.get(n.path)&&e.addItem(i=>i.setTitle(this.t("fileMenuClear")).setIcon("trash").onClick(async()=>{await this.cacheManager.delete(n.path),new d.Notice(this.t("cacheClearedFile",{name:n.basename}))})))}async handleFileRename(e,n){if(!(e instanceof d.TFile)||!n)return;let i=n.endsWith(".md"),a=e.path.endsWith(".md");if(!i&&!a)return;if(i&&!a){await this.cacheManager.delete(n);let o=this.getParallelView();o&&o.sourceFile?.path===n&&o.renderEmpty();return}if(!i)return;await this.cacheManager.move(n,e.path);let s=this.getParallelView();s?.sourceFile&&(s.sourceFile.path===n||s.sourceFile.path===e.path)&&(s.sourceFile=e,await this.syncViewToFile(e))}async handleFileDelete(e){if(!(e instanceof d.TFile))return;await this.cacheManager.delete(e.path);let n=this.getParallelView();n?.sourceFile?.path===e.path&&n.renderEmpty()}async exportCurrentView(){let e=this.getActiveView(),n=await this.ensureView();if(n){if((!n.sourceFile||!n.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!n.sourceFile||!n.sections.length){new d.Notice(this.t("noExportContent"));return}await n.exportToVault()}}async copyCurrentViewMarkdown(){let e=this.getActiveView(),n=await this.ensureView();if(n){if((!n.sourceFile||!n.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!n.sourceFile||!n.sections.length){new d.Notice(this.t("noCopyContent"));return}await O(ie(`${n.sourceFile.basename} \xB7 ${this.t("displayName")}`,n.sections),this.t("copiedAllMarkdown"))}}async runForActiveFile(e){let n=this.getActiveView();if(!n?.file){new d.Notice(this.t("openNoteFirst"));return}return this.runForFile(n.file,e)}async runForFile(e,n){if(!e){new d.Notice(this.t("openNoteFirst"));return}if(this.jobs.isRunning(e.path)){new d.Notice(this.t("alreadyGenerating"));return}if(qe(this.cacheManager.get(e.path),n)&&!await this.confirmRegenerateEditedCards()){new d.Notice(this.t("regenerateCancelled"));return}let i=null;return this.jobs.start(e.path,async a=>{a.setPhase("reading");let s=await this.app.vault.read(e);if(a.throwIfCancelled(),!s.trim()){new d.Notice(this.t("emptyNote"));return}if(i=await this.ensureView(),!i)return;if(a.throwIfCancelled(),a.setPhase("cache-check"),!n){let h=this.cacheManager.get(e.path);if(h&&j(h,s,this.settings)){await this.cacheTouch(e.path),this.activeFileStillMatches(e)&&await i.loadFor(e,this.resolveCardAnchors(s,h.cards),!1);return}}await i.renderLoading(e,this.t("loadingGenerating"));let o=Number(this.settings.maxDocChars)||y.maxDocChars;s.length>o&&new d.Notice(this.t("longNoteTruncated",{count:o})),new d.Notice(this.t("generatingNotice")),a.setPhase("generating");let c=i,u=c?h=>{!h.done&&this.viewIsShowingFile(c,e)&&c.renderStreamingPreview(e,h.accumulated)}:void 0,l=await tt(s,this.settings,a,u);if(a.throwIfCancelled(),l.length===0){new d.Notice(this.t("noCardsReturned"));return}let p=l.map(h=>({title:h.title,anchor:h.anchor,gist:h.gist,bullets:h.bullets}));a.setPhase("saving"),await this.cacheManager.put(e.path,s,p,this.settings),a.throwIfCancelled(),this.viewIsShowingFile(i,e)&&await i.loadFor(e,l,!1);let f=l.filter(h=>h.startLine<0).length;new d.Notice(this.t("generationDone",{count:l.length,suffix:f?this.t("unanchoredSuffix",{count:f}):""}))}).catch(async a=>{if(a instanceof G){new d.Notice(a.message);return}if(a instanceof k){i&&this.viewIsShowingFile(i,e)&&await i.renderError(e,this.t("cancelledError")),new d.Notice(this.t("cancelled"));return}let s=We(a);console.error(a),i&&this.viewIsShowingFile(i,e)&&await i.renderError(e,a.message||String(a)),new d.Notice(this.t("generationFailed",{kind:s==="unknown"?"":` (${s})`,error:a.message||a}))})}async runBatchForFolder(){if(this.activeBatch){new d.Notice(this.t("batchAlreadyRunning"));return}let e=this,n=await new Promise(u=>{class l extends d.Modal{onOpen(){this.contentEl.createEl("p",{text:e.t("batchSelectFolder")}),this.input=this.contentEl.createEl("input",{type:"text"}),this.input.placeholder=e.t("batchFolderPrompt"),this.input.style.width="100%",this.input.addEventListener("keydown",f=>{f.key==="Enter"&&(u(this.input.value.trim()),this.close())}),this.contentEl.createEl("button",{text:"OK"}).addEventListener("click",()=>{u(this.input.value.trim()),this.close()})}onClose(){u(null)}}new l(e.app).open()});if(n===null)return;let i=_e(n,u=>{let l=this.app.vault.getAbstractFileByPath(u);return!!l&&!(l instanceof d.TFile)});if(!i.valid){let u=i.reason==="unsafe"?"batchInvalidFolderInput":"batchFolderNotFound";new d.Notice(this.t(u,{path:i.folderPath||n}));return}let a=Ve(this.app.vault.getMarkdownFiles(),i.folderPath);if(a.length===0){new d.Notice(this.t("batchNoMarkdown"));return}let s=$e();this.activeBatch=s;let o=je(a.length);try{for(let u=0;u({title:a.title,level:2,anchor:a.anchor,gist:a.gist,startLine:J(e,a.anchor),bullets:a.bullets||[]}));return i.sort((a,s)=>a.startLine<0&&s.startLine<0?0:a.startLine<0?1:s.startLine<0?-1:a.startLine-s.startLine),i}async syncViewToFile(e){if(!e?.path?.endsWith(".md"))return;let n=this.app.workspace.getLeavesOfType(B);if(n.length===0)return;let i=n[0].view;if(!i||!this.activeFileStillMatches(e))return;let a=this.cacheManager.get(e.path);if(!a){await i.loadFor(e,[],!1),i.renderEmptyWithHint(e);return}let s=await this.app.vault.read(e);if(!this.activeFileStillMatches(e))return;let o=!j(a,s,this.settings);await this.cacheTouch(e.path),await i.loadFor(e,this.resolveCardAnchors(s,a.cards),o)}bindScrollSync(){this._scrollDispose&&(this._scrollDispose(),this._scrollDispose=null);let e=this.getActiveView();if(!e)return;let n=e.editor,i=n&&n.cm,a=i?.scrollDOM?i.scrollDOM:e.contentEl.querySelector(".cm-scroller");if(!a)return;let s=at(()=>this.handleEditorScroll(e));a.addEventListener("scroll",s,{passive:!0}),this._scrollDispose=()=>{s.cancel(),a.removeEventListener("scroll",s)}}handleEditorScroll(e){let n=this.getParallelView();if(!n||!e.file||n.sourceFile?.path!==e.file.path)return;let i=e.editor,a=i&&i.cm;if(!a?.scrollDOM)return;let s=a.scrollDOM.getBoundingClientRect(),o=it(s),c=0;try{let l=a.posAtCoords({x:s.left+20,y:o});l!=null&&(c=a.state.doc.lineAt(l).number-1)}catch{return}let u=-1;for(let l=0;l; const delta = extractDelta(json); diff --git a/tests/modules.test.js b/tests/modules.test.js index dad6e94..b410f33 100644 --- a/tests/modules.test.js +++ b/tests/modules.test.js @@ -594,7 +594,7 @@ assert.strictEqual(t.deltaExtractorForFormat('google-generative-ai'), null, 'no // parseSseBuffer const sseResult = t.parseSseBuffer( - 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: {"choices":[{"delta":{"content":" there"}}]}\ndata: [DONE]\npartial', + 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: {"choices":[{"delta":{"content":" there"}}]}\n\ndata: [DONE]\n\npartial', openaiExtract, ); assert.deepStrictEqual(sseResult.deltas, ['hi', ' there'], 'SSE parser extracts deltas'); @@ -618,21 +618,34 @@ assert.ok(ssePartial.rest.includes('"ok"'), 'partial line kept in rest'); // parseSseBuffer: multi-event in one chunk const sseMulti = t.parseSseBuffer( - 'data: {"choices":[{"delta":{"content":"a"}}]}\ndata: {"choices":[{"delta":{"content":"b"}}]}\ndata: {"choices":[{"delta":{"content":"c"}}]}\n', + 'data: {"choices":[{"delta":{"content":"a"}}]}\n\ndata: {"choices":[{"delta":{"content":"b"}}]}\n\ndata: {"choices":[{"delta":{"content":"c"}}]}\n\n', openaiExtract, ); assert.deepStrictEqual(sseMulti.deltas, ['a', 'b', 'c'], 'three events in one chunk'); assert.strictEqual(sseMulti.rest, '', 'nothing left in rest when chunk ends with newline'); +const sseMultilineData = t.parseSseBuffer( + 'data: {"choices":[\ndata: {"delta":{"content":"joined"}}\ndata: ]}\n\n', + openaiExtract, +); +assert.deepStrictEqual(sseMultilineData.deltas, ['joined'], 'consecutive data lines are merged into one event'); + +const ssePartialEvent = t.parseSseBuffer( + 'data: {"choices":[{"delta":{"content":"wait"}}]}\n', + openaiExtract, +); +assert.deepStrictEqual(ssePartialEvent.deltas, [], 'event without blank-line terminator is retained'); +assert.strictEqual(ssePartialEvent.rest.includes('"wait"'), true, 'partial event remains in rest'); + // parseSseBuffer: non-data lines are skipped const sseMixed = t.parseSseBuffer( - ': comment\nevent: ping\ndata: {"choices":[{"delta":{"content":"x"}}]}\n', + ': comment\nevent: ping\ndata: {"choices":[{"delta":{"content":"x"}}]}\n\n', openaiExtract, ); assert.deepStrictEqual(sseMixed.deltas, ['x'], 'comment and event lines ignored'); // parseSseBuffer: malformed JSON is silently skipped -const sseBad = t.parseSseBuffer('data: not_json\ndata: {"choices":[{"delta":{"content":"y"}}]}\n', openaiExtract); +const sseBad = t.parseSseBuffer('data: not_json\n\ndata: {"choices":[{"delta":{"content":"y"}}]}\n\n', openaiExtract); assert.deepStrictEqual(sseBad.deltas, ['y'], 'bad JSON line skipped, good line extracted'); // i18n: additional edge cases