diff --git a/main.js b/main.js index 681cdbd..e543af7 100644 --- a/main.js +++ b/main.js @@ -1,24 +1,24 @@ 'use strict'; -"use strict";var Rt=Object.create;var ae=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var Nt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Dt=Object.prototype.hasOwnProperty;var Lt=(r,t)=>{for(var e in t)ae(r,e,{get:t[e],enumerable:!0})},lt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Nt(t))!Dt.call(r,i)&&i!==e&&ae(r,i,{get:()=>t[i],enumerable:!(n=Mt(t,i))||n.enumerable});return r};var se=(r,t,e)=>(e=r!=null?Rt(It(r)):{},lt(t||!r||!r.__esModule?ae(e,"default",{value:r,enumerable:!0}):e,r)),Ot=r=>lt(ae({},"__esModule",{value:!0}),r);var hr={};Lt(hr,{__test:()=>pr,default:()=>dr});module.exports=Ot(hr);var d=require("obsidian");function J(r,t){if(!t)return-1;let e=h=>h.replace(/\s+/g," ").trim(),n=h=>{let g=[],p=[],f=!1;for(let b=0;b0;continue}f&&(g.push(" "),p.push(b),f=!1),g.push(ie),p.push(b)}return{text:g.join(""),map:p}},i=h=>{if(!h)return-1;let g=r.indexOf(h);if(g===-1)return-1;let p=0;for(let f=0;f=0||(a=i(t.trim()),a>=0))return a;for(let h of[60,40,25,15]){let g=t.trim().slice(0,h);if(a=i(g),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)oe(r,e,{get:t[e],enumerable:!0})},mt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Bt(t))!Vt.call(r,i)&&i!==e&&oe(r,i,{get:()=>t[i],enumerable:!(n=Lt(t,i))||n.enumerable});return r};var ce=(r,t,e)=>(e=r!=null?Ot(_t(r)):{},mt(t||!r||!r.__esModule?oe(e,"default",{value:r,enumerable:!0}):e,r)),Gt=r=>mt(oe({},"__esModule",{value:!0}),r);var fr={};Ut(fr,{__test:()=>gr,default:()=>mr});module.exports=Gt(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(se),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 --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 Bt(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=Bt(r),i=oe[n]||oe.en,a=oe.en[t]||oe.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,_t=2,V=2,U=100,Vt=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},S={"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 S[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||S[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||S[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 ce(r){Ne[r.uiLanguage]||(r.uiLanguage=y.uiLanguage),(!r.apiProvider||!R[r.apiProvider])&&(r.apiProvider="anthropic");let t=x(r);(!r.apiFormat||!S[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=ce(Object.assign({},y,r||{})),e=De(t.backend),n=x(t),i=P(t),a=e?(t.apiBaseUrl||n.baseUrl||S[i]?.defaultBaseUrl||"").trim().replace(/\/+$/,""):"";return _(Re({cacheSchemaVersion:V,promptVersion:_t,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 ue(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=ue(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 Ut(r,t){return t?r.parent?.path===t:!r.path.includes("/")}function Ve(r,t){let e=ue(t);return r.filter(n=>Ut(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 de(r){return!r||r.cancelled?!1:(r.cancelled=!0,!0)}function pe(r,t){return r?{...r,lastAccessedAt:t||new Date().toISOString()}:null}function he(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(),he(this.cache))}async load(){this.cache=await this.readFile(),this.prune().length>0&&await this.writeFile()}prune(){let t=this.getSettings();return le(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=pe(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 me(r,t){let e=Array.isArray(r)?r.slice():[];return!Number.isInteger(t)||t<0||t>=e.length||e.splice(t,1),e}function ge(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=se(require("fs")),be=se(require("os")),v=se(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}},T=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 T(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 T)?new T(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 T)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 ye="record_parallel_reader_cards";function jt(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=jt(t);n.sort((i,a)=>a.length-i.length);for(let i of n)try{return JSON.parse(i),i}catch{}return t}function k(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 Y(n)}function Y(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 X(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:X(!0)}}}function ft(){return{format:{type:"json_schema",name:"parallel_reader_cards",strict:!0,schema:X(!0)}}}function yt(){return{name:ye,description:"Return the generated Parallel Reader summary cards.",input_schema:X(!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))},g=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="",f="";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 T(i.key))}),!c.stdout||!c.stderr||!c.stdin){h(new Error("CLI process streams are unavailable"));return}let b=c.stdout,ie=c.stderr,Fe=c.stdin;if(b.on("data",C=>{p+=C.toString("utf8")}),ie.on("data",C=>{f+=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 jt(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=jt(r),i=le[n]||le.en,a=le.en[t]||le.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 Be=1e5,Ht=2,V=2,U=100,Jt=1e3,$={zh:"\u4E2D\u6587",en:"English",auto:"Auto-detect"},_e={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:Be,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"}},Ve={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 yt.default.createHash("sha1").update(r,"utf8").digest("hex")}function Le(r){return Array.isArray(r)?"["+r.map(Le).join(",")+"]":r&&typeof r=="object"?"{"+Object.keys(r).sort().map(t=>JSON.stringify(t)+":"+Le(r[t])).join(",")+"}":JSON.stringify(r)}function Ue(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 E(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 Ge(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 bt(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 je(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 ue(r){_e[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||!Ve[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=wt(r.maxCacheEntries),$[r.promptLanguage]||(r.promptLanguage=y.promptLanguage),r.minCards=gt(r.minCards,y.minCards),r.maxCards=gt(r.maxCards,y.maxCards),r.maxCardsft(s)-ft(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=ue(Object.assign({},y,r||{})),e=Ue(t.backend),n=x(t),i=P(t),a=e?(t.apiBaseUrl||n.baseUrl||T[i]?.defaultBaseUrl||"").trim().replace(/\/+$/,""):"";return _(Le({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?Ge(t):"",apiHeadersHash:e?_(t.apiHeaders||""):"",apiMaxTokens:e?Number(t.apiMaxTokens)||y.apiMaxTokens:0,structuredOutputVersion:1}))}function G(r,t,e){return!!r&&r.schemaVersion===V&&r.contentHash===_(t)&&r.settingsHash===q(e)}function pe(r){return(r||"").trim().split("/").map(t=>t.trim()).filter(t=>t&&t!=="."&&t!=="..").join("/")}function He(r){return(r||"").split("/").map(t=>t.trim()).some(t=>t==="."||t==="..")}function Je(r,t){let e=pe(r);return He(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 $e(r,t){let e=pe(t);return r.filter(n=>$t(n,e))}function Ke(r,t){return{current:r+1,total:t}}function qe(r){return{total:r,processed:0,skipped:0}}function ze(r){return{...r,processed:r.processed+1}}function We(r){return{...r,processed:r.processed+1,skipped:r.skipped+1}}function Ye(r,t,e){return!!r&&G(r,t,e)}function Xe(){return{cancelled:!1,currentPath:""}}function Ze(r,t){return r.currentPath=t,r}function he(r){return!r||r.cancelled?!1:(r.cancelled=!0,!0)}function me(r,t){return r?{...r,lastAccessedAt:t||new Date().toISOString()}:null}function ge(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(),ge(this.cache))}async load(){this.cache=await this.readFile(),this.prune().length>0&&await this.writeFile()}prune(){let t=this.getSettings();return de(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=me(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 fe(r,t){let e=Array.isArray(r)?r.slice():[];return!Number.isInteger(t)||t<0||t>=e.length||e.splice(t,1),e}function ye(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 At=require("child_process"),Pt=ce(require("fs")),we=ce(require("os")),v=ce(require("path"));var j=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}},et=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 j(t);let n=new et(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 tt(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 rt(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=rt(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 Ct(){return{type:"json_schema",json_schema:{name:"parallel_reader_cards",strict:!0,schema:Z(!0)}}}function vt(){return{format:{type:"json_schema",name:"parallel_reader_cards",strict:!0,schema:Z(!0)}}}function xt(){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=we.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(Pt.default.existsSync(c))return c}catch{}}return r}function O(r,t,e,n,i,a=At.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(we.default.homedir(),".local/bin"),v.default.join(we.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,se=c.stderr,Oe=c.stdin;if(b.on("data",C=>{p+=C.toString("utf8")}),se.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} stderr: -${f.slice(0,1e3)}`));g({stdout:p,stderr:f})}}),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:p,stderr:g})}}),e)try{Oe.write(e),Oe.end()}catch{}else try{Oe.end()}catch{}})}async function St(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 O(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: `+s.slice(0,500))}if(!o)throw new Error(`claude CLI returned no result. Output: -`+s.slice(0,500));return k(o,e)}async function vt(r,t,e,n){let i=D("codex",e.cliPath),a=`<> +`+s.slice(0,500));return S(o,e)}async function Tt(r,t,e,n){let i=D("codex",e.cliPath),a=`<> ${r} <> ${t} -Output JSON directly with no explanation.`,s=["exec","--skip-git-repo-check","-"],{stdout:o}=await L(i,s,a,e.cliTimeoutMs,n);return k(o,e)}var Tt=require("obsidian");function Gt(r){return r==="en"?"Write title, gist, and bullets in English.":r==="auto"?"Write title, gist, and bullets in the main language of the source document.":"\u7528\u4E2D\u6587\u8F93\u51FA title\u3001gist \u548C bullets\u3002"}function Ht(r){return r==="en"?`{"cards":[ +Output JSON directly with no explanation.`,s=["exec","--skip-git-repo-check","-"],{stdout:o}=await O(i,s,a,e.cliTimeoutMs,n);return S(o,e)}var Mt=require("obsidian");function qt(r){return r==="en"?"Write title, gist, and bullets in English.":r==="auto"?"Write title, gist, and bullets in the main language of the source document.":"\u7528\u4E2D\u6587\u8F93\u51FA title\u3001gist \u548C bullets\u3002"}function zt(r){return r==="en"?`{"cards":[ {"title":"U-shaped gains","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"AI productivity gains form a U shape, with both ends benefiting most","bullets":["Top-paid software managers benefit by accelerating existing work","Low-paid workers use AI to create new side income","Middle-layer specialists gain less because prompt precision is hard to trust","Average reported benefit is 5.1/7, with 42% describing gains as unclear"]} ]}`:`{"cards":[ {"title":"U \u578B\u6536\u76CA\u66F2\u7EBF","anchor":"\u90A3\u8C01\u53C8\u4F1A\u88AB AI \u6240\u53D7\u76CA\uFF1F\u6574\u4F53\u6765\u770B\uFF0C\u5B83\u628A\u6574\u4E2A\u5206\u6570\u53D8\u6210\u4E86\u4E00\u5206\u5230\u4E03\u5206","gist":"AI \u751F\u4EA7\u529B\u6536\u76CA\u5448 U \u578B\uFF0C\u4E24\u7AEF\u53D7\u76CA\u6700\u5927\u3001\u4E2D\u95F4\u5C42\u584C\u9677","bullets":["\u6700\u9AD8\u85AA\u5C97\u4F4D\uFF08\u8F6F\u4EF6\u7BA1\u7406\uFF09\u901A\u8FC7\u52A0\u901F\u65E2\u6709\u5DE5\u4F5C\u53D7\u76CA\u6700\u5927","\u6700\u4F4E\u85AA\u5C97\u4F4D\uFF08\u5916\u5356\u5458\u3001\u56ED\u827A\u5DE5\uFF09\u7528 AI \u5F00\u526F\u4E1A\u521B\u9020\u65B0\u6536\u5165","\u4E2D\u95F4\u5C42\u79D1\u5B66\u5BB6\u3001\u5F8B\u5E08\u6536\u76CA\u6700\u5C11\uFF0C\u90E8\u5206\u56E0\u5BF9 prompt \u7CBE\u5EA6\u4FE1\u4EFB\u4E0D\u8DB3","\u5168\u4F53\u5747\u5206 5.1/7\uFF0C42% \u62A5\u544A\u6536\u76CA\u6A21\u7CCA"]} -]}`}function Jt(r,t){return String(r||"").replace(/\{([a-zA-Z0-9_]+)\}/g,(e,n)=>Object.hasOwn(t,n)?String(t[n]):e)}function $t(r,t,e,n,i,a){return r==="en"?`You are a long-form reading summary assistant. After reading the full document, split it into ${t}-${e} natural topic units. They do not need to match markdown headings; use a complete argument or topic as the unit, merging short sections and splitting long ones when needed. +]}`}function Wt(r,t){return String(r||"").replace(/\{([a-zA-Z0-9_]+)\}/g,(e,n)=>Object.hasOwn(t,n)?String(t[n]):e)}function Yt(r,t,e,n,i,a){return r==="en"?`You are a long-form reading summary assistant. After reading the full document, split it into ${t}-${e} natural topic units. They do not need to match markdown headings; use a complete argument or topic as the unit, merging short sections and splitting long ones when needed. Each card has one guiding sentence plus several bullets. Bullets carry details; gist is the lead-in. @@ -68,7 +68,7 @@ ${a}`:`\u4F60\u662F\u4E00\u4E2A\u957F\u6587\u9605\u8BFB\u6458\u8981\u52A9\u624B\ ${i} \u793A\u4F8B\uFF1A -${a}`}function Kt(r,t,e,n,i){return r==="en"?`Non-overridable output contract: +${a}`}function Xt(r,t,e,n,i){return r==="en"?`Non-overridable output contract: - Must output ${t}-${e} cards. - ${n} - anchor must be copied verbatim from the source and exact-substring-match the source. @@ -78,26 +78,26 @@ ${a}`}function Kt(r,t,e,n,i){return r==="en"?`Non-overridable output contract: - ${n} - anchor \u5FC5\u987B\u4ECE\u539F\u6587\u9010\u5B57\u590D\u5236\uFF0C\u5FC5\u987B\u80FD\u5728\u539F\u6587 exact substring match \u627E\u5230\u3002 - \u4E25\u683C\u53EA\u8F93\u51FA JSON\uFF0C\u65E0 markdown fence\u3001\u65E0\u89E3\u91CA\u3001\u65E0 tool call\u3002 -- JSON shape: ${i}`}function we(r,t){let e=Number(t.maxDocChars)||Me,n=$[t.promptLanguage]?t.promptLanguage:y.promptLanguage,i=Math.max(1,Number(t.minCards)||y.minCards),a=Math.max(i,Number(t.maxCards)||y.maxCards),s=Gt(n),o=r.length>e?r.slice(0,e)+(n==="en"?` +- JSON shape: ${i}`}function Ce(r,t){let e=Number(t.maxDocChars)||Be,n=$[t.promptLanguage]?t.promptLanguage:y.promptLanguage,i=Math.max(1,Number(t.minCards)||y.minCards),a=Math.max(i,Number(t.maxCards)||y.maxCards),s=qt(n),o=r.length>e?r.slice(0,e)+(n==="en"?` [Document truncated]`:` -[\u6587\u6863\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]`):r,c='{"cards":[{"title":"...","anchor":"...","gist":"...","bullets":["...","..."]}]}',l=Ht(n),u={minCards:i,maxCards:a,languageInstruction:s,schema:c,example:l},h=Jt(t.customSystemPrompt,u).trim(),g=Kt(n,i,a,s,c),p=$t(n,i,a,s,c,l),f=h?`${h} +[\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} -${g}`:p,b=n==="en"?`Source document: +${f}`:p,b=n==="en"?`Source document: ${o}`:`\u4EE5\u4E0B\u662F\u9700\u8981\u5904\u7406\u7684\u6587\u6863\u5168\u6587\uFF1A -${o}`;return{system:f,user:b}}function qt(r){return r.choices?.[0]?.delta?.content||""}function zt(r){return r.type==="content_block_delta"&&r.delta?.text||""}function Z(r){switch(r){case"openai-chat":return qt;case"anthropic-messages":return zt;default:return null}}function Xe(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 Wt(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 g=await o.text();throw new Error(w(s||null,"errorProviderApiStatus",{label:"Streaming",status:o.status,excerpt:g.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:g,value:p}=await c.read();if(g)break;h+=l.decode(p,{stream:!0});let f=Xe(h,n);h=f.rest;for(let b of f.deltas)u+=b;f.deltas.length>0&&i?.({accumulated:u,done:!1})}}finally{c.releaseLock()}return i?.({accumulated:u,done:!0}),u}async function Ze(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,g)=>{l=setTimeout(()=>{c.abort(),g(new Error(`Streaming timed out after ${o}ms`))},o)});try{return await Promise.race([Wt(r,t,e,n,i,c.signal,s),u])}finally{l!==null&&clearTimeout(l)}}function At(r){let t=Z(r);if(!t)throw new Error(`Streaming not supported for format: ${r}`);return t}function te(r,t){let e=r.replace(/\/+$/,"");for(let n of t)if(e.endsWith(n))return e;return e+t[0]}function Yt(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 Xt(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",...Xt(r),...t||{},...Yt(r.apiHeaders,r)}}function Zt(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 xt(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 Zt(s,t,a)}function Qt(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 xt(r,t,e,n,i,s)}catch(o){if(!a||!Qt(o))throw o;return console.warn(`[parallel-reader] ${t} structured output rejected; retrying without structured output`,o),xt(r,t+" fallback",e,n,a,s)}}function Qe(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 er(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 et(r){let t=x(r),e=S[P(r)];return t.tokenLimitField||e?.tokenLimitField||"max_tokens"}function Q(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:ye}),a}function ee(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=X(!1)),{systemInstruction:{parts:[{text:r}]},contents:[{role:"user",parts:[{text:t}]}],generationConfig:a}}function tr(r,t){let n=(Array.isArray(r?.content)?r.content:[]).find(i=>i&&i.type==="tool_use"&&i.name===ye);return n?typeof n.input=="string"?k(n.input,t):n.input&&typeof n.input=="object"?Y(n.input):[]:null}async function rr(r,t,e,n){let i=te(F(n),["/messages"]),a=await xe(r,"Anthropic-compatible",i,H(n,{"anthropic-version":"2023-06-01"}),Q(t,e,n),Q(t,e,n,{structured:!1}),n),s=tr(a,n);if(s)return s;let c=(Array.isArray(a.content)?a.content:[]).map(l=>Qe(l)).join("").trim();return k(c,n)}async function nr(r,t,e,n){let i=te(F(n),["/chat/completions"]),a=await xe(r,"OpenAI-compatible Chat",i,H(n),ee(t,e,n),ee(t,e,n,{structured:!1}),n),o=(Array.isArray(a.choices)?a.choices:[])[0]||{},c=o.message,l=Qe(c?.content??o.text??"").trim();return k(l,n)}async function ir(r,t,e,n){let i=te(F(n),["/responses"]),a=await xe(r,"OpenAI Responses",i,H(n),Ce(t,e,n),Ce(t,e,n,{structured:!1}),n);return k(er(a).trim(),n)}async function ar(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),u=((Array.isArray(o.candidates)?o.candidates:[])[0]||{}).content,g=(Array.isArray(u?.parts)?u.parts:[]).map(p=>Qe(p)).join("").trim();return k(g,n)}async function re(r,t,e,n){switch(P(n)){case"openai-chat":return nr(r,t,e,n);case"openai-responses":return ir(r,t,e,n);case"google-generative-ai":return ar(r,t,e,n);default:return rr(r,t,e,n)}}function Ae(r){if(!r.streaming)return!1;let t=P(r);return!!Z(t)}async function sr(r,t,e,n,i){let a=te(F(e),["/chat/completions"]),s=H(e),o=ee(r,t,e,{structured:!1});o.stream=!0;let c=At("openai-chat"),l=await Ze(a,s,o,c,n,i,e);return k(l.trim(),e)}async function or(r,t,e,n,i){let a=te(F(e),["/messages"]),s=H(e,{"anthropic-version":"2023-06-01"}),o=Q(r,t,e,{structured:!1});o.stream=!0;let c=At("anthropic-messages"),l=await Ze(a,s,o,c,n,i,e);return k(l.trim(),e)}async function Pt(r,t,e,n,i){let a=P(e);switch(a){case"openai-chat":return sr(r,t,e,n,i);case"anthropic-messages":return or(r,t,e,n,i);default:throw new Error(`Streaming not supported for format: ${a}`)}}async function St(r,t){await re(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} / ${S[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 Pt(i,a,t,n,l.signal)}else s=await re(Tt.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 Q(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 ve(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 xe(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 Ae(r){return(Array.isArray(r.content)?r.content:[]).map(e=>Q(e)).join("").trim()}function Pe(r){let e=(Array.isArray(r.choices)?r.choices:[])[0]||{},n=e.message;return Q(n?.content??e.text??"").trim()}function Se(r){let n=((Array.isArray(r.candidates)?r.candidates:[])[0]||{}).content;return(Array.isArray(n?.parts)?n.parts:[]).map(a=>Q(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 ee(r){switch(r){case"openai-chat":return Zt;case"anthropic-messages":return Qt;default:return null}}function nt(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=nt(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 it(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 Ft(r){let t=ee(r);if(!t)throw new Error(`Streaming not supported for format: ${r}`);return t}function ne(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=Ge(r);if(t==="none")return{};let e=bt(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 Fe(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 at(r){let t=x(r),e=T[P(r)];return t.tokenLimitField||e?.tokenLimitField||"max_tokens"}function te(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=[xt()],a.tool_choice={type:"tool",name:Y}),a}function re(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[at(e)]=Number(e.apiMaxTokens)||4096,i&&(a.response_format=Ct()),a}function Te(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=vt()),a}function ke(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=ne(E(n),["/messages"]),a=await Fe(r,"Anthropic-compatible",i,H(n,{"anthropic-version":"2023-06-01"}),te(t,e,n),te(t,e,n,{structured:!1}),n),s=xe(a,n);return s||S(Ae(a),n)}async function sr(r,t,e,n){let i=ne(E(n),["/chat/completions"]),a=await Fe(r,"OpenAI-compatible Chat",i,H(n),re(t,e,n),re(t,e,n,{structured:!1}),n);return S(Pe(a),n)}async function or(r,t,e,n){let i=ne(E(n),["/responses"]),a=await Fe(r,"OpenAI Responses",i,H(n),Te(t,e,n),Te(t,e,n,{structured:!1}),n);return S(ve(a).trim(),n)}async function cr(r,t,e,n){let i=encodeURIComponent(I(n)),a=E(n);/:generateContent(?:\?|$)/.test(a)||(a=`${a.replace(/\/+$/,"")}/models/${i}:generateContent`);let s=H(n),o=await Fe(r,"Google Gemini",a,s,ke(t,e,n),ke(t,e,n,{structured:!1}),n);return S(Se(o),n)}async function ie(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 Ee(r){if(!r.streaming)return!1;let t=P(r);return!!ee(t)}async function lr(r,t,e,n,i){let a=ne(E(e),["/chat/completions"]),s=H(e),o=re(r,t,e,{structured:!1});o.stream=!0;let c=Ft("openai-chat"),l=await it(a,s,o,c,n,i,e);return S(l.trim(),e)}async function ur(r,t,e,n,i){let a=ne(E(e),["/messages"]),s=H(e,{"anthropic-version":"2023-06-01"}),o=te(r,t,e,{structured:!1});o.stream=!0;let c=Ft("anthropic-messages"),l=await it(a,s,o,c,n,i,e);return S(l.trim(),e)}async function Et(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 ie(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 st(r,t,e,n){let{system:i,user:a}=Ce(r,t),s;switch(t.backend){case"claude-code":s=await St(i,a,t,e);break;case"codex":s=await Tt(i,a,t,e);break;default:{if(Ee(t)){let l=new AbortController;e.onCancel(()=>l.abort()),s=await Et(i,a,t,n,l.signal)}else s=await ie(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 ot(r,t){return t?.phase==="generating"&&r&&Ue(r.backend)?"cancelRequestedApiInFlight":"cancelRequested"}function ct(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 kt(r){return[r.title,r.gist||"",...(r.bullets||[]).map(t=>"\u2022 "+t)].filter(Boolean).join(` -`)}function ne(r,t){let e=[`# ${r||"\u5BF9\u7167\u7B14\u8BB0"}`];for(let n of t||[])e.push(nt(n));return e.join(` +`)}function Nt(r){return[r.title,r.gist||"",...(r.bullets||[]).map(t=>"\u2022 "+t)].filter(Boolean).join(` +`)}function ae(r,t){let e=[`# ${r||"\u5BF9\u7167\u7B14\u8BB0"}`];for(let n of t||[])e.push(ct(n));return e.join(` -`)}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 cr(r){return typeof requestAnimationFrame=="function"?requestAnimationFrame(r):setTimeout(()=>r(Date.now()),16)}function lr(r){if(typeof cancelAnimationFrame=="function"){cancelAnimationFrame(r);return}clearTimeout(r)}function at(r,t=cr,e=lr){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 ur(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 St(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(S))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||S[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 ur(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 Et(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 Ft=require("obsidian");var ke=class extends Ft.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 g=a.querySelector("pre");g&&(g.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 g=c.bullets||[];if(g.length>0){let p=u.createEl("div",{cls:"parallel-reader-bullets-md"}),f=g.map(b=>`- ${b}`).join(` -`);A.MarkdownRenderer.render(this.app,f,p,o,this).catch(()=>{p.setText(f)})}else c.gist||u.createEl("div",{cls:"parallel-reader-empty-li",text:this.plugin.t("emptyCard")});u.addEventListener("click",p=>{let f=window.getSelection();if(f&&f.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 f=new A.Menu;f.addItem(b=>b.setTitle(this.plugin.t("menuCopyMarkdown")).setIcon("copy").onClick(()=>O(nt(c),this.plugin.t("copiedMarkdown")))),f.addItem(b=>b.setTitle(this.plugin.t("menuCopyPlain")).setIcon("clipboard-copy").onClick(()=>O(kt(c),this.plugin.t("copiedPlain")))),c.anchor&&f.addItem(b=>b.setTitle(this.plugin.t("menuCopyAnchor")).setIcon("quote-glyph").onClick(()=>O(c.anchor,this.plugin.t("copiedAnchor")))),f.addSeparator(),c.startLine>=0&&f.addItem(b=>b.setTitle(this.plugin.t("menuJumpSource")).setIcon("arrow-right").onClick(()=>this.plugin.scrollEditorToLine(c.startLine,this.sourceFile))),f.addSeparator(),f.addItem(b=>b.setTitle(this.plugin.t("menuEditCard")).setIcon("pencil").onClick(()=>this.openEditCardModal(l))),f.addItem(b=>b.setTitle(this.plugin.t("menuDeleteCard")).setIcon("trash").onClick(()=>this.deleteCard(l))),f.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=me(this.sections,e);if(n.length===this.sections.length)return!1;let i=this.sections.length;return this.sections=n,this.activeIdx=ge(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=fe(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","---","",ne(`${this.sourceFile.basename} \xB7 ${this.plugin.t("displayName")}`,this.sections),""].join(` -`),s=this.plugin.app;await Et(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=ce(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&&de(this.activeBatch),new d.Notice(a?this.t(i):this.t("noCancelableJob")),a}requestBatchCancellation(){return de(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(ne(`${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 g=u.filter(p=>p.startLine<0).length;new d.Notice(this.t("generationDone",{count:u.length,suffix:g?this.t("unanchoredSuffix",{count:g}):""}))}).catch(async a=>{if(a instanceof G){new d.Notice(a.message);return}if(a instanceof T){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",g=>{g.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;u=n?i<0?n-1:0:Math.min(n-1,Math.max(0,r+i))}function Me(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 lt(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 ut(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 O(t,["--version"],"",1e4);return`claude @ ${t} +${e.trim()}`}if(r.backend==="codex"){let t=D("codex",r.cliPath),{stdout:e}=await O(t,["--version"],"",1e4);return`codex @ ${t} +${e.trim()}`}return Rt(m.requestUrl,r)}var Ne=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(_e))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&&je(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=>{je(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(Ve))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 F=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 F.setIcon=="function"?(0,F.setIcon)(i,t):i.textContent=e,i.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Promise.resolve(n()).catch(s=>{console.error(s),new F.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 F.setIcon=="function"&&(0,F.setIcon)(a,t),a.createSpan({text:e}),a.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Promise.resolve(n()).catch(o=>{console.error(o),new F.Notice(`${e} failed: ${o instanceof Error?o.message:String(o)}`)})}),a}async function L(r,t){try{await navigator.clipboard.writeText(r),new F.Notice(t)}catch(e){new F.Notice(`Copy failed: ${e instanceof Error?e.message:String(e)}`)}}function dt(r){return String(r||"").split("/").map(t=>t.trim()).filter(t=>!!t&&t!==".."&&t!==".").join("/")}function pt(r){let t=dt(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 pt(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 Ie=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",De=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(()=>L(ct(c),this.plugin.t("copiedMarkdown")))),g.addItem(b=>b.setTitle(this.plugin.t("menuCopyPlain")).setIcon("clipboard-copy").onClick(()=>L(Nt(c),this.plugin.t("copiedPlain")))),c.anchor&&g.addItem(b=>b.setTitle(this.plugin.t("menuCopyAnchor")).setIcon("quote-glyph").onClick(()=>L(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=Re(this.activeIdx,this.sections.length,e);return this.setActiveSection(n),this.focusSummaryPane(),n}jumpToActiveSection(){let e=Me(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=fe(this.sections,e);if(n.length===this.sections.length)return!1;let i=this.sections.length;return this.sections=n,this.activeIdx=ye(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 Ie(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=be(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=dt(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","---","",ae(`${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 ht=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 De(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 Ne(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=ue(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=ot(this.settings,n),a=this.jobs.cancel(e.path);return a&&this.activeBatch?.currentPath===e.path&&he(this.activeBatch),new d.Notice(a?this.t(i):this.t("noCancelableJob")),a}requestBatchCancellation(){return he(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 L(ae(`${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&&G(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 st(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 j){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=tt(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=Je(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=$e(this.app.vault.getMarkdownFiles(),i.folderPath);if(a.length===0){new d.Notice(this.t("batchNoMarkdown"));return}let s=Xe();this.activeBatch=s;let o=qe(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=!G(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=ut(()=>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=lt(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;u { + if (typeof part === 'string') return part; + if (part && typeof part === 'object') { + const p = part as Record; + return typeof p.text === 'string' ? p.text : typeof p.output_text === 'string' ? p.output_text : ''; + } + return ''; + }) + .join(''); + } + if (content && typeof content === 'object') { + const c = content as Record; + return typeof c.text === 'string' ? c.text : typeof c.output_text === 'string' ? c.output_text : ''; + } + return ''; +} + +export function textFromOpenAiResponsesResponse(json: Record): string { + if (typeof json.output_text === 'string') return json.output_text; + const parts: string[] = []; + const walk = (value: unknown) => { + if (!value) return; + if (typeof value === 'string') return; + if (Array.isArray(value)) { + value.forEach(walk); + return; + } + if (typeof value === 'object') { + const v = value as Record; + if (typeof v.text === 'string') parts.push(v.text); + if (typeof v.output_text === 'string') parts.push(v.output_text); + if (v.type === 'output_text' && typeof v.content === 'string') parts.push(v.content); + if (v.content) walk(v.content); + if (v.output) walk(v.output); + } + }; + walk(json.output); + return parts.join(''); +} + +export function cardsFromAnthropicToolUse( + json: Record, + settings?: PluginSettings | null, +): RawCard[] | null { + const content = Array.isArray(json?.content) ? (json.content as Array>) : []; + const block = content.find((c) => c && c.type === 'tool_use' && c.name === ANTHROPIC_CARD_TOOL_NAME); + if (!block) return null; + if (typeof block.input === 'string') return parseCardsJson(block.input, settings); + if (block.input && typeof block.input === 'object') + return normalizeCardsPayload(block.input as Record); + return []; +} + +export function textFromAnthropicMessagesResponse(json: Record): string { + const contentBlocks = Array.isArray(json.content) ? (json.content as Array) : []; + return contentBlocks + .map((c) => textFromProviderContent(c)) + .join('') + .trim(); +} + +export function textFromOpenAiChatResponse(json: Record): string { + const choices = Array.isArray(json.choices) ? (json.choices as Array>) : []; + const choice = choices[0] || {}; + const message = choice.message as Record | undefined; + return textFromProviderContent(message?.content ?? choice.text ?? '').trim(); +} + +export function textFromGoogleGenerativeAiResponse(json: Record): string { + const candidates = Array.isArray(json.candidates) ? (json.candidates as Array>) : []; + const candidate = candidates[0] || {}; + const contentObj = candidate.content as Record | undefined; + const parts = Array.isArray(contentObj?.parts) ? (contentObj.parts as Array) : []; + return parts + .map((p) => textFromProviderContent(p)) + .join('') + .trim(); +} diff --git a/src/providers.ts b/src/providers.ts index 7cab47e..ee6fb2a 100644 --- a/src/providers.ts +++ b/src/providers.ts @@ -1,11 +1,17 @@ 'use strict'; import { translate } from './i18n'; +import { + cardsFromAnthropicToolUse, + textFromAnthropicMessagesResponse, + textFromGoogleGenerativeAiResponse, + textFromOpenAiChatResponse, + textFromOpenAiResponsesResponse, +} from './provider-parsers'; import { ANTHROPIC_CARD_TOOL_NAME, anthropicCardTool, cardOutputSchema, - normalizeCardsPayload, openAiJsonSchemaResponseFormat, openAiResponsesTextFormat, parseCardsJson, @@ -231,50 +237,6 @@ async function requestJsonBodyWithStructuredFallback( } } -function textFromContent(content: unknown): string { - if (typeof content === 'string') return content; - if (Array.isArray(content)) { - return content - .map((part) => { - if (typeof part === 'string') return part; - if (part && typeof part === 'object') { - const p = part as Record; - return typeof p.text === 'string' ? p.text : typeof p.output_text === 'string' ? p.output_text : ''; - } - return ''; - }) - .join(''); - } - if (content && typeof content === 'object') { - const c = content as Record; - return typeof c.text === 'string' ? c.text : typeof c.output_text === 'string' ? c.output_text : ''; - } - return ''; -} - -function textFromOpenAiResponses(json: Record): string { - if (typeof json.output_text === 'string') return json.output_text; - const parts: string[] = []; - const walk = (value: unknown) => { - if (!value) return; - if (typeof value === 'string') return; - if (Array.isArray(value)) { - value.forEach(walk); - return; - } - if (typeof value === 'object') { - const v = value as Record; - if (typeof v.text === 'string') parts.push(v.text); - if (typeof v.output_text === 'string') parts.push(v.output_text); - if (v.type === 'output_text' && typeof v.content === 'string') parts.push(v.content); - if (v.content) walk(v.content); - if (v.output) walk(v.output); - } - }; - walk(json.output); - return parts.join(''); -} - export function tokenLimitFieldForOpenAiChat(settings: PluginSettings): string { const preset = getApiPreset(settings); const format = API_FORMATS[getApiFormat(settings)]; @@ -363,16 +325,6 @@ export function buildGeminiBody( }; } -function cardsFromAnthropicToolUse(json: Record, settings?: PluginSettings | null) { - const content = Array.isArray(json?.content) ? (json.content as Array>) : []; - const block = content.find((c) => c && c.type === 'tool_use' && c.name === ANTHROPIC_CARD_TOOL_NAME); - if (!block) return null; - if (typeof block.input === 'string') return parseCardsJson(block.input, settings); - if (block.input && typeof block.input === 'object') - return normalizeCardsPayload(block.input as Record); - return []; -} - async function summarizeViaAnthropicMessages( requestUrlImpl: RequestUrlFunction, system: string, @@ -393,12 +345,7 @@ async function summarizeViaAnthropicMessages( const toolCards = cardsFromAnthropicToolUse(json, settings); if (toolCards) return toolCards; - const contentBlocks = Array.isArray(json.content) ? (json.content as Array) : []; - const text = contentBlocks - .map((c) => textFromContent(c)) - .join('') - .trim(); - return parseCardsJson(text, settings); + return parseCardsJson(textFromAnthropicMessagesResponse(json), settings); } async function summarizeViaOpenAiChat( @@ -417,11 +364,7 @@ async function summarizeViaOpenAiChat( buildOpenAiChatBody(system, user, settings, { structured: false }), settings, ); - const choices = Array.isArray(json.choices) ? (json.choices as Array>) : []; - const choice = choices[0] || {}; - const message = choice.message as Record | undefined; - const text = textFromContent(message?.content ?? choice.text ?? '').trim(); - return parseCardsJson(text, settings); + return parseCardsJson(textFromOpenAiChatResponse(json), settings); } async function summarizeViaOpenAiResponses( @@ -440,7 +383,7 @@ async function summarizeViaOpenAiResponses( buildOpenAiResponsesBody(system, user, settings, { structured: false }), settings, ); - return parseCardsJson(textFromOpenAiResponses(json).trim(), settings); + return parseCardsJson(textFromOpenAiResponsesResponse(json).trim(), settings); } async function summarizeViaGoogleGenerativeAi( @@ -464,15 +407,7 @@ async function summarizeViaGoogleGenerativeAi( buildGeminiBody(system, user, settings, { structured: false }), settings, ); - const candidates = Array.isArray(json.candidates) ? (json.candidates as Array>) : []; - const candidate = candidates[0] || {}; - const contentObj = candidate.content as Record | undefined; - const parts = Array.isArray(contentObj?.parts) ? (contentObj.parts as Array) : []; - const text = parts - .map((p) => textFromContent(p)) - .join('') - .trim(); - return parseCardsJson(text, settings); + return parseCardsJson(textFromGoogleGenerativeAiResponse(json), settings); } // Obsidian's requestUrl is not directly compatible with fetch — we accept it as a typed callback diff --git a/tests/main.test.js b/tests/main.test.js index 6bc3f42..5db8b9b 100644 --- a/tests/main.test.js +++ b/tests/main.test.js @@ -70,6 +70,11 @@ assert.strictEqual(typeof t.resolveCliPath, 'function'); assert.strictEqual(typeof t.runCli, 'function'); assert.strictEqual(typeof t.buildPrompts, 'function'); assert.strictEqual(typeof t.buildOpenAiChatBody, 'function'); +assert.strictEqual(typeof t.textFromOpenAiChatResponse, 'function'); +assert.strictEqual(typeof t.textFromAnthropicMessagesResponse, 'function'); +assert.strictEqual(typeof t.textFromOpenAiResponsesResponse, 'function'); +assert.strictEqual(typeof t.textFromGoogleGenerativeAiResponse, 'function'); +assert.strictEqual(typeof t.cardsFromAnthropicToolUse, 'function'); assert.strictEqual(typeof t.extractJson, 'function'); assert.strictEqual(typeof t.findLineForAnchor, 'function'); assert.strictEqual(typeof t.folderPathsForTarget, 'function'); diff --git a/tests/modules.test.js b/tests/modules.test.js index dad6e94..8b5d0c1 100644 --- a/tests/modules.test.js +++ b/tests/modules.test.js @@ -523,6 +523,35 @@ assert.strictEqual(gemBody.systemInstruction.parts[0].text, 'sys'); assert.strictEqual(gemBody.contents[0].parts[0].text, 'usr'); assert.strictEqual(gemBody.generationConfig.responseMimeType, 'application/json'); +const providerCardsJson = JSON.stringify({ cards: [{ title: 'T', anchor: 'A', gist: 'G', bullets: ['B'] }] }); +assert.strictEqual( + t.textFromOpenAiChatResponse({ choices: [{ message: { content: [{ text: providerCardsJson }] } }] }), + providerCardsJson, + 'OpenAI Chat parser extracts message content text', +); +assert.strictEqual( + t.textFromAnthropicMessagesResponse({ content: [{ type: 'text', text: providerCardsJson }] }), + providerCardsJson, + 'Anthropic parser extracts text blocks', +); +assert.strictEqual( + t.textFromOpenAiResponsesResponse({ output: [{ content: [{ type: 'output_text', text: providerCardsJson }] }] }), + providerCardsJson, + 'OpenAI Responses parser extracts nested output text', +); +assert.strictEqual( + t.textFromGoogleGenerativeAiResponse({ candidates: [{ content: { parts: [{ text: providerCardsJson }] } }] }), + providerCardsJson, + 'Gemini parser extracts candidate part text', +); +assert.deepStrictEqual( + t.cardsFromAnthropicToolUse({ + content: [{ type: 'tool_use', name: 'record_parallel_reader_cards', input: JSON.parse(providerCardsJson) }], + }), + [{ title: 'T', anchor: 'A', gist: 'G', bullets: ['B'] }], + 'Anthropic tool-use parser extracts structured card payloads', +); + // tokenLimitFieldForOpenAiChat assert.strictEqual( t.tokenLimitFieldForOpenAiChat({ ...baseSettings, apiProvider: 'openai' }),