diff --git a/main.js b/main.js index 5d79a32..ec80313 100644 --- a/main.js +++ b/main.js @@ -1,34 +1,34 @@ 'use strict'; -"use strict";var st=Object.create;var q=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var dt=(r,e)=>{for(var t in e)q(r,t,{get:e[t],enumerable:!0})},He=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of lt(e))!ut.call(r,a)&&a!==t&&q(r,a,{get:()=>e[a],enumerable:!(n=ot(e,a))||n.enumerable});return r};var W=(r,e,t)=>(t=r!=null?st(ct(r)):{},He(e||!r||!r.__esModule?q(t,"default",{value:r,enumerable:!0}):t,r)),pt=r=>He(q({},"__esModule",{value:!0}),r);var _t={};dt(_t,{__test:()=>Ot,default:()=>Lt});module.exports=pt(_t);var u=require("obsidian");function Y(r,e){if(!e)return-1;let t=y=>y.replace(/\s+/g," ").trim(),n=y=>{let f=[],h=[],c=!1;for(let N=0;N0;continue}c&&(f.push(" "),h.push(N),c=!1),f.push(Ue),h.push(N)}return{text:f.join(""),map:h}},a=y=>{if(!y)return-1;let f=r.indexOf(y);if(f===-1)return-1;let h=0;for(let c=0;c=0||(i=a(e.trim()),i>=0))return i;for(let y of[60,40,25,15]){let f=e.trim().slice(0,y);if(i=a(f),i>=0)return i}let o=n(r),s=t(e).slice(0,30);if(!s)return-1;let l=o.text.indexOf(s);if(l===-1)return-1;let d=o.map[l];if(d==null)return-1;let g=0;for(let y=0;y0}function X(r,e){let t=Array.isArray(r)?r.slice():[];return!Number.isInteger(e)||e<0||e>=t.length||t.splice(e,1),t}function Z(r,e,t){if(!Number.isInteger(r)||!Number.isInteger(e)||e<=0||!Number.isInteger(t)||t<0||r<0||r>=e)return t;let n=e-1;return n<=0?-1:r=n.length||(n[e]=Object.assign({},n[e],t||{})),n}var Ke=require("child_process"),$e=W(require("fs")),re=W(require("os")),x=W(require("path"));var O=class extends Error{constructor(e){super("\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0"),this.name="GenerationJobAlreadyRunningError",this.code="already-running",this.key=e}},v=class extends Error{constructor(e){super("\u751F\u6210\u5DF2\u53D6\u6D88"),this.name="GenerationJobCancelledError",this.code="cancelled",this.key=e}},be=class{constructor(e){this.key=e,this.phase="queued",this.cancelled=!1,this.startedAt=new Date().toISOString(),this.updatedAt=this.startedAt,this._cancelHandlers=[]}setPhase(e){this.phase=e,this.updatedAt=new Date().toISOString()}onCancel(e){if(typeof e=="function"){if(this.cancelled){e();return}this._cancelHandlers.push(e)}}cancel(){if(this.cancelled)return!1;this.cancelled=!0,this.setPhase("cancelled");for(let e of this._cancelHandlers.splice(0))try{e()}catch{}return!0}throwIfCancelled(){if(this.cancelled)throw new v(this.key)}},U=class{constructor(){this.jobs=new Map}get(e){return this.jobs.get(e)||null}isRunning(e){return this.jobs.has(e)}async start(e,t){if(this.jobs.has(e))throw new O(e);let n=new be(e);this.jobs.set(e,n);try{n.setPhase("running");let a=await t(n);return n.throwIfCancelled(),a}catch(a){throw n.cancelled&&!(a instanceof v)?new v(e):a}finally{this.jobs.delete(e)}}cancel(e){let t=this.jobs.get(e);return t?t.cancel():!1}};function we(r){if(r instanceof v)return"cancelled";let e=r;if(e?.code==="cancelled")return"cancelled";let t=String(e?.message||r);return/api key|unauthorized|401|403|认证|权限/i.test(t)?"auth":/timeout|超时|timed out/i.test(t)?"timeout":/429|rate limit|too many requests/i.test(t)?"rate-limit":/非 JSON|json_schema|schema|structured/i.test(t)?"schema":/model 未设置|base url|配置|config/i.test(t)?"config":"unknown"}var ee={zh:{appTitle:"\u5BF9\u7167\u9605\u8BFB\u7B14\u8BB0",settingsTitle:"Parallel Reader \u8BBE\u7F6E",emptyOpenNote:"\u6253\u5F00\u4E00\u7BC7\u7B14\u8BB0\uFF0C\u7136\u540E\u8FD0\u884C\u547D\u4EE4\uFF1A",emptyNoCache:"\u8BE5\u7B14\u8BB0\u5C1A\u65E0\u5BF9\u7167\u7B14\u8BB0\u7F13\u5B58\u3002\u8FD0\u884C\u547D\u4EE4\uFF1A",commandGenerate:"Parallel Reader: \u4E3A\u5F53\u524D\u7B14\u8BB0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",displayName:"\u5BF9\u7167\u9605\u8BFB\u7B14\u8BB0",ribbonOpen:"\u6253\u5F00\u5BF9\u7167\u7B14\u8BB0\u9762\u677F",cmdRun:"\u4E3A\u5F53\u524D\u7B14\u8BB0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0\uFF08\u7F13\u5B58\u4F18\u5148\uFF09",cmdRegen:"\u5F3A\u5236\u91CD\u65B0\u751F\u6210\uFF08\u7ED5\u8FC7\u7F13\u5B58\uFF09",cmdOpenView:"\u6253\u5F00\u5BF9\u7167\u7B14\u8BB0\u9762\u677F",cmdExport:"\u5BFC\u51FA\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0\u5230 Vault",cmdCopyMarkdown:"\u590D\u5236\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0 Markdown",cmdCancel:"\u53D6\u6D88\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0\u751F\u6210",cmdClearCurrent:"\u6E05\u9664\u5F53\u524D\u7B14\u8BB0\u7684\u7F13\u5B58",cmdClearAll:"\u6E05\u9664\u6240\u6709\u7F13\u5B58",cmdCardPrev:"\u805A\u7126\u4E0A\u4E00\u5F20\u6458\u8981\u5361\u7247",cmdCardNext:"\u805A\u7126\u4E0B\u4E00\u5F20\u6458\u8981\u5361\u7247",cmdCardJump:"\u8DF3\u8F6C\u5230\u5F53\u524D\u6458\u8981\u5361\u7247\u539F\u6587",actionCancel:"\u53D6\u6D88\u751F\u6210",actionRegenerate:"\u91CD\u65B0\u751F\u6210",actionCopyAll:"\u590D\u5236\u5168\u90E8 Markdown",actionExport:"\u5BFC\u51FA\u5230 Vault",staleBanner:"\u6E90\u7B14\u8BB0\u6216\u751F\u6210\u914D\u7F6E\u5DF2\u4FEE\u6539\uFF0C\u5F53\u524D\u662F\u65E7\u7F13\u5B58\u3002",loadingDefault:"\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0...",loadingGenerating:"\u5BF9\u7167\u9605\u8BFB\uFF1A\u8BA9 LLM \u8BFB\u5168\u6587\u5E76\u81EA\u9002\u5E94\u5207\u6BB5...",loadingSubtitle:"\u53EF\u4EE5\u7EE7\u7EED\u9605\u8BFB\u539F\u6587\uFF0C\u751F\u6210\u5B8C\u6210\u540E\u4F1A\u81EA\u52A8\u5237\u65B0\u53F3\u4FA7\u5361\u7247\u3002",errorTitle:"\u751F\u6210\u5931\u8D25",emptyCard:"\uFF08\u672A\u751F\u6210\uFF09",anchorMismatch:"anchor \u5339\u914D\u5931\u8D25\uFF0C\u65E0\u6CD5\u6EDA\u52A8\u8054\u52A8",menuCopyMarkdown:"\u590D\u5236 Markdown",menuCopyPlain:"\u590D\u5236\u7EAF\u6587\u672C",menuCopyAnchor:"\u590D\u5236 anchor \u5F15\u7528",menuJumpSource:"\u8DF3\u8F6C\u5230\u539F\u6587",menuEditCard:"\u7F16\u8F91\u6B64\u5361\u7247",menuDeleteCard:"\u5220\u9664\u6B64\u5361\u7247",copiedMarkdown:"\u5DF2\u590D\u5236 Markdown",copiedPlain:"\u5DF2\u590D\u5236\u7EAF\u6587\u672C",copiedAnchor:"\u5DF2\u590D\u5236\u5F15\u7528\u539F\u6587",copiedAllMarkdown:"\u5DF2\u590D\u5236\u5168\u90E8 Markdown",copyFailed:"\u590D\u5236\u5931\u8D25\uFF1A{error}",actionFailed:"{label}\u5931\u8D25\uFF1A{error}",exported:"\u5DF2\u5BFC\u51FA \u2192 {path}",noCurrentNote:"\u6CA1\u6709\u5F53\u524D\u7B14\u8BB0",cacheClearedFile:"\u5DF2\u6E05\u9664\u7F13\u5B58\uFF1A{name}",cacheClearedAll:"\u5DF2\u6E05\u9664 {count} \u6761\u7F13\u5B58",noCancelableJob:"\u5F53\u524D\u6CA1\u6709\u53EF\u53D6\u6D88\u7684\u751F\u6210\u4EFB\u52A1",cancelRequested:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u751F\u6210",cancelRequestedApiInFlight:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u751F\u6210\uFF1B\u5F53\u524D API \u8BF7\u6C42\u65E0\u6CD5\u7ACB\u5373\u4E2D\u65AD\uFF0C\u8FD4\u56DE\u540E\u4F1A\u4E22\u5F03\u7ED3\u679C\u3002",fileMenuGenerate:"\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",fileMenuRegen:"\u5F3A\u5236\u91CD\u65B0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",fileMenuClear:"\u6E05\u9664\u5BF9\u7167\u7B14\u8BB0\u7F13\u5B58",noExportContent:"\u5F53\u524D\u6CA1\u6709\u53EF\u5BFC\u51FA\u7684\u5BF9\u7167\u7B14\u8BB0",noCopyContent:"\u5F53\u524D\u6CA1\u6709\u53EF\u590D\u5236\u7684\u5BF9\u7167\u7B14\u8BB0",noActiveCard:"\u5F53\u524D\u6CA1\u6709\u53EF\u8DF3\u8F6C\u7684\u6458\u8981\u5361\u7247",confirmRegenerateEditedCards:"\u8FD9\u7BC7\u7B14\u8BB0\u7684\u5BF9\u7167\u5361\u7247\u5DF2\u88AB\u624B\u52A8\u7F16\u8F91\u3002\u91CD\u65B0\u751F\u6210\u4F1A\u8986\u76D6\u8FD9\u4E9B\u4FEE\u6539\uFF0C\u662F\u5426\u7EE7\u7EED\uFF1F",regenerateCancelled:"\u5DF2\u53D6\u6D88\u91CD\u65B0\u751F\u6210",cardDeleted:"\u5DF2\u5220\u9664\u6B64\u5361\u7247",cardSaved:"\u5DF2\u4FDD\u5B58\u6B64\u5361\u7247",editCardTitle:"\u7F16\u8F91\u6458\u8981\u5361\u7247",editCardTitleField:"\u6807\u9898",editCardGistField:"\u9886\u8BFB",editCardBulletsField:"\u8981\u70B9\uFF08\u6BCF\u884C\u4E00\u6761\uFF09",editCardCancel:"\u53D6\u6D88",editCardSave:"\u4FDD\u5B58",openNoteFirst:"\u5148\u6253\u5F00\u4E00\u7BC7\u7B14\u8BB0",alreadyGenerating:"\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",emptyNote:"\u7B14\u8BB0\u4E3A\u7A7A",longNoteTruncated:"\u7B14\u8BB0\u8F83\u957F\uFF1A\u4EC5\u53D1\u9001\u524D {count} \u4E2A\u5B57\u7B26\u7ED9\u6A21\u578B",generatingNotice:"\u5BF9\u7167\u9605\u8BFB\uFF1A\u8BA9 LLM \u8BFB\u5168\u6587\u5E76\u81EA\u9002\u5E94\u5207\u6BB5\u2026",noCardsReturned:"LLM \u672A\u8FD4\u56DE\u4EFB\u4F55 card",generationDone:"\u5BF9\u7167\u7B14\u8BB0\u751F\u6210\u5B8C\u6210\uFF1A{count} \u6BB5{suffix}",unanchoredSuffix:"\uFF08\u26A0 {count} \u6BB5 anchor \u672A\u5339\u914D\uFF09",cancelled:"\u5DF2\u53D6\u6D88\u751F\u6210",cancelledError:"\u751F\u6210\u5DF2\u53D6\u6D88",generationFailed:"\u751F\u6210\u5931\u8D25{kind}\uFF1A{error}",errorCustomProviderBaseUrlRequired:"\u81EA\u5B9A\u4E49 provider \u9700\u8981\u586B\u5199 API Base URL\u3002",errorApiBaseUrlMissing:"API Base URL \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u9009\u62E9 provider \u6216\u586B\u5199\u81EA\u5B9A\u4E49 base URL\u3002",errorModelMissing:"Model \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u586B\u5199\u6A21\u578B ID\u3002",errorApiKeyMissing:"API key \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u586B\u5199 API Key{hint}\u3002",errorApiKeyEnvHint:" \u6216\u73AF\u5883\u53D8\u91CF {envVar}",errorLlmNonJson:`LLM \u8FD4\u56DE\u975E JSON\uFF1A +"use strict";var st=Object.create;var q=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var dt=(r,n)=>{for(var e in n)q(r,e,{get:n[e],enumerable:!0})},He=(r,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of lt(n))!ut.call(r,i)&&i!==e&&q(r,i,{get:()=>n[i],enumerable:!(t=ot(n,i))||t.enumerable});return r};var W=(r,n,e)=>(e=r!=null?st(ct(r)):{},He(n||!r||!r.__esModule?q(e,"default",{value:r,enumerable:!0}):e,r)),pt=r=>He(q({},"__esModule",{value:!0}),r);var _t={};dt(_t,{__test:()=>Ot,default:()=>Lt});module.exports=pt(_t);var u=require("obsidian");function Y(r,n){if(!n)return-1;let e=d=>d.replace(/\s+/g," ").trim(),t=d=>{let b=[],y=[],c=!1;for(let g=0;g0;continue}c&&(b.push(" "),y.push(g),c=!1),b.push(Ue),y.push(g)}return{text:b.join(""),map:y}},i=d=>{if(!d)return-1;let b=r.indexOf(d);if(b===-1)return-1;let y=0;for(let c=0;c=0||(a=i(n.trim()),a>=0))return a;for(let d of[60,40,25,15]){let b=n.trim().slice(0,d);if(a=i(b),a>=0)return a}let s=t(r),o=e(n).slice(0,30);if(!o)return-1;let l=s.text.indexOf(o);if(l===-1)return-1;let f=s.map[l];if(f==null)return-1;let p=0;for(let d=0;d0}function X(r,n){let e=Array.isArray(r)?r.slice():[];return!Number.isInteger(n)||n<0||n>=e.length||e.splice(n,1),e}function Z(r,n,e){if(!Number.isInteger(r)||!Number.isInteger(n)||n<=0||!Number.isInteger(e)||e<0||r<0||r>=n)return e;let t=n-1;return t<=0?-1:r=t.length||(t[n]=Object.assign({},t[n],e||{})),t}var Ke=require("child_process"),$e=W(require("fs")),re=W(require("os")),P=W(require("path"));var O=class extends Error{constructor(n){super("\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0"),this.name="GenerationJobAlreadyRunningError",this.code="already-running",this.key=n}},A=class extends Error{constructor(n){super("\u751F\u6210\u5DF2\u53D6\u6D88"),this.name="GenerationJobCancelledError",this.code="cancelled",this.key=n}},be=class{constructor(n){this.key=n,this.phase="queued",this.cancelled=!1,this.startedAt=new Date().toISOString(),this.updatedAt=this.startedAt,this._cancelHandlers=[]}setPhase(n){this.phase=n,this.updatedAt=new Date().toISOString()}onCancel(n){if(typeof n=="function"){if(this.cancelled){n();return}this._cancelHandlers.push(n)}}cancel(){if(this.cancelled)return!1;this.cancelled=!0,this.setPhase("cancelled");for(let n of this._cancelHandlers.splice(0))try{n()}catch{}return!0}throwIfCancelled(){if(this.cancelled)throw new A(this.key)}},U=class{constructor(){this.jobs=new Map}get(n){return this.jobs.get(n)||null}isRunning(n){return this.jobs.has(n)}async start(n,e){if(this.jobs.has(n))throw new O(n);let t=new be(n);this.jobs.set(n,t);try{t.setPhase("running");let i=await e(t);return t.throwIfCancelled(),i}catch(i){throw t.cancelled&&!(i instanceof A)?new A(n):i}finally{this.jobs.delete(n)}}cancel(n){let e=this.jobs.get(n);return e?e.cancel():!1}};function we(r){if(r instanceof A)return"cancelled";let n=r;if(n?.code==="cancelled")return"cancelled";let e=String(n?.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 ee={zh:{appTitle:"\u5BF9\u7167\u9605\u8BFB\u7B14\u8BB0",settingsTitle:"Parallel Reader \u8BBE\u7F6E",emptyOpenNote:"\u6253\u5F00\u4E00\u7BC7\u7B14\u8BB0\uFF0C\u7136\u540E\u8FD0\u884C\u547D\u4EE4\uFF1A",emptyNoCache:"\u8BE5\u7B14\u8BB0\u5C1A\u65E0\u5BF9\u7167\u7B14\u8BB0\u7F13\u5B58\u3002\u8FD0\u884C\u547D\u4EE4\uFF1A",commandGenerate:"Parallel Reader: \u4E3A\u5F53\u524D\u7B14\u8BB0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",displayName:"\u5BF9\u7167\u9605\u8BFB\u7B14\u8BB0",ribbonOpen:"\u6253\u5F00\u5BF9\u7167\u7B14\u8BB0\u9762\u677F",cmdRun:"\u4E3A\u5F53\u524D\u7B14\u8BB0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0\uFF08\u7F13\u5B58\u4F18\u5148\uFF09",cmdRegen:"\u5F3A\u5236\u91CD\u65B0\u751F\u6210\uFF08\u7ED5\u8FC7\u7F13\u5B58\uFF09",cmdOpenView:"\u6253\u5F00\u5BF9\u7167\u7B14\u8BB0\u9762\u677F",cmdExport:"\u5BFC\u51FA\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0\u5230 Vault",cmdCopyMarkdown:"\u590D\u5236\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0 Markdown",cmdCancel:"\u53D6\u6D88\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0\u751F\u6210",cmdClearCurrent:"\u6E05\u9664\u5F53\u524D\u7B14\u8BB0\u7684\u7F13\u5B58",cmdClearAll:"\u6E05\u9664\u6240\u6709\u7F13\u5B58",cmdCardPrev:"\u805A\u7126\u4E0A\u4E00\u5F20\u6458\u8981\u5361\u7247",cmdCardNext:"\u805A\u7126\u4E0B\u4E00\u5F20\u6458\u8981\u5361\u7247",cmdCardJump:"\u8DF3\u8F6C\u5230\u5F53\u524D\u6458\u8981\u5361\u7247\u539F\u6587",actionCancel:"\u53D6\u6D88\u751F\u6210",actionRegenerate:"\u91CD\u65B0\u751F\u6210",actionCopyAll:"\u590D\u5236\u5168\u90E8 Markdown",actionExport:"\u5BFC\u51FA\u5230 Vault",staleBanner:"\u6E90\u7B14\u8BB0\u6216\u751F\u6210\u914D\u7F6E\u5DF2\u4FEE\u6539\uFF0C\u5F53\u524D\u662F\u65E7\u7F13\u5B58\u3002",loadingDefault:"\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0...",loadingGenerating:"\u5BF9\u7167\u9605\u8BFB\uFF1A\u8BA9 LLM \u8BFB\u5168\u6587\u5E76\u81EA\u9002\u5E94\u5207\u6BB5...",loadingSubtitle:"\u53EF\u4EE5\u7EE7\u7EED\u9605\u8BFB\u539F\u6587\uFF0C\u751F\u6210\u5B8C\u6210\u540E\u4F1A\u81EA\u52A8\u5237\u65B0\u53F3\u4FA7\u5361\u7247\u3002",errorTitle:"\u751F\u6210\u5931\u8D25",emptyCard:"\uFF08\u672A\u751F\u6210\uFF09",anchorMismatch:"anchor \u5339\u914D\u5931\u8D25\uFF0C\u65E0\u6CD5\u6EDA\u52A8\u8054\u52A8",menuCopyMarkdown:"\u590D\u5236 Markdown",menuCopyPlain:"\u590D\u5236\u7EAF\u6587\u672C",menuCopyAnchor:"\u590D\u5236 anchor \u5F15\u7528",menuJumpSource:"\u8DF3\u8F6C\u5230\u539F\u6587",menuEditCard:"\u7F16\u8F91\u6B64\u5361\u7247",menuDeleteCard:"\u5220\u9664\u6B64\u5361\u7247",copiedMarkdown:"\u5DF2\u590D\u5236 Markdown",copiedPlain:"\u5DF2\u590D\u5236\u7EAF\u6587\u672C",copiedAnchor:"\u5DF2\u590D\u5236\u5F15\u7528\u539F\u6587",copiedAllMarkdown:"\u5DF2\u590D\u5236\u5168\u90E8 Markdown",copyFailed:"\u590D\u5236\u5931\u8D25\uFF1A{error}",actionFailed:"{label}\u5931\u8D25\uFF1A{error}",exported:"\u5DF2\u5BFC\u51FA \u2192 {path}",noCurrentNote:"\u6CA1\u6709\u5F53\u524D\u7B14\u8BB0",cacheClearedFile:"\u5DF2\u6E05\u9664\u7F13\u5B58\uFF1A{name}",cacheClearedAll:"\u5DF2\u6E05\u9664 {count} \u6761\u7F13\u5B58",noCancelableJob:"\u5F53\u524D\u6CA1\u6709\u53EF\u53D6\u6D88\u7684\u751F\u6210\u4EFB\u52A1",cancelRequested:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u751F\u6210",cancelRequestedApiInFlight:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u751F\u6210\uFF1B\u5F53\u524D API \u8BF7\u6C42\u65E0\u6CD5\u7ACB\u5373\u4E2D\u65AD\uFF0C\u8FD4\u56DE\u540E\u4F1A\u4E22\u5F03\u7ED3\u679C\u3002",fileMenuGenerate:"\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",fileMenuRegen:"\u5F3A\u5236\u91CD\u65B0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",fileMenuClear:"\u6E05\u9664\u5BF9\u7167\u7B14\u8BB0\u7F13\u5B58",noExportContent:"\u5F53\u524D\u6CA1\u6709\u53EF\u5BFC\u51FA\u7684\u5BF9\u7167\u7B14\u8BB0",noCopyContent:"\u5F53\u524D\u6CA1\u6709\u53EF\u590D\u5236\u7684\u5BF9\u7167\u7B14\u8BB0",noActiveCard:"\u5F53\u524D\u6CA1\u6709\u53EF\u8DF3\u8F6C\u7684\u6458\u8981\u5361\u7247",confirmRegenerateEditedCards:"\u8FD9\u7BC7\u7B14\u8BB0\u7684\u5BF9\u7167\u5361\u7247\u5DF2\u88AB\u624B\u52A8\u7F16\u8F91\u3002\u91CD\u65B0\u751F\u6210\u4F1A\u8986\u76D6\u8FD9\u4E9B\u4FEE\u6539\uFF0C\u662F\u5426\u7EE7\u7EED\uFF1F",regenerateCancelled:"\u5DF2\u53D6\u6D88\u91CD\u65B0\u751F\u6210",cardDeleted:"\u5DF2\u5220\u9664\u6B64\u5361\u7247",cardSaved:"\u5DF2\u4FDD\u5B58\u6B64\u5361\u7247",editCardTitle:"\u7F16\u8F91\u6458\u8981\u5361\u7247",editCardTitleField:"\u6807\u9898",editCardGistField:"\u9886\u8BFB",editCardBulletsField:"\u8981\u70B9\uFF08\u6BCF\u884C\u4E00\u6761\uFF09",editCardCancel:"\u53D6\u6D88",editCardSave:"\u4FDD\u5B58",openNoteFirst:"\u5148\u6253\u5F00\u4E00\u7BC7\u7B14\u8BB0",alreadyGenerating:"\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",emptyNote:"\u7B14\u8BB0\u4E3A\u7A7A",longNoteTruncated:"\u7B14\u8BB0\u8F83\u957F\uFF1A\u4EC5\u53D1\u9001\u524D {count} \u4E2A\u5B57\u7B26\u7ED9\u6A21\u578B",generatingNotice:"\u5BF9\u7167\u9605\u8BFB\uFF1A\u8BA9 LLM \u8BFB\u5168\u6587\u5E76\u81EA\u9002\u5E94\u5207\u6BB5\u2026",noCardsReturned:"LLM \u672A\u8FD4\u56DE\u4EFB\u4F55 card",generationDone:"\u5BF9\u7167\u7B14\u8BB0\u751F\u6210\u5B8C\u6210\uFF1A{count} \u6BB5{suffix}",unanchoredSuffix:"\uFF08\u26A0 {count} \u6BB5 anchor \u672A\u5339\u914D\uFF09",cancelled:"\u5DF2\u53D6\u6D88\u751F\u6210",cancelledError:"\u751F\u6210\u5DF2\u53D6\u6D88",generationFailed:"\u751F\u6210\u5931\u8D25{kind}\uFF1A{error}",errorCustomProviderBaseUrlRequired:"\u81EA\u5B9A\u4E49 provider \u9700\u8981\u586B\u5199 API Base URL\u3002",errorApiBaseUrlMissing:"API Base URL \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u9009\u62E9 provider \u6216\u586B\u5199\u81EA\u5B9A\u4E49 base URL\u3002",errorModelMissing:"Model \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u586B\u5199\u6A21\u578B ID\u3002",errorApiKeyMissing:"API key \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u586B\u5199 API Key{hint}\u3002",errorApiKeyEnvHint:" \u6216\u73AF\u5883\u53D8\u91CF {envVar}",errorLlmNonJson:`LLM \u8FD4\u56DE\u975E JSON\uFF1A {excerpt}`,errorCustomHeadersJsonParse:"\u81EA\u5B9A\u4E49 headers JSON \u89E3\u6790\u5931\u8D25\uFF1A{error}",errorCustomHeadersJsonObject:"\u81EA\u5B9A\u4E49 headers JSON \u5FC5\u987B\u662F\u5BF9\u8C61",errorCustomHeadersLineFormat:"\u81EA\u5B9A\u4E49 headers \u6BCF\u884C\u683C\u5F0F\u5E94\u4E3A `Header-Name: value`",errorProviderNonJson:`{label} \u8FD4\u56DE\u975E JSON\uFF1A {excerpt}`,errorProviderRequestFailed:"{label} \u8BF7\u6C42\u5931\u8D25\uFF1A{error}",errorProviderApiStatus:"{label} API \u8FD4\u56DE HTTP {status}\uFF1A{excerpt}",noEditor:"\u627E\u4E0D\u5230\u6E90\u7B14\u8BB0\u5BF9\u5E94\u7684\u7F16\u8F91\u5668\u7A97\u53E3",settingUiLanguageName:"\u754C\u9762\u8BED\u8A00",settingUiLanguageDesc:"\u63A7\u5236\u63D2\u4EF6\u754C\u9762\u3001\u547D\u4EE4\u548C\u63D0\u793A\u6587\u6848\uFF1BAuto \u8DDF\u968F Obsidian/\u7CFB\u7EDF\u8BED\u8A00",settingBackendName:"Backend",settingBackendDesc:"\u751F\u6210 bullet \u7684\u540E\u7AEF\uFF1ACLI \u590D\u7528\u672C\u673A\u767B\u5F55\uFF1BAPI \u652F\u6301 OpenAI/Anthropic/Gemini \u53CA\u517C\u5BB9\u4EE3\u7406",settingCliPathName:"CLI \u8DEF\u5F84\uFF08\u53EF\u9009\uFF09",settingCliPathDesc:"\u7559\u7A7A\u5219\u81EA\u52A8\u63A2\u6D4B\u5E38\u89C1\u4F4D\u7F6E\uFF1BObsidian GUI \u542F\u52A8\u65F6\u4E0D\u7EE7\u627F shell PATH\uFF0C\u5FC5\u8981\u65F6\u586B\u7EDD\u5BF9\u8DEF\u5F84",settingCliPathPlaceholder:"\u4F8B\uFF1A/Users/you/bin/codex",settingCliTimeoutName:"CLI \u8D85\u65F6 (ms)",apiProviderHeader:"API Provider",settingProviderPresetName:"Provider preset",settingProviderPresetDesc:"\u53C2\u8003 OpenClaw \u7684 provider/model \u601D\u8DEF\uFF1Apreset \u53EA\u8D1F\u8D23\u534F\u8BAE\u3001base URL \u548C\u8BA4\u8BC1\u9ED8\u8BA4\u503C",settingApiFormatName:"API format",settingApiFormatDesc:"\u4E0D\u540C provider \u7684 wire protocol\uFF1BOpenAI-compatible \u4EE3\u7406\u901A\u5E38\u9009 Chat Completions",settingBaseUrlName:"Base URL",settingBaseUrlDesc:"\u586B provider \u6839\u5730\u5740\uFF0C\u4E0D\u8981\u9644\u52A0 /chat/completions\uFF1B\u7559\u7A7A\u65F6\u4F7F\u7528 preset \u9ED8\u8BA4\u503C",settingApiKeyName:"API Key",settingApiKeyDesc:"\u672C\u5730 Ollama/LM Studio \u53EF\u7559\u7A7A\uFF1B\u5176\u4ED6 provider \u901A\u5E38\u9700\u8981 key",settingApiKeyEnvName:"API Key \u73AF\u5883\u53D8\u91CF",settingApiKeyEnvDesc:"\u53EF\u9009\uFF1BObsidian GUI \u4E0D\u4E00\u5B9A\u7EE7\u627F shell \u73AF\u5883\uFF0C\u76F4\u63A5\u586B API Key \u66F4\u7A33\u5B9A",settingAuthTypeName:"\u8BA4\u8BC1\u65B9\u5F0F",settingAuthTypeDesc:"Auto \u4F7F\u7528 provider preset\uFF1B\u81EA\u5B9A\u4E49\u4EE3\u7406\u53EF\u6309\u9700\u8981\u6539\u6210 Bearer\u3001x-api-key \u6216 none",settingHeadersName:"\u989D\u5916 headers",settingHeadersDesc:"\u53EF\u9009\u3002\u652F\u6301 JSON \u5BF9\u8C61\u6216\u6BCF\u884C `Header: value`\uFF0C\u7528\u4E8E Cloudflare AI Gateway \u7B49\u4EE3\u7406",settingMaxTokensName:"\u6700\u5927\u8F93\u51FA tokens",settingModelName:"Model",settingModelDescApi:"API \u8C03\u7528\u7684\u6A21\u578B ID\uFF1B\u652F\u6301 OpenClaw \u98CE\u683C provider/model\uFF0C\u82E5 provider \u524D\u7F00\u5339\u914D\u5F53\u524D preset \u4F1A\u81EA\u52A8\u5265\u79BB",settingModelDescCli:"Claude Code \u4E0B\u4F1A\u4F20 --model\uFF1BCodex \u4E0B\u901A\u5E38\u5FFD\u7565\uFF08\u7528 Codex \u9ED8\u8BA4\u914D\u7F6E\uFF09",settingMaxInputName:"\u6700\u5927\u8F93\u5165\u5B57\u7B26\u6570",settingMaxInputDesc:"\u8D85\u8FC7\u8BE5\u957F\u5EA6\u4F1A\u622A\u65AD\u540E\u518D\u53D1\u9001\u7ED9\u6A21\u578B\uFF1B\u957F\u4E0A\u4E0B\u6587\u6A21\u578B\u53EF\u9002\u5F53\u8C03\u5927",promptHeader:"Prompt",settingPromptLanguageName:"\u8F93\u51FA\u8BED\u8A00",settingPromptLanguageDesc:"\u63A7\u5236 title/gist/bullets \u7684\u8BED\u8A00\uFF1Banchor \u59CB\u7EC8\u9010\u5B57\u590D\u5236\u539F\u6587",settingCardRangeName:"\u5361\u7247\u6570\u91CF\u8303\u56F4",settingCardRangeDesc:"\u6A21\u578B\u4F1A\u5728\u8FD9\u4E2A\u8303\u56F4\u5185\u81EA\u9002\u5E94\u5207\u6BB5",settingCustomPromptName:"\u81EA\u5B9A\u4E49 system prompt",settingCustomPromptDesc:"\u53EF\u9009\u3002\u652F\u6301\u53D8\u91CF\uFF1A{minCards}\u3001{maxCards}\u3001{languageInstruction}\u3001{schema}\u3001{example}",settingCustomPromptPlaceholder:"\u7559\u7A7A\u4F7F\u7528\u5185\u7F6E prompt",settingTestBackendName:"\u6D4B\u8BD5\u5F53\u524D\u540E\u7AEF",settingTestBackendDescApi:"\u4F1A\u53D1\u8D77\u4E00\u6B21\u6700\u5C0F LLM \u8BF7\u6C42\u9A8C\u8BC1 API \u8BBE\u7F6E",settingTestBackendDescCli:"\u8C03\u7528 ` --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"},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",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"}};function ht(r){let e=r?.uiLanguage;return e==="zh"||e==="en"?e:String((typeof navigator<"u"?navigator:null)?.language||"").toLowerCase().startsWith("zh")?"zh":"en"}function C(r,e,t){let n=ht(r),a=ee[n]||ee.en,i=ee.en[e]||ee.zh[e]||e,o=a[e]||i;return String(o).replace(/\{([a-zA-Z0-9_]+)\}/g,(s,l)=>t&&Object.hasOwn(t,l)?String(t[l]):s)}var te="record_parallel_reader_cards";function mt(r){let e=[],t=-1,n=0,a=!1,i=!1;for(let o=0;o0&&n--,n===0&&t>=0&&(e.push(r.slice(t,o+1)),t=-1))}return e}function ve(r){let e=(r||"").trim();if(!e)return e;try{return JSON.parse(e),e}catch{}let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t){let a=t[1].trim();try{return JSON.parse(a),a}catch{}}let n=mt(e);n.sort((a,i)=>i.length-a.length);for(let a of n)try{return JSON.parse(a),a}catch{}return e}function S(r,e){let t=ve(r),n;try{n=JSON.parse(t)}catch{throw new Error(C(e||null,"errorLlmNonJson",{excerpt:(r||"").slice(0,500)}))}return H(n)}function H(r){return(r&&Array.isArray(r.cards)?r.cards:[]).filter(t=>!!t&&typeof t=="object").map(t=>({title:typeof t.title=="string"?t.title:"(\u65E0\u6807\u9898)",anchor:typeof t.anchor=="string"?t.anchor:"",gist:typeof t.gist=="string"?t.gist:"",bullets:Array.isArray(t.bullets)?t.bullets.filter(n=>typeof n=="string"):[]}))}function j(r){let e={type:"object",properties:{title:{type:"string"},anchor:{type:"string"},gist:{type:"string"},bullets:{type:"array",items:{type:"string"}}},required:["title","anchor","gist","bullets"]},t={type:"object",properties:{cards:{type:"array",items:e}},required:["cards"]};return r&&(e.additionalProperties=!1,t.additionalProperties=!1),t}function je(){return{type:"json_schema",json_schema:{name:"parallel_reader_cards",strict:!0,schema:j(!0)}}}function Ge(){return{format:{type:"json_schema",name:"parallel_reader_cards",strict:!0,schema:j(!0)}}}function Je(){return{name:te,description:"Return the generated Parallel Reader summary cards.",input_schema:j(!0)}}function M(r,e){if(e?.trim())return e.trim();let t=re.default.homedir(),n=[x.default.join(t,"bin",r),x.default.join(t,".local/bin",r),x.default.join(t,".claude/local",r),x.default.join(t,".codex/bin",r),x.default.join(t,".bun/bin",r),x.default.join(t,".npm-global/bin",r),x.default.join(t,".cargo/bin",r),"/opt/homebrew/bin/"+r,"/usr/local/bin/"+r];for(let a of n)try{if($e.default.existsSync(a))return a}catch{}return r}function G(r,e,t,n,a){return new Promise((i,o)=>{let s,l=!1,d=null,g=c=>{l||(l=!0,d&&clearTimeout(d),o(c))},y=c=>{l||(l=!0,d&&clearTimeout(d),i(c))};try{s=(0,Ke.spawn)(r,e,{stdio:["pipe","pipe","pipe"],env:{...process.env,PATH:[process.env.PATH||"","/usr/local/bin","/opt/homebrew/bin",x.default.join(re.default.homedir(),".local/bin"),x.default.join(re.default.homedir(),".claude/local")].filter(Boolean).join(":")}})}catch(c){return o(new Error(`Failed to start ${r}: ${c.message}`))}let f="",h="";if(d=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}g(new Error(`CLI timed out (${n}ms)`))},n),a&&a.onCancel(()=>{try{s.kill("SIGKILL")}catch{}g(new v(a.key))}),s.stdout.on("data",c=>{f+=c.toString("utf8")}),s.stderr.on("data",c=>{h+=c.toString("utf8")}),s.on("error",c=>{g(new Error(`CLI startup error: ${c.message}. Try setting an absolute CLI path.`))}),s.on("close",c=>{if(!l){if(c!==0)return g(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"}};function ht(r){let n=r?.uiLanguage;return n==="zh"||n==="en"?n:String((typeof navigator<"u"?navigator:null)?.language||"").toLowerCase().startsWith("zh")?"zh":"en"}function C(r,n,e){let t=ht(r),i=ee[t]||ee.en,a=ee.en[n]||ee.zh[n]||n,s=i[n]||a;return String(s).replace(/\{([a-zA-Z0-9_]+)\}/g,(o,l)=>e&&Object.hasOwn(e,l)?String(e[l]):o)}var te="record_parallel_reader_cards";function mt(r){let n=[],e=-1,t=0,i=!1,a=!1;for(let s=0;s0&&t--,t===0&&e>=0&&(n.push(r.slice(e,s+1)),e=-1))}return n}function ve(r){let n=(r||"").trim();if(!n)return n;try{return JSON.parse(n),n}catch{}let e=n.match(/```(?:json)?\s*([\s\S]*?)```/);if(e){let i=e[1].trim();try{return JSON.parse(i),i}catch{}}let t=mt(n);t.sort((i,a)=>a.length-i.length);for(let i of t)try{return JSON.parse(i),i}catch{}return n}function E(r,n){let e=ve(r),t;try{t=JSON.parse(e)}catch{throw new Error(C(n||null,"errorLlmNonJson",{excerpt:(r||"").slice(0,500)}))}return H(t)}function H(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(t=>typeof t=="string"):[]}))}function j(r){let n={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:n}},required:["cards"]};return r&&(n.additionalProperties=!1,e.additionalProperties=!1),e}function je(){return{type:"json_schema",json_schema:{name:"parallel_reader_cards",strict:!0,schema:j(!0)}}}function Ge(){return{format:{type:"json_schema",name:"parallel_reader_cards",strict:!0,schema:j(!0)}}}function Je(){return{name:te,description:"Return the generated Parallel Reader summary cards.",input_schema:j(!0)}}function M(r,n){if(n?.trim())return n.trim();let e=re.default.homedir(),t=[P.default.join(e,"bin",r),P.default.join(e,".local/bin",r),P.default.join(e,".claude/local",r),P.default.join(e,".codex/bin",r),P.default.join(e,".bun/bin",r),P.default.join(e,".npm-global/bin",r),P.default.join(e,".cargo/bin",r),"/opt/homebrew/bin/"+r,"/usr/local/bin/"+r];for(let i of t)try{if($e.default.existsSync(i))return i}catch{}return r}function G(r,n,e,t,i){return new Promise((a,s)=>{let o,l=!1,f=null,p=c=>{l||(l=!0,f&&clearTimeout(f),s(c))},d=c=>{l||(l=!0,f&&clearTimeout(f),a(c))};try{o=(0,Ke.spawn)(r,n,{stdio:["pipe","pipe","pipe"],env:{...process.env,PATH:[process.env.PATH||"","/usr/local/bin","/opt/homebrew/bin",P.default.join(re.default.homedir(),".local/bin"),P.default.join(re.default.homedir(),".claude/local")].filter(Boolean).join(":")}})}catch(c){return s(new Error(`Failed to start ${r}: ${c.message}`))}let b="",y="";if(f=setTimeout(()=>{try{o.kill("SIGKILL")}catch{}p(new Error(`CLI timed out (${t}ms)`))},t),i&&i.onCancel(()=>{try{o.kill("SIGKILL")}catch{}p(new A(i.key))}),o.stdout.on("data",c=>{b+=c.toString("utf8")}),o.stderr.on("data",c=>{y+=c.toString("utf8")}),o.on("error",c=>{p(new Error(`CLI startup error: ${c.message}. Try setting an absolute CLI path.`))}),o.on("close",c=>{if(!l){if(c!==0)return p(new Error(`CLI exited with code ${c} stderr: -${h.slice(0,1e3)}`));y({stdout:f,stderr:h})}}),t)try{s.stdin.write(t),s.stdin.end()}catch{}else try{s.stdin.end()}catch{}})}async function ze(r,e,t,n){let a=M("claude",t.cliPath),i=["-p","--output-format","json","--append-system-prompt",r,"--disallowed-tools","Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,TodoWrite,Task"];t.model&&i.push("--model",t.model);let{stdout:o}=await G(a,i,e,t.cliTimeoutMs,n),s;try{s=JSON.parse(o)}catch{throw new Error(`claude CLI returned a non-JSON envelope: -`+o.slice(0,500))}let l=s.result||s.content||"";return S(l,t)}async function qe(r,e,t,n){let a=M("codex",t.cliPath),i=`<> +${y.slice(0,1e3)}`));d({stdout:b,stderr:y})}}),e)try{o.stdin.write(e),o.stdin.end()}catch{}else try{o.stdin.end()}catch{}})}async function ze(r,n,e,t){let i=M("claude",e.cliPath),a=["-p","--output-format","json","--append-system-prompt",r,"--disallowed-tools","Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,TodoWrite,Task"];e.model&&a.push("--model",e.model);let{stdout:s}=await G(i,a,n,e.cliTimeoutMs,t),o;try{o=JSON.parse(s)}catch{throw new Error(`claude CLI returned a non-JSON envelope: +`+s.slice(0,500))}let l=o.result||o.content||"";return E(l,e)}async function qe(r,n,e,t){let i=M("codex",e.cliPath),a=`<> ${r} <> -${e} +${n} -Output JSON directly with no explanation.`,o=["exec","--skip-git-repo-check","-"],{stdout:s}=await G(a,o,i,t.cliTimeoutMs,n);return S(s,t)}function Ae(r){let e=[`## ${r.title}`];if(r.anchor){let t=r.anchor.replace(/\s+/g," ").trim();e.push(`> ${t}`)}return r.gist&&e.push(r.gist),r.bullets&&r.bullets.length>0&&e.push(r.bullets.map(t=>`- ${t}`).join(` -`)),e.join(` +Output JSON directly with no explanation.`,s=["exec","--skip-git-repo-check","-"],{stdout:o}=await G(i,s,a,e.cliTimeoutMs,t);return E(o,e)}function Ae(r){let n=[`## ${r.title}`];if(r.anchor){let e=r.anchor.replace(/\s+/g," ").trim();n.push(`> ${e}`)}return r.gist&&n.push(r.gist),r.bullets&&r.bullets.length>0&&n.push(r.bullets.map(e=>`- ${e}`).join(` +`)),n.join(` -`)}function We(r){return[r.title,r.gist||"",...(r.bullets||[]).map(e=>"\u2022 "+e)].filter(Boolean).join(` -`)}function J(r,e){let t=[`# ${r||"\u5BF9\u7167\u7B14\u8BB0"}`];for(let n of e||[])t.push(Ae(n));return t.join(` +`)}function We(r){return[r.title,r.gist||"",...(r.bullets||[]).map(n=>"\u2022 "+n)].filter(Boolean).join(` +`)}function J(r,n){let e=[`# ${r||"\u5BF9\u7167\u7B14\u8BB0"}`];for(let t of n||[])e.push(Ae(t));return e.join(` -`)}function ne(r,e,t){if(!Number.isFinite(e)||e<=0)return-1;let n=Math.floor(e),a=t<0?-1:1;return r<0||r>=n?a<0?n-1:0:Math.min(n-1,Math.max(0,r+a))}function ae(r,e){if(!Array.isArray(r)||e<0||e>=r.length)return-1;let t=Number(r[e]?.startLine);return Number.isFinite(t)&&t>=0?t:-1}var Ze=W(require("crypto"));var Pe=2e4,gt=2,K=2,V=100,$={zh:"\u4E2D\u6587",en:"English",auto:"Auto-detect"},Te={auto:"Auto",zh:"\u4E2D\u6587",en:"English"},m={uiLanguage:"auto",backend:"claude-code",cliPath:"",apiProvider:"anthropic",apiFormat:"anthropic-messages",apiBaseUrl:"",apiKey:"",apiKeyEnvVar:"",apiAuthType:"auto",apiHeaders:"",apiMaxTokens:4096,maxDocChars:Pe,maxCacheEntries:V,promptLanguage:"zh",minCards:5,maxCards:15,customSystemPrompt:"",model:"claude-sonnet-4-6",exportFolder:"Reading/Articles",cliTimeoutMs:12e4},A={"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"}},Se={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"},E={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 Ze.default.createHash("sha1").update(r,"utf8").digest("hex")}function xe(r){return Array.isArray(r)?"["+r.map(xe).join(",")+"]":r&&typeof r=="object"?"{"+Object.keys(r).sort().map(e=>JSON.stringify(e)+":"+xe(r[e])).join(",")+"}":JSON.stringify(r)}function B(r){return r==="api"||r==="anthropic-api"}function b(r){return E[r.apiProvider]||E.anthropic}function P(r){let e=b(r),t=(r.apiFormat||e.format||"").trim();return A[t]?t:e.format}function D(r){let e=P(r),t=b(r),n=(r.apiBaseUrl||"").trim();if(n)return n.replace(/\/+$/,"");if((r.apiProvider||"").startsWith("custom-"))throw new Error(C(r,"errorCustomProviderBaseUrlRequired"));let a=(t.baseUrl||A[e].defaultBaseUrl||"").trim();if(!a)throw new Error(C(r,"errorApiBaseUrlMissing"));return a.replace(/\/+$/,"")}function Ee(r){let e=(r.apiAuthType||"auto").trim();if(e&&e!=="auto")return e;let t=b(r),n=P(r);return t.authType||A[n].defaultAuthType||"bearer"}function Qe(r){let e=(r.apiKey||"").trim();if(e)return e;let t=(r.apiKeyEnvVar||b(r).envVar||"").trim();return t&&process.env?.[t]?String(process.env[t]).trim():""}function I(r){let e=(r.model||"").trim();if(!e)throw new Error(C(r,"errorModelMissing"));let t=b(r),n=[r.apiProvider,t.modelPrefix].map(i=>(i||"").trim()).filter(Boolean),a=e.toLowerCase();for(let i of n){let o=i.toLowerCase();if(a.startsWith(o+"/"))return e.slice(i.length+1).trim()}return e}function Fe(r,e){let t=b(r),n=E[e]||E.anthropic,a=(r.model||"").trim(),i=!a||a===m.model||!!t.model&&a===t.model;r.apiProvider=e,r.apiFormat=n.format,r.apiBaseUrl=n.baseUrl,r.apiAuthType=n.authType||"auto",r.apiKeyEnvVar=n.envVar||"",i&&(r.model=n.model||"")}function ke(r){Te[r.uiLanguage]||(r.uiLanguage=m.uiLanguage),(!r.apiProvider||!E[r.apiProvider])&&(r.apiProvider="anthropic");let e=b(r);(!r.apiFormat||!A[r.apiFormat])&&(r.apiFormat=e.format),(!r.apiAuthType||!Se[r.apiAuthType])&&(r.apiAuthType="auto"),r.backend==="anthropic-api"&&(r.apiProvider=r.apiProvider||"anthropic",r.apiFormat=r.apiFormat||"anthropic-messages",r.apiBaseUrl=r.apiBaseUrl||E.anthropic.baseUrl,r.apiAuthType=r.apiAuthType||"x-api-key",r.apiKeyEnvVar=r.apiKeyEnvVar||"ANTHROPIC_API_KEY");let t=Number(r.apiMaxTokens);(!Number.isFinite(t)||t<=0)&&(r.apiMaxTokens=m.apiMaxTokens);let n=Number(r.maxDocChars);return(!Number.isFinite(n)||n<1e3)&&(r.maxDocChars=m.maxDocChars),r.maxCacheEntries=et(r.maxCacheEntries),$[r.promptLanguage]||(r.promptLanguage=m.promptLanguage),r.minCards=Ye(r.minCards,m.minCards),r.maxCards=Ye(r.maxCards,m.maxCards),r.maxCardsXe(o)-Xe(l)||i.localeCompare(s)).slice(0,n.length-t).map(([i])=>i);for(let i of a)delete r[i];return a}function ie(r){let e=ke(Object.assign({},m,r||{})),t=B(e.backend),n=b(e),a=P(e),i=t?(e.apiBaseUrl||n.baseUrl||A[a]?.defaultBaseUrl||"").trim().replace(/\/+$/,""):"";return _(xe({cacheSchemaVersion:K,promptVersion:gt,maxDocChars:Number(e.maxDocChars)||m.maxDocChars,promptLanguage:e.promptLanguage,minCards:e.minCards,maxCards:e.maxCards,customSystemPromptHash:_(e.customSystemPrompt||""),backend:e.backend,model:e.model,apiProvider:t?e.apiProvider:"",apiFormat:t?a:"",apiBaseUrl:i,apiAuthType:t?Ee(e):"",apiHeadersHash:t?_(e.apiHeaders||""):"",apiMaxTokens:t?Number(e.apiMaxTokens)||m.apiMaxTokens:0,structuredOutputVersion:1}))}function se(r,e,t){return!!r&&r.schemaVersion===K&&r.contentHash===_(e)&&r.settingsHash===ie(t)}function ft(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 yt(r){return r==="en"?`{"cards":[ +`)}function ne(r,n,e){if(!Number.isFinite(n)||n<=0)return-1;let t=Math.floor(n),i=e<0?-1:1;return r<0||r>=t?i<0?t-1:0:Math.min(t-1,Math.max(0,r+i))}function ae(r,n){if(!Array.isArray(r)||n<0||n>=r.length)return-1;let e=Number(r[n]?.startLine);return Number.isFinite(e)&&e>=0?e:-1}var Ze=W(require("crypto"));var Pe=2e4,gt=2,K=2,V=100,$={zh:"\u4E2D\u6587",en:"English",auto:"Auto-detect"},Te={auto:"Auto",zh:"\u4E2D\u6587",en:"English"},m={uiLanguage:"auto",backend:"claude-code",cliPath:"",apiProvider:"anthropic",apiFormat:"anthropic-messages",apiBaseUrl:"",apiKey:"",apiKeyEnvVar:"",apiAuthType:"auto",apiHeaders:"",apiMaxTokens:4096,maxDocChars:Pe,maxCacheEntries:V,promptLanguage:"zh",minCards:5,maxCards:15,customSystemPrompt:"",model:"claude-sonnet-4-6",exportFolder:"Reading/Articles",cliTimeoutMs:12e4},x={"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"}},Se={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"},k={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 Ze.default.createHash("sha1").update(r,"utf8").digest("hex")}function xe(r){return Array.isArray(r)?"["+r.map(xe).join(",")+"]":r&&typeof r=="object"?"{"+Object.keys(r).sort().map(n=>JSON.stringify(n)+":"+xe(r[n])).join(",")+"}":JSON.stringify(r)}function B(r){return r==="api"||r==="anthropic-api"}function w(r){return k[r.apiProvider]||k.anthropic}function T(r){let n=w(r),e=(r.apiFormat||n.format||"").trim();return x[e]?e:n.format}function D(r){let n=T(r),e=w(r),t=(r.apiBaseUrl||"").trim();if(t)return t.replace(/\/+$/,"");if((r.apiProvider||"").startsWith("custom-"))throw new Error(C(r,"errorCustomProviderBaseUrlRequired"));let i=(e.baseUrl||x[n].defaultBaseUrl||"").trim();if(!i)throw new Error(C(r,"errorApiBaseUrlMissing"));return i.replace(/\/+$/,"")}function Ee(r){let n=(r.apiAuthType||"auto").trim();if(n&&n!=="auto")return n;let e=w(r),t=T(r);return e.authType||x[t].defaultAuthType||"bearer"}function Qe(r){let n=(r.apiKey||"").trim();if(n)return n;let e=(r.apiKeyEnvVar||w(r).envVar||"").trim();return e&&process.env?.[e]?String(process.env[e]).trim():""}function I(r){let n=(r.model||"").trim();if(!n)throw new Error(C(r,"errorModelMissing"));let e=w(r),t=[r.apiProvider,e.modelPrefix].map(a=>(a||"").trim()).filter(Boolean),i=n.toLowerCase();for(let a of t){let s=a.toLowerCase();if(i.startsWith(s+"/"))return n.slice(a.length+1).trim()}return n}function ke(r,n){let e=w(r),t=k[n]||k.anthropic,i=(r.model||"").trim(),a=!i||i===m.model||!!e.model&&i===e.model;r.apiProvider=n,r.apiFormat=t.format,r.apiBaseUrl=t.baseUrl,r.apiAuthType=t.authType||"auto",r.apiKeyEnvVar=t.envVar||"",a&&(r.model=t.model||"")}function Fe(r){Te[r.uiLanguage]||(r.uiLanguage=m.uiLanguage),(!r.apiProvider||!k[r.apiProvider])&&(r.apiProvider="anthropic");let n=w(r);(!r.apiFormat||!x[r.apiFormat])&&(r.apiFormat=n.format),(!r.apiAuthType||!Se[r.apiAuthType])&&(r.apiAuthType="auto"),r.backend==="anthropic-api"&&(r.apiProvider=r.apiProvider||"anthropic",r.apiFormat=r.apiFormat||"anthropic-messages",r.apiBaseUrl=r.apiBaseUrl||k.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=m.apiMaxTokens);let t=Number(r.maxDocChars);return(!Number.isFinite(t)||t<1e3)&&(r.maxDocChars=m.maxDocChars),r.maxCacheEntries=et(r.maxCacheEntries),$[r.promptLanguage]||(r.promptLanguage=m.promptLanguage),r.minCards=Ye(r.minCards,m.minCards),r.maxCards=Ye(r.maxCards,m.maxCards),r.maxCardsXe(s)-Xe(l)||a.localeCompare(o)).slice(0,t.length-e).map(([a])=>a);for(let a of i)delete r[a];return i}function ie(r){let n=Fe(Object.assign({},m,r||{})),e=B(n.backend),t=w(n),i=T(n),a=e?(n.apiBaseUrl||t.baseUrl||x[i]?.defaultBaseUrl||"").trim().replace(/\/+$/,""):"";return _(xe({cacheSchemaVersion:K,promptVersion:gt,maxDocChars:Number(n.maxDocChars)||m.maxDocChars,promptLanguage:n.promptLanguage,minCards:n.minCards,maxCards:n.maxCards,customSystemPromptHash:_(n.customSystemPrompt||""),backend:n.backend,model:n.model,apiProvider:e?n.apiProvider:"",apiFormat:e?i:"",apiBaseUrl:a,apiAuthType:e?Ee(n):"",apiHeadersHash:e?_(n.apiHeaders||""):"",apiMaxTokens:e?Number(n.apiMaxTokens)||m.apiMaxTokens:0,structuredOutputVersion:1}))}function se(r,n,e){return!!r&&r.schemaVersion===K&&r.contentHash===_(n)&&r.settingsHash===ie(e)}function ft(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 yt(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 Ct(r,e){return String(r||"").replace(/\{([a-zA-Z0-9_]+)\}/g,(t,n)=>Object.hasOwn(e,n)?String(e[n]):t)}function bt(r,e,t,n,a,i){return r==="en"?`You are a long-form reading summary assistant. After reading the full document, split it into ${e}-${t} 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 Ct(r,n){return String(r||"").replace(/\{([a-zA-Z0-9_]+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):e)}function bt(r,n,e,t,i,a){return r==="en"?`You are a long-form reading summary assistant. After reading the full document, split it into ${n}-${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. Language: -- ${n} +- ${t} For each unit, output: @@ -45,15 +45,15 @@ Rules: - Output strict JSON only: no markdown fence, no explanation, no tool call. Output shape: -${a} +${i} Example: -${i}`:`\u4F60\u662F\u4E00\u4E2A\u957F\u6587\u9605\u8BFB\u6458\u8981\u52A9\u624B\u3002\u9605\u8BFB\u5168\u6587\u540E\uFF0C\u628A\u6587\u7AE0\u5207\u6210 ${e}-${t} \u4E2A"\u81EA\u7136\u4E3B\u9898\u5355\u5143"\u2014\u2014\u4E0D\u5FC5\u5BF9\u5E94 markdown heading\uFF0C\u4EE5"\u4E00\u4E2A\u5B8C\u6574\u8BBA\u70B9\u6216\u8BDD\u9898"\u4E3A\u5355\u4F4D\u81EA\u884C\u5224\u65AD\u7C92\u5EA6\uFF1A\u77ED\u7AE0\u8282\u5408\u5E76\u3001\u957F\u7AE0\u8282\u62C6\u5206\u3002 +${a}`:`\u4F60\u662F\u4E00\u4E2A\u957F\u6587\u9605\u8BFB\u6458\u8981\u52A9\u624B\u3002\u9605\u8BFB\u5168\u6587\u540E\uFF0C\u628A\u6587\u7AE0\u5207\u6210 ${n}-${e} \u4E2A"\u81EA\u7136\u4E3B\u9898\u5355\u5143"\u2014\u2014\u4E0D\u5FC5\u5BF9\u5E94 markdown heading\uFF0C\u4EE5"\u4E00\u4E2A\u5B8C\u6574\u8BBA\u70B9\u6216\u8BDD\u9898"\u4E3A\u5355\u4F4D\u81EA\u884C\u5224\u65AD\u7C92\u5EA6\uFF1A\u77ED\u7AE0\u8282\u5408\u5E76\u3001\u957F\u7AE0\u8282\u62C6\u5206\u3002 **\u6BCF\u5F20\u5361\u7247\u7684\u7ED3\u6784\uFF1A\u4E00\u53E5\u8BDD\u9886\u8BFB + \u82E5\u5E72\u6761 bullet\u3002bullet \u627F\u8F7D\u7EC6\u8282\uFF0Cgist \u662F\u4E00\u53E5\u8BDD\u5BFC\u8BFB\u3002** \u8BED\u8A00\uFF1A -- ${n} +- ${t} \u5BF9\u6BCF\u4E2A\u5355\u5143\u8F93\u51FA\uFF1A @@ -70,32 +70,32 @@ ${i}`:`\u4F60\u662F\u4E00\u4E2A\u957F\u6587\u9605\u8BFB\u6458\u8981\u52A9\u624B\ - \u4E25\u683C\u53EA\u8F93\u51FA JSON\uFF0C\u65E0 markdown fence\u3001\u65E0\u89E3\u91CA\u3001\u65E0 tool call \u8F93\u51FA\u683C\u5F0F\uFF1A -${a} +${i} \u793A\u4F8B\uFF1A -${i}`}function wt(r,e,t,n,a){return r==="en"?`Non-overridable output contract: -- Must output ${e}-${t} cards. -- ${n} +${a}`}function wt(r,n,e,t,i){return r==="en"?`Non-overridable output contract: +- Must output ${n}-${e} cards. +- ${t} - anchor must be copied verbatim from the source and exact-substring-match the source. - Output strict JSON only: no markdown fence, no explanation, no tool call. -- JSON shape: ${a}`:`\u4E0D\u53EF\u8986\u76D6\u7684\u8F93\u51FA\u5951\u7EA6\uFF1A -- \u5FC5\u987B\u8F93\u51FA ${e}-${t} \u5F20 cards\u3002 -- ${n} +- JSON shape: ${i}`:`\u4E0D\u53EF\u8986\u76D6\u7684\u8F93\u51FA\u5951\u7EA6\uFF1A +- \u5FC5\u987B\u8F93\u51FA ${n}-${e} \u5F20 cards\u3002 +- ${t} - 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: ${a}`}function Me(r,e){let t=Number(e.maxDocChars)||Pe,n=$[e.promptLanguage]?e.promptLanguage:m.promptLanguage,a=Math.max(1,Number(e.minCards)||m.minCards),i=Math.max(a,Number(e.maxCards)||m.maxCards),o=ft(n),s=r.length>t?r.slice(0,t)+(n==="en"?` +- JSON shape: ${i}`}function Me(r,n){let e=Number(n.maxDocChars)||Pe,t=$[n.promptLanguage]?n.promptLanguage:m.promptLanguage,i=Math.max(1,Number(n.minCards)||m.minCards),a=Math.max(i,Number(n.maxCards)||m.maxCards),s=ft(t),o=r.length>e?r.slice(0,e)+(t==="en"?` [Document truncated]`:` -[\u6587\u6863\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]`):r,l='{"cards":[{"title":"...","anchor":"...","gist":"...","bullets":["...","..."]}]}',d=yt(n),g={minCards:a,maxCards:i,languageInstruction:o,schema:l,example:d},y=Ct(e.customSystemPrompt,g).trim(),f=wt(n,a,i,o,l),h=bt(n,a,i,o,l,d),c=y?`${y} +[\u6587\u6863\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]`):r,l='{"cards":[{"title":"...","anchor":"...","gist":"...","bullets":["...","..."]}]}',f=yt(t),p={minCards:i,maxCards:a,languageInstruction:s,schema:l,example:f},d=Ct(n.customSystemPrompt,p).trim(),b=wt(t,i,a,s,l),y=bt(t,i,a,s,l,f),c=d?`${d} -${f}`:h,N=n==="en"?`Source document: +${b}`:y,g=t==="en"?`Source document: -${s}`:`\u4EE5\u4E0B\u662F\u9700\u8981\u5904\u7406\u7684\u6587\u6863\u5168\u6587\uFF1A +${o}`:`\u4EE5\u4E0B\u662F\u9700\u8981\u5904\u7406\u7684\u6587\u6863\u5168\u6587\uFF1A -${s}`;return{system:c,user:N}}function De(r,e){let t=r.replace(/\/+$/,"");for(let n of e)if(t.endsWith(n))return t;return t+e[0]}function vt(r,e){let t=(r||"").trim();if(!t)return{};if(t.startsWith("{")){let a;try{a=JSON.parse(t)}catch(o){throw new Error(C(e||null,"errorCustomHeadersJsonParse",{error:o.message}))}if(!a||typeof a!="object"||Array.isArray(a))throw new Error(C(e||null,"errorCustomHeadersJsonObject"));let i={};for(let[o,s]of Object.entries(a))typeof s=="string"&&o.trim()&&(i[o.trim()]=s);return i}let n={};for(let a of t.split(/\r?\n/)){let i=a.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf(":");if(o<=0)throw new Error(C(e||null,"errorCustomHeadersLineFormat"));let s=i.slice(0,o).trim(),l=i.slice(o+1).trim();s&&(n[s]=l)}return n}function At(r){let e=Ee(r);if(e==="none")return{};let t=Qe(r);if(!t){let n=(r.apiKeyEnvVar||b(r).envVar||"").trim(),a=n?C(r,"errorApiKeyEnvHint",{envVar:n}):"";throw new Error(C(r,"errorApiKeyMissing",{hint:a}))}return e==="bearer"?{authorization:`Bearer ${t}`}:e==="x-api-key"?{"x-api-key":t}:e==="x-goog-api-key"?{"x-goog-api-key":t}:e==="api-key"?{"api-key":t}:{authorization:`Bearer ${t}`}}function de(r,e){return{"content-type":"application/json",...At(r),...e||{},...vt(r.apiHeaders,r)}}function xt(r,e,t){if(r.json&&typeof r.json=="object")return r.json;try{return JSON.parse(r.text||"{}")}catch{throw new Error(C(t||null,"errorProviderNonJson",{label:e,excerpt:(r.text||"").slice(0,500)}))}}async function tt(r,e,t,n,a,i){let o;try{o=await r({url:t,method:"POST",headers:n,body:JSON.stringify(a),throw:!1})}catch(s){throw new Error(C(i||null,"errorProviderRequestFailed",{label:e,error:s.message||s}))}if(o.status>=400)throw new Error(C(i||null,"errorProviderApiStatus",{label:e,status:o.status,excerpt:(o.text||"").slice(0,500)}));return xt(o,e,i)}function Pt(r){let e=String(r?.message?r.message:r);return/(?:API (?:400|404|422):|API returned HTTP (?:400|404|422)|API 返回 HTTP (?:400|404|422))/.test(e)?/response_format|json_schema|responseJsonSchema|responseMimeType|tools?|tool_choice|unsupported|unrecognized|unknown|schema/i.test(e):!1}async function pe(r,e,t,n,a,i,o){try{return await tt(r,e,t,n,a,o)}catch(s){if(!i||!Pt(s))throw s;return console.warn(`[parallel-reader] ${e} structured output rejected; retrying without structured output`,s),tt(r,e+" fallback",t,n,i,o)}}function Ie(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&(e.text||e.output_text)||"").join(""):r&&typeof r=="object"&&(r.text||r.output_text)||""}function Tt(r){if(typeof r.output_text=="string")return r.output_text;let e=[],t=n=>{if(n&&typeof n!="string"){if(Array.isArray(n)){n.forEach(t);return}typeof n=="object"&&(typeof n.text=="string"&&e.push(n.text),typeof n.output_text=="string"&&e.push(n.output_text),n.type==="output_text"&&typeof n.content=="string"&&e.push(n.content),n.content&&t(n.content),n.output&&t(n.output))}};return t(r.output),e.join("")}function Re(r){let e=b(r),t=A[P(r)];return e.tokenLimitField||t?.tokenLimitField||"max_tokens"}function oe(r,e,t,n){let a=!n||n.structured!==!1,i={model:I(t),max_tokens:Number(t.apiMaxTokens)||4096,system:r,messages:[{role:"user",content:e}]};return a&&(i.tools=[Je()],i.tool_choice={type:"tool",name:te}),i}function le(r,e,t,n){let a=!n||n.structured!==!1,i={model:I(t),messages:[{role:"system",content:r},{role:"user",content:e}]};return i[Re(t)]=Number(t.apiMaxTokens)||4096,a&&(i.response_format=je()),i}function ce(r,e,t,n){let a=!n||n.structured!==!1,i={model:I(t),instructions:r,input:e,max_output_tokens:Number(t.apiMaxTokens)||4096};return a&&(i.text=Ge()),i}function ue(r,e,t,n){let a=!n||n.structured!==!1,i={temperature:0,maxOutputTokens:Number(t.apiMaxTokens)||4096};return a&&(i.responseMimeType="application/json",i.responseJsonSchema=j(!1)),{systemInstruction:{parts:[{text:r}]},contents:[{role:"user",parts:[{text:e}]}],generationConfig:i}}function St(r,e){let n=(Array.isArray(r?.content)?r.content:[]).find(a=>a&&a.type==="tool_use"&&a.name===te);return n?typeof n.input=="string"?S(n.input,e):n.input&&typeof n.input=="object"?H(n.input):[]:null}async function Et(r,e,t,n){let a=De(D(n),["/messages"]),i=await pe(r,"Anthropic-compatible",a,de(n,{"anthropic-version":"2023-06-01"}),oe(e,t,n),oe(e,t,n,{structured:!1}),n),o=St(i,n);if(o)return o;let s=(i.content||[]).map(l=>Ie(l)).join("").trim();return S(s,n)}async function Ft(r,e,t,n){let a=De(D(n),["/chat/completions"]),o=((await pe(r,"OpenAI-compatible Chat",a,de(n),le(e,t,n),le(e,t,n,{structured:!1}),n)).choices||[])[0]||{},s=Ie(o.message?.content||o.text||"").trim();return S(s,n)}async function kt(r,e,t,n){let a=De(D(n),["/responses"]),i=await pe(r,"OpenAI Responses",a,de(n),ce(e,t,n),ce(e,t,n,{structured:!1}),n);return S(Tt(i).trim(),n)}async function Nt(r,e,t,n){let a=encodeURIComponent(I(n)),i=D(n);/:generateContent(?:\?|$)/.test(i)||(i=`${i.replace(/\/+$/,"")}/models/${a}:generateContent`);let o=de(n),g=((((await pe(r,"Google Gemini",i,o,ue(e,t,n),ue(e,t,n,{structured:!1}),n)).candidates||[])[0]||{}).content?.parts||[]).map(y=>Ie(y)).join("").trim();return S(g,n)}async function z(r,e,t,n){switch(P(n)){case"openai-chat":return Ft(r,e,t,n);case"openai-responses":return kt(r,e,t,n);case"google-generative-ai":return Nt(r,e,t,n);default:return Et(r,e,t,n)}}async function rt(r,e){await z(r,'\u53EA\u8F93\u51FA JSON\uFF1A{"cards":[]}','\u8FDE\u901A\u6027\u6D4B\u8BD5\uFF1A\u8BF7\u539F\u6837\u8F93\u51FA {"cards":[]}',e);let t=P(e);return`${b(e).label} / ${A[t].label}`}function Le(r,e=80,t=.1){let n=Number(r?.top)||0,a=Math.max(0,Number(r?.height)||0),i=Math.min(Number(e)||0,a*t);return n+Math.max(0,i)}function Mt(r){return typeof requestAnimationFrame=="function"?requestAnimationFrame(r):setTimeout(()=>r(Date.now()),16)}function Dt(r){if(typeof cancelAnimationFrame=="function"){cancelAnimationFrame(r);return}clearTimeout(r)}function Oe(r,e=Mt,t=Dt){let n=null,a=()=>{n===null&&(n=e(()=>{n=null,r()}))};return a.cancel=()=>{n!==null&&(t(n),n=null)},a}var p=require("obsidian");async function It(r){if(r.backend==="codex"){let e=M("codex",r.cliPath),{stdout:t}=await G(e,["--version"],"",1e4);return`codex @ ${e} -${t.trim()}`}if(r.backend==="claude-code"){let e=M("claude",r.cliPath),{stdout:t}=await G(e,["--version"],"",1e4);return`claude @ ${e} -${t.trim()}`}if(B(r.backend))return rt(p.requestUrl,r);throw new Error("Unknown backend: "+r.backend)}var he=class extends p.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this,t=(i,o)=>this.plugin.t(i,o);e.empty(),e.createEl("h2",{text:t("settingsTitle")}),new p.Setting(e).setName(t("settingUiLanguageName")).setDesc(t("settingUiLanguageDesc")).addDropdown(i=>{for(let[o,s]of Object.entries(Te))i.addOption(o,s);return i.setValue(this.plugin.settings.uiLanguage||m.uiLanguage).onChange(async o=>{this.plugin.settings.uiLanguage=o,await this.plugin.saveSettings(),this.display()})}),new p.Setting(e).setName(t("settingBackendName")).setDesc(t("settingBackendDesc")).addDropdown(i=>i.addOption("claude-code","Claude Code CLI").addOption("codex","Codex CLI").addOption("api","API / Provider").addOption("anthropic-api","Anthropic API (legacy)").setValue(this.plugin.settings.backend).onChange(async o=>{this.plugin.settings.backend=o,o==="api"&&!this.plugin.settings.apiBaseUrl&&Fe(this.plugin.settings,this.plugin.settings.apiProvider||"anthropic"),await this.plugin.saveSettings(),this.display()}));let n=B(this.plugin.settings.backend);if(!n)new p.Setting(e).setName(t("settingCliPathName")).setDesc(t("settingCliPathDesc")).addText(i=>i.setPlaceholder(t("settingCliPathPlaceholder")).setValue(this.plugin.settings.cliPath).onChange(async o=>{this.plugin.settings.cliPath=o.trim(),this.plugin.saveSettingsDebounced()})),new p.Setting(e).setName(t("settingCliTimeoutName")).addText(i=>i.setValue(String(this.plugin.settings.cliTimeoutMs)).onChange(async o=>{let s=parseInt(o,10);!Number.isNaN(s)&&s>0&&(this.plugin.settings.cliTimeoutMs=s,this.plugin.saveSettingsDebounced())}));else{e.createEl("h3",{text:t("apiProviderHeader")});let i=b(this.plugin.settings);new p.Setting(e).setName(t("settingProviderPresetName")).setDesc(t("settingProviderPresetDesc")).addDropdown(o=>{for(let[s,l]of Object.entries(E))o.addOption(s,l.label);return o.setValue(this.plugin.settings.apiProvider).onChange(async s=>{Fe(this.plugin.settings,s),await this.plugin.saveSettings(),this.display()})}),new p.Setting(e).setName(t("settingApiFormatName")).setDesc(t("settingApiFormatDesc")).addDropdown(o=>{for(let[s,l]of Object.entries(A))o.addOption(s,l.label);return o.setValue(P(this.plugin.settings)).onChange(async s=>{this.plugin.settings.apiFormat=s,await this.plugin.saveSettings(),this.display()})}),new p.Setting(e).setName(t("settingBaseUrlName")).setDesc(t("settingBaseUrlDesc")).addText(o=>o.setPlaceholder((this.plugin.settings.apiProvider||"").startsWith("custom-")?"https://your-provider.example/v1":i.baseUrl||A[P(this.plugin.settings)].defaultBaseUrl).setValue(this.plugin.settings.apiBaseUrl).onChange(async s=>{this.plugin.settings.apiBaseUrl=s.trim(),this.plugin.saveSettingsDebounced()})),new p.Setting(e).setName(t("settingApiKeyName")).setDesc(t("settingApiKeyDesc")).addText(o=>(o.inputEl.type="password",o.setPlaceholder("sk-...").setValue(this.plugin.settings.apiKey).onChange(async s=>{this.plugin.settings.apiKey=s.trim(),this.plugin.saveSettingsDebounced()}))),new p.Setting(e).setName(t("settingApiKeyEnvName")).setDesc(t("settingApiKeyEnvDesc")).addText(o=>o.setPlaceholder(i.envVar||"OPENAI_API_KEY").setValue(this.plugin.settings.apiKeyEnvVar).onChange(async s=>{this.plugin.settings.apiKeyEnvVar=s.trim(),this.plugin.saveSettingsDebounced()})),new p.Setting(e).setName(t("settingAuthTypeName")).setDesc(t("settingAuthTypeDesc")).addDropdown(o=>{for(let[s,l]of Object.entries(Se))o.addOption(s,l);return o.setValue(this.plugin.settings.apiAuthType||"auto").onChange(async s=>{this.plugin.settings.apiAuthType=s,await this.plugin.saveSettings()})}),new p.Setting(e).setName(t("settingHeadersName")).setDesc(t("settingHeadersDesc")).addTextArea(o=>o.setPlaceholder("cf-aig-authorization: Bearer ...").setValue(this.plugin.settings.apiHeaders).onChange(async s=>{this.plugin.settings.apiHeaders=s,this.plugin.saveSettingsDebounced()})),new p.Setting(e).setName(t("settingMaxTokensName")).addText(o=>o.setValue(String(this.plugin.settings.apiMaxTokens)).onChange(async s=>{let l=parseInt(s,10);!Number.isNaN(l)&&l>0&&(this.plugin.settings.apiMaxTokens=l,this.plugin.saveSettingsDebounced())}))}new p.Setting(e).setName(t("settingModelName")).setDesc(t(n?"settingModelDescApi":"settingModelDescCli")).addText(i=>i.setPlaceholder(n?b(this.plugin.settings).model||"model-id":m.model).setValue(this.plugin.settings.model).onChange(async o=>{this.plugin.settings.model=o.trim()||(n?"":m.model),this.plugin.saveSettingsDebounced()})),new p.Setting(e).setName(t("settingMaxInputName")).setDesc(t("settingMaxInputDesc")).addText(i=>i.setValue(String(this.plugin.settings.maxDocChars||m.maxDocChars)).onChange(async o=>{let s=parseInt(o,10);!Number.isNaN(s)&&s>=1e3&&(this.plugin.settings.maxDocChars=s,this.plugin.saveSettingsDebounced())})),e.createEl("h3",{text:t("promptHeader")}),new p.Setting(e).setName(t("settingPromptLanguageName")).setDesc(t("settingPromptLanguageDesc")).addDropdown(i=>{for(let[o,s]of Object.entries($))i.addOption(o,s);return i.setValue(this.plugin.settings.promptLanguage||m.promptLanguage).onChange(async o=>{this.plugin.settings.promptLanguage=o,await this.plugin.saveSettings()})}),new p.Setting(e).setName(t("settingCardRangeName")).setDesc(t("settingCardRangeDesc")).addText(i=>i.setPlaceholder("min").setValue(String(this.plugin.settings.minCards||m.minCards)).onChange(async o=>{let s=parseInt(o,10);!Number.isNaN(s)&&s>0&&(this.plugin.settings.minCards=s,this.plugin.settings.maxCardsi.setPlaceholder("max").setValue(String(this.plugin.settings.maxCards||m.maxCards)).onChange(async o=>{let s=parseInt(o,10);!Number.isNaN(s)&&s>0&&(this.plugin.settings.maxCards=Math.max(s,this.plugin.settings.minCards||m.minCards),this.plugin.saveSettingsDebounced())})),new p.Setting(e).setName(t("settingCustomPromptName")).setDesc(t("settingCustomPromptDesc")).addTextArea(i=>(i.inputEl.rows=8,i.setPlaceholder(t("settingCustomPromptPlaceholder")).setValue(this.plugin.settings.customSystemPrompt||"").onChange(async o=>{this.plugin.settings.customSystemPrompt=o,this.plugin.saveSettingsDebounced()}))),new p.Setting(e).setName(t("settingTestBackendName")).setDesc(t(n?"settingTestBackendDescApi":"settingTestBackendDescCli")).addButton(i=>i.setButtonText("Test").onClick(async()=>{try{let o=await It(this.plugin.settings);new p.Notice(`\u2713 ${o.slice(0,180)}`,8e3)}catch(o){new p.Notice(t("backendTestFailed",{error:o.message}),1e4)}})),new p.Setting(e).setName(t("settingExportFolderName")).setDesc(t("settingExportFolderDesc")).addText(i=>i.setValue(this.plugin.settings.exportFolder).onChange(async o=>{this.plugin.settings.exportFolder=o.trim()||m.exportFolder,this.plugin.saveSettingsDebounced()})),e.createEl("h3",{text:t("cacheHeader")}),new p.Setting(e).setName(t("settingMaxCacheName")).setDesc(t("settingMaxCacheDesc")).addText(i=>{i.setValue(String(this.plugin.settings.maxCacheEntries||V));let o=async()=>{let s=parseInt(i.getValue(),10);if(Number.isFinite(s)&&s>0){this.plugin.settings.maxCacheEntries=s,await this.plugin.saveSettings();let l=await this.plugin.pruneCacheIfNeeded();l.length>0&&new p.Notice(t("cachePruned",{count:l.length})),this.display()}};return i.inputEl.addEventListener("change",o),i.inputEl.addEventListener("keydown",s=>{s.key==="Enter"&&i.inputEl.blur()}),i});let a=Object.keys(this.plugin.cache).length;new p.Setting(e).setName(t("cachedNotesName",{count:a})).setDesc(t("cachedNotesDesc")).addButton(i=>i.setButtonText(t("clearAllCacheButton")).setWarning().onClick(async()=>{let o=Object.keys(this.plugin.cache).length;await this.plugin.cacheClear(),new p.Notice(t("cacheClearedAll",{count:o})),this.display()}))}};var T=require("obsidian");function R(r,e,t,n){let a=r.createEl("button",{cls:"parallel-reader-icon-button",attr:{type:"button","aria-label":t}});return a.title=t,typeof T.setIcon=="function"?(0,T.setIcon)(a,e):a.textContent=t,a.addEventListener("click",async i=>{i.preventDefault(),i.stopPropagation();try{await n()}catch(o){console.error(o),new T.Notice(`${t} failed: `+(o.message||o))}}),a}function F(r,e,t,n,a){let i=r.createEl("button",{cls:a||"parallel-reader-text-button",attr:{type:"button"}});return e&&typeof T.setIcon=="function"&&(0,T.setIcon)(i,e),i.createSpan({text:t}),i.addEventListener("click",async o=>{o.preventDefault(),o.stopPropagation();try{await n()}catch(s){console.error(s),new T.Notice(`${t} failed: `+(s.message||s))}}),i}async function L(r,e){try{await navigator.clipboard.writeText(r),new T.Notice(e)}catch(t){new T.Notice("Copy failed: "+(t.message||t))}}function _e(r){return String(r||"").split("/").map(e=>e.trim()).filter(Boolean).join("/")}function Ve(r){let e=_e(r);if(!e)return[];let t=e.split("/");return t.map((n,a)=>t.slice(0,a+1).join("/"))}async function nt(r,e){for(let t of Ve(e))if(!r.vault.getAbstractFileByPath(t))try{await r.vault.createFolder(t)}catch(n){if(!r.vault.getAbstractFileByPath(t))throw n}}var w=require("obsidian");var at=require("obsidian");var me=class extends at.Modal{constructor(e,t,n,a){super(e),this.plugin=t,this.card=n||{},this.onSave=a}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:this.plugin.t("editCardTitle")});let t=this.createLabeledInput(e,this.plugin.t("editCardTitleField"),this.card.title||""),n=this.createLabeledTextarea(e,this.plugin.t("editCardGistField"),this.card.gist||"",3),a=this.createLabeledTextarea(e,this.plugin.t("editCardBulletsField"),(this.card.bullets||[]).join(` -`),8),i=e.createDiv({cls:"parallel-reader-modal-actions"});F(i,null,this.plugin.t("editCardCancel"),()=>this.close(),"parallel-reader-text-button"),F(i,null,this.plugin.t("editCardSave"),async()=>{await this.onSave({title:t.value.trim()||this.card.title||"",gist:n.value.trim(),bullets:a.value.split(/\r?\n/).map(o=>o.trim()).filter(Boolean)}),this.close()},"parallel-reader-text-button")}createLabeledInput(e,t,n){let a=e.createDiv({cls:"parallel-reader-modal-field"});a.createEl("label",{text:t});let i=a.createEl("input",{attr:{type:"text"}});return i.value=n,i}createLabeledTextarea(e,t,n,a){let i=e.createDiv({cls:"parallel-reader-modal-field"});i.createEl("label",{text:t});let o=i.createEl("textarea");return o.rows=a,o.value=n,o}};var k="parallel-reader-view",ge=class extends w.ItemView{constructor(e,t){super(e),this.plugin=t,this.sections=[],this.sourceFile=null,this.cards=[],this.activeIdx=-1,this.loadingMessage="",this.errorMessage=""}getViewType(){return k}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",t=>this.handleKeydown(t)),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 t=e.createDiv({cls:"parallel-reader-empty"});t.createEl("h3",{text:this.plugin.t("appTitle")}),t.createEl("p",{text:this.plugin.t("emptyOpenNote")}),t.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)}async loadFor(e,t,n){this.sourceFile=e,this.sections=t,this.stale=!!n,this.loadingMessage="",this.errorMessage="",this.render()}async renderLoading(e,t){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage=t||this.plugin.t("loadingDefault"),this.errorMessage="",this.render()}async renderError(e,t){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage=t||this.plugin.t("errorTitle"),this.render()}renderEmptyWithHint(e){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let t=this.containerEl.children[1];t.empty();let n=t.createDiv({cls:"parallel-reader-empty"});n.createEl("h3",{text:e.basename}),n.createEl("p",{text:this.plugin.t("emptyNoCache")}),n.createEl("code",{text:this.plugin.t("commandGenerate")})}render(){let e=this.containerEl.children[1];e.empty();let n=e.createDiv({cls:"parallel-reader-header"}).createDiv({cls:"parallel-reader-header-row"});n.createEl("div",{text:this.sourceFile?.basename||"",cls:"parallel-reader-title"});let a=n.createDiv({cls:"parallel-reader-actions"});if(this.sourceFile&&(this.plugin.isGeneratingFile(this.sourceFile)?R(a,"square",this.plugin.t("actionCancel"),()=>{this.plugin.cancelGenerationForFile(this.sourceFile)}):R(a,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0)),R(a,"copy",this.plugin.t("actionCopyAll"),()=>this.plugin.copyCurrentViewMarkdown()),R(a,"download",this.plugin.t("actionExport"),()=>this.exportToVault())),this.stale){let s=e.createDiv({cls:"parallel-reader-stale-banner"});s.createSpan({text:this.plugin.t("staleBanner")}),F(s,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-stale-button")}if(this.loadingMessage){let s=e.createDiv({cls:"parallel-reader-state parallel-reader-loading"});s.createDiv({cls:"parallel-reader-spinner"}),s.createEl("div",{text:this.loadingMessage,cls:"parallel-reader-state-title"}),s.createEl("div",{text:this.plugin.t("loadingSubtitle"),cls:"parallel-reader-state-subtitle"});return}if(this.errorMessage){let s=e.createDiv({cls:"parallel-reader-state parallel-reader-error"});s.createEl("div",{text:this.plugin.t("errorTitle"),cls:"parallel-reader-state-title"}),s.createEl("div",{text:this.errorMessage,cls:"parallel-reader-state-subtitle"}),F(s,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-text-button");return}let i=e.createDiv({cls:"parallel-reader-cards"});this.cards=[];let o=this.sourceFile?.path||"";this.sections.forEach((s,l)=>{let d=i.createDiv({cls:"parallel-reader-card"});d.dataset.idx=String(l),s.startLine<0&&d.addClass("parallel-reader-card-unanchored");let g=d.createEl("div",{cls:"parallel-reader-card-title"});if(g.createSpan({text:s.title}),s.startLine<0&&g.createEl("span",{text:" \u26A0",cls:"parallel-reader-warn",title:this.plugin.t("anchorMismatch")}),s.gist){let f=d.createEl("div",{cls:"parallel-reader-gist"});w.MarkdownRenderer.render(this.app,s.gist,f,o,this).catch(()=>{f.setText(s.gist)})}let y=s.bullets||[];if(y.length>0){let f=d.createEl("div",{cls:"parallel-reader-bullets-md"}),h=y.map(c=>`- ${c}`).join(` -`);w.MarkdownRenderer.render(this.app,h,f,o,this).catch(()=>{f.setText(h)})}else s.gist||d.createEl("div",{cls:"parallel-reader-empty-li",text:this.plugin.t("emptyCard")});d.addEventListener("click",f=>{let h=window.getSelection();if(h&&h.toString().length>0)return;let c=f.target;c&&c.tagName==="A"||s.startLine>=0&&this.plugin.scrollEditorToLine(s.startLine,this.sourceFile)}),d.addEventListener("contextmenu",f=>{f.preventDefault();let h=new w.Menu;h.addItem(c=>c.setTitle(this.plugin.t("menuCopyMarkdown")).setIcon("copy").onClick(()=>L(Ae(s),this.plugin.t("copiedMarkdown")))),h.addItem(c=>c.setTitle(this.plugin.t("menuCopyPlain")).setIcon("clipboard-copy").onClick(()=>L(We(s),this.plugin.t("copiedPlain")))),s.anchor&&h.addItem(c=>c.setTitle(this.plugin.t("menuCopyAnchor")).setIcon("quote-glyph").onClick(()=>L(s.anchor,this.plugin.t("copiedAnchor")))),h.addSeparator(),s.startLine>=0&&h.addItem(c=>c.setTitle(this.plugin.t("menuJumpSource")).setIcon("arrow-right").onClick(()=>this.plugin.scrollEditorToLine(s.startLine,this.sourceFile))),h.addSeparator(),h.addItem(c=>c.setTitle(this.plugin.t("menuEditCard")).setIcon("pencil").onClick(()=>this.openEditCardModal(l))),h.addItem(c=>c.setTitle(this.plugin.t("menuDeleteCard")).setIcon("trash").onClick(()=>this.deleteCard(l))),h.showAtMouseEvent(f)}),this.cards.push(d)}),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 t=ne(this.activeIdx,this.sections.length,e);return this.setActiveSection(t),this.focusSummaryPane(),t}jumpToActiveSection(){let e=ae(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 t=X(this.sections,e);if(t.length===this.sections.length)return!1;let n=this.sections.length;return this.sections=t,this.activeIdx=Z(e,n,this.activeIdx),await this.plugin.cacheReplaceCards(this.sourceFile.path,t),this.render(),new w.Notice(this.plugin.t("cardDeleted")),!0}openEditCardModal(e){return!this.sourceFile||!this.sections[e]?!1:(new me(this.app,this.plugin,this.sections[e],async t=>{await this.updateCard(e,t)}).open(),!0)}async updateCard(e,t){if(!this.sourceFile)return!1;let n=Q(this.sections,e,t);return n.length!==this.sections.length?!1:(this.sections=n,await this.plugin.cacheReplaceCards(this.sourceFile.path,n),this.render(),new w.Notice(this.plugin.t("cardSaved")),!0)}async exportToVault(){if(!this.sourceFile)return;let e=_e(this.plugin.settings.exportFolder),t=`${this.sourceFile.basename} - ${this.plugin.t("displayName")}.md`,n=`${e}/${t}`,a=["---",`source: [[${this.sourceFile.basename}]]`,`generated: ${new Date().toISOString().slice(0,10)}`,"tool: parallel-reader","---","",J(`${this.sourceFile.basename} \xB7 ${this.plugin.t("displayName")}`,this.sections),""].join(` -`),i=this.plugin.app;await nt(i,e);let o=i.vault.getAbstractFileByPath(n);o instanceof w.TFile?await i.vault.modify(o,a):await i.vault.create(n,a),new w.Notice(this.plugin.t("exported",{path:n}))}};async function Rt(r,e,t){let{system:n,user:a}=Me(r,e),i;switch(e.backend){case"codex":i=await qe(n,a,e,t);break;case"api":i=await z(u.requestUrl,n,a,e);break;case"anthropic-api":i=await z(u.requestUrl,n,a,e);break;default:i=await ze(n,a,e,t);break}let o=i.map(s=>({title:s.title,level:2,anchor:s.anchor,gist:s.gist,startLine:Y(r,s.anchor),bullets:s.bullets}));return o.sort((s,l)=>s.startLine<0&&l.startLine<0?0:s.startLine<0?1:l.startLine<0?-1:s.startLine-l.startLine),o}function it(r,e){return e?.phase==="generating"&&r&&B(r.backend)?"cancelRequestedApiInFlight":"cancelRequested"}var Be=class extends u.Plugin{t(e,t){return C(this.settings||m,e,t)}async onload(){await this.loadSettings(),this.jobs=new U,this._cacheSaveTimer=null,this._cacheDirty=!1,this.addRibbonIcon("book-open",this.t("ribbonOpen"),async()=>{let e=this.getActiveView();await this.ensureView(),e?.file&&await this.syncViewToFile(e.file)}),this.registerView(k,e=>new ge(e,this)),this.addCommand({id:"parallel-reader-run",name:this.t("cmdRun"),callback:()=>this.runForActiveFile(!1)}),this.addCommand({id:"parallel-reader-regen",name:this.t("cmdRegen"),callback:()=>this.runForActiveFile(!0)}),this.addCommand({id:"parallel-reader-open-view",name:this.t("cmdOpenView"),callback:async()=>{let e=this.getActiveView();await this.ensureView(),e?.file&&this.syncViewToFile(e.file)}}),this.addCommand({id:"parallel-reader-export-current",name:this.t("cmdExport"),callback:()=>this.exportCurrentView()}),this.addCommand({id:"parallel-reader-copy-current-markdown",name:this.t("cmdCopyMarkdown"),callback:()=>this.copyCurrentViewMarkdown()}),this.addCommand({id:"parallel-reader-cancel-current",name:this.t("cmdCancel"),callback:()=>this.cancelActiveGeneration()}),this.addCommand({id:"parallel-reader-clear-current",name:this.t("cmdClearCurrent"),callback:async()=>{let e=this.getActiveView();if(!e?.file)return new u.Notice(this.t("noCurrentNote"));await this.cacheDelete(e.file.path),new u.Notice(this.t("cacheClearedFile",{name:e.file.basename}))}}),this.addCommand({id:"parallel-reader-clear-all",name:this.t("cmdClearAll"),callback:async()=>{let e=Object.keys(this.cache).length;await this.cacheClear(),new u.Notice(this.t("cacheClearedAll",{count:e}))}}),this.addCommand({id:"parallel-reader-card-prev",name:this.t("cmdCardPrev"),hotkeys:[{modifiers:["Alt"],key:"ArrowUp"}],callback:()=>this.moveActiveCard(-1)}),this.addCommand({id:"parallel-reader-card-next",name:this.t("cmdCardNext"),hotkeys:[{modifiers:["Alt"],key:"ArrowDown"}],callback:()=>this.moveActiveCard(1)}),this.addCommand({id:"parallel-reader-card-jump",name:this.t("cmdCardJump"),callback:()=>this.jumpActiveCard()}),this.addSettingTab(new he(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,t)=>this.addFileMenuItems(e,t))),this.registerEvent(this.app.vault.on("rename",(e,t)=>this.handleFileRename(e,t))),this.registerEvent(this.app.vault.on("delete",e=>this.handleFileDelete(e))),this.bindScrollSync()}async onunload(){await this.flushSettingsSave(),await this.flushCacheSave(),this.app.workspace.detachLeavesOfType(k)}async loadSettings(){let t=(await this.loadData()||{}).settings||{};this.settings=ke(Object.assign({},m,t)),await this.loadCache()}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(t=>console.error("[parallel-reader] failed to save settings",t))},e)}async flushSettingsSave(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null,await this.saveSettings())}async saveCache(){this._cacheSaveTimer&&(clearTimeout(this._cacheSaveTimer),this._cacheSaveTimer=null),this.pruneCache(),await this.writeCacheFile(),this._cacheDirty=!1}scheduleCacheSave(e=5e3){this._cacheDirty=!0,!this._cacheSaveTimer&&(this._cacheSaveTimer=setTimeout(()=>{this._cacheSaveTimer=null,this._cacheDirty&&this.saveCache().catch(t=>console.error("[parallel-reader] failed to save cache",t))},e))}async flushCacheSave(){this._cacheSaveTimer&&(clearTimeout(this._cacheSaveTimer),this._cacheSaveTimer=null),this._cacheDirty&&await this.saveCache()}cacheFilePath(){let e=this.app.vault.configDir||".obsidian",t=this.manifest?.id||"parallel-reader";return`${e}/plugins/${t}/cache.json`}async ensurePluginDataDir(){let e=this.app.vault.adapter,t=this.app.vault.configDir||".obsidian",n=this.manifest?.id||"parallel-reader",a=`${t}/plugins/${n}`;try{if(typeof e.exists=="function"&&await e.exists(a))return;await e.mkdir(a)}catch{}}async readCacheFile(){let e=this.app.vault.adapter;try{let t=await e.read(this.cacheFilePath()),n=JSON.parse(t);if(n&&typeof n=="object"&&n.entries&&typeof n.entries=="object")return n.entries}catch(t){let n=String(t?.message||t||"");/not found|does not exist|ENOENT/i.test(n)||console.warn("[parallel-reader] failed to read cache.json",t)}return{}}async writeCacheFile(){await this.ensurePluginDataDir(),await this.app.vault.adapter.write(this.cacheFilePath(),ye(this.cache))}async loadCache(){this.cache=await this.readCacheFile(),this.pruneCache().length>0&&await this.writeCacheFile()}pruneCache(){return Ne(this.cache,this.settings?.maxCacheEntries||V)}async pruneCacheIfNeeded(){let e=this.pruneCache();return e.length>0&&await this.saveCache(),e}cacheGet(e){return this.cache[e]||null}async cacheTouch(e){let t=fe(this.cache[e]||null);return t?(this.scheduleCacheSave(),t):null}async cachePut(e,t,n,a){let i=new Date().toISOString();this.cache[e]={schemaVersion:K,contentHash:_(t),settingsHash:ie(a||this.settings),cards:n,generatedAt:i,lastAccessedAt:i},await this.saveCache()}async cacheReplaceCards(e,t){let n=this.cache[e];if(!n)return!1;let a=new Date().toISOString();return n.cards=(t||[]).map(i=>({title:i.title,anchor:i.anchor,gist:i.gist,bullets:i.bullets||[]})),n.updatedAt=a,n.lastAccessedAt=a,await this.saveCache(),!0}async cacheDelete(e){this.cache[e]&&(delete this.cache[e],await this.saveCache())}async cacheClear(){this.cache={},await this.saveCache()}async ensureView(){let{workspace:e}=this.app,t=e.getLeavesOfType(k)[0];return t||(t=e.getRightLeaf(!1),await t.setViewState({type:k,active:!0})),e.revealLeaf(t),t.view}getActiveView(){return this.app.workspace.getActiveViewOfType(u.MarkdownView)}getParallelView(){return this.app.workspace.getLeavesOfType(k)[0]?.view}moveActiveCard(e){let t=this.getParallelView();return t?.sections.length?t.moveActiveSection(e):(new u.Notice(this.t("noActiveCard")),-1)}jumpActiveCard(){let e=this.getParallelView();return!e||e.jumpToActiveSection()<0?(new u.Notice(this.t("noActiveCard")),!1):!0}isGeneratingFile(e){return!!e&&!!e.path&&this.jobs.isRunning(e.path)}cancelGenerationForFile(e){if(!e?.path)return new u.Notice(this.t("noCancelableJob")),!1;let t=this.jobs.get(e.path),n=it(this.settings,t),a=this.jobs.cancel(e.path);return new u.Notice(a?this.t(n):this.t("noCancelableJob")),a}viewIsShowingFile(e,t){return!!e&&!!t&&e.sourceFile?.path===t.path}activeFileStillMatches(e){let t=this.getActiveView();return!t?.file||t.file.path===e.path}cancelActiveGeneration(){let e=this.getActiveView();if(e?.file&&this.cancelGenerationForFile(e.file))return;let t=this.getParallelView();t?.sourceFile?this.cancelGenerationForFile(t.sourceFile):new u.Notice(this.t("noCancelableJob"))}confirmRegenerateEditedCards(){let e=this.t("confirmRegenerateEditedCards");return typeof window<"u"&&typeof window.confirm=="function"?window.confirm(e):!0}addFileMenuItems(e,t){!(t instanceof u.TFile)||!t.path.endsWith(".md")||(e.addSeparator(),e.addItem(n=>n.setTitle(this.t("fileMenuGenerate")).setIcon("book-open").onClick(()=>this.runForFile(t,!1))),e.addItem(n=>n.setTitle(this.t("fileMenuRegen")).setIcon("refresh-cw").onClick(()=>this.runForFile(t,!0))),this.cacheGet(t.path)&&e.addItem(n=>n.setTitle(this.t("fileMenuClear")).setIcon("trash").onClick(async()=>{await this.cacheDelete(t.path),new u.Notice(this.t("cacheClearedFile",{name:t.basename}))})))}async handleFileRename(e,t){if(!(e instanceof u.TFile)||!t)return;let n=t.endsWith(".md"),a=e.path.endsWith(".md");if(!n&&!a)return;if(n&&!a){this.cache[t]&&(delete this.cache[t],await this.saveCache());let o=this.getParallelView();o&&o.sourceFile?.path===t&&o.renderEmpty();return}if(!n)return;this.cache[t]&&(this.cache[e.path]=this.cache[t],delete this.cache[t],await this.saveCache());let i=this.getParallelView();i?.sourceFile&&(i.sourceFile.path===t||i.sourceFile.path===e.path)&&(i.sourceFile=e,await this.syncViewToFile(e))}async handleFileDelete(e){if(!(e instanceof u.TFile))return;this.cache[e.path]&&(delete this.cache[e.path],await this.saveCache());let t=this.getParallelView();t?.sourceFile?.path===e.path&&t.renderEmpty()}async exportCurrentView(){let e=this.getActiveView(),t=await this.ensureView();if((!t.sourceFile||!t.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!t.sourceFile||!t.sections.length){new u.Notice(this.t("noExportContent"));return}await t.exportToVault()}async copyCurrentViewMarkdown(){let e=this.getActiveView(),t=await this.ensureView();if((!t.sourceFile||!t.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!t.sourceFile||!t.sections.length){new u.Notice(this.t("noCopyContent"));return}await L(J(`${t.sourceFile.basename} \xB7 ${this.t("displayName")}`,t.sections),this.t("copiedAllMarkdown"))}async runForActiveFile(e){let t=this.getActiveView();if(!t?.file){new u.Notice(this.t("openNoteFirst"));return}return this.runForFile(t.file,e)}async runForFile(e,t){if(!e){new u.Notice(this.t("openNoteFirst"));return}if(this.jobs.isRunning(e.path)){new u.Notice(this.t("alreadyGenerating"));return}if(Ce(this.cacheGet(e.path),t)&&!this.confirmRegenerateEditedCards()){new u.Notice(this.t("regenerateCancelled"));return}let n=null;return this.jobs.start(e.path,async a=>{a.setPhase("reading");let i=await this.app.vault.read(e);if(a.throwIfCancelled(),!i.trim()){new u.Notice(this.t("emptyNote"));return}if(n=await this.ensureView(),a.throwIfCancelled(),a.setPhase("cache-check"),!t){let g=this.cacheGet(e.path);if(se(g,i,this.settings)){await this.cacheTouch(e.path),this.activeFileStillMatches(e)&&await n.loadFor(e,this.resolveCardAnchors(i,g.cards),!1);return}}await n.renderLoading(e,this.t("loadingGenerating"));let o=Number(this.settings.maxDocChars)||m.maxDocChars;i.length>o&&new u.Notice(this.t("longNoteTruncated",{count:o})),new u.Notice(this.t("generatingNotice")),a.setPhase("generating");let s=await Rt(i,this.settings,a);if(a.throwIfCancelled(),s.length===0){new u.Notice(this.t("noCardsReturned"));return}let l=s.map(g=>({title:g.title,anchor:g.anchor,gist:g.gist,bullets:g.bullets}));a.setPhase("saving"),await this.cachePut(e.path,i,l,this.settings),a.throwIfCancelled(),this.viewIsShowingFile(n,e)&&await n.loadFor(e,s,!1);let d=s.filter(g=>g.startLine<0).length;new u.Notice(this.t("generationDone",{count:s.length,suffix:d?this.t("unanchoredSuffix",{count:d}):""}))}).catch(async a=>{if(a instanceof O){new u.Notice(a.message);return}if(a instanceof v){n&&this.viewIsShowingFile(n,e)&&await n.renderError(e,this.t("cancelledError")),new u.Notice(this.t("cancelled"));return}let i=we(a);console.error(a),n&&this.viewIsShowingFile(n,e)&&await n.renderError(e,a.message||String(a)),new u.Notice(this.t("generationFailed",{kind:i==="unknown"?"":` (${i})`,error:a.message||a}))})}resolveCardAnchors(e,t){let n=(t||[]).map(a=>({title:a.title,level:2,anchor:a.anchor,gist:a.gist,startLine:Y(e,a.anchor),bullets:a.bullets||[]}));return n.sort((a,i)=>a.startLine<0&&i.startLine<0?0:a.startLine<0?1:i.startLine<0?-1:a.startLine-i.startLine),n}async syncViewToFile(e){if(!e?.path?.endsWith(".md"))return;let t=this.app.workspace.getLeavesOfType(k);if(t.length===0)return;let n=t[0].view;if(!n||!this.activeFileStillMatches(e))return;let a=this.cacheGet(e.path);if(!a){await n.loadFor(e,[],!1),n.renderEmptyWithHint(e);return}let i=await this.app.vault.read(e);if(!this.activeFileStillMatches(e))return;let o=!se(a,i,this.settings);await this.cacheTouch(e.path),await n.loadFor(e,this.resolveCardAnchors(i,a.cards),o)}bindScrollSync(){this._scrollDispose&&(this._scrollDispose(),this._scrollDispose=null);let e=this.getActiveView();if(!e)return;let t=e.editor,n=t&&t.cm,a=n?.scrollDOM?n.scrollDOM:e.contentEl.querySelector(".cm-scroller");if(!a)return;let i=Oe(()=>this.handleEditorScroll(e));a.addEventListener("scroll",i,{passive:!0}),this._scrollDispose=()=>{i.cancel(),a.removeEventListener("scroll",i)}}handleEditorScroll(e){let t=this.getParallelView();if(!t||!e.file||t.sourceFile?.path!==e.file.path)return;let n=e.editor,a=n&&n.cm;if(!a?.scrollDOM)return;let i=a.scrollDOM.getBoundingClientRect(),o=Le(i),s=0;try{let d=a.posAtCoords({x:i.left+20,y:o});d!=null&&(s=a.state.doc.lineAt(d).number-1)}catch{return}let l=-1;for(let d=0;d=400)throw new Error(C(a||null,"errorProviderApiStatus",{label:n,status:s.status,excerpt:(s.text||"").slice(0,500)}));return xt(s,n,a)}function Pt(r){let n=String(r?.message?r.message:r);return/(?:API (?:400|404|422):|API returned HTTP (?:400|404|422)|API 返回 HTTP (?:400|404|422))/.test(n)?/response_format|json_schema|responseJsonSchema|responseMimeType|tools?|tool_choice|unsupported|unrecognized|unknown|schema/i.test(n):!1}async function pe(r,n,e,t,i,a,s){try{return await tt(r,n,e,t,i,s)}catch(o){if(!a||!Pt(o))throw o;return console.warn(`[parallel-reader] ${n} structured output rejected; retrying without structured output`,o),tt(r,n+" fallback",e,t,a,s)}}function Ie(r){return typeof r=="string"?r:Array.isArray(r)?r.map(n=>typeof n=="string"?n:n&&typeof n=="object"&&(n.text||n.output_text)||"").join(""):r&&typeof r=="object"&&(r.text||r.output_text)||""}function Tt(r){if(typeof r.output_text=="string")return r.output_text;let n=[],e=t=>{if(t&&typeof t!="string"){if(Array.isArray(t)){t.forEach(e);return}typeof t=="object"&&(typeof t.text=="string"&&n.push(t.text),typeof t.output_text=="string"&&n.push(t.output_text),t.type==="output_text"&&typeof t.content=="string"&&n.push(t.content),t.content&&e(t.content),t.output&&e(t.output))}};return e(r.output),n.join("")}function Re(r){let n=w(r),e=x[T(r)];return n.tokenLimitField||e?.tokenLimitField||"max_tokens"}function oe(r,n,e,t){let i=!t||t.structured!==!1,a={model:I(e),max_tokens:Number(e.apiMaxTokens)||4096,system:r,messages:[{role:"user",content:n}]};return i&&(a.tools=[Je()],a.tool_choice={type:"tool",name:te}),a}function le(r,n,e,t){let i=!t||t.structured!==!1,a={model:I(e),messages:[{role:"system",content:r},{role:"user",content:n}]};return a[Re(e)]=Number(e.apiMaxTokens)||4096,i&&(a.response_format=je()),a}function ce(r,n,e,t){let i=!t||t.structured!==!1,a={model:I(e),instructions:r,input:n,max_output_tokens:Number(e.apiMaxTokens)||4096};return i&&(a.text=Ge()),a}function ue(r,n,e,t){let i=!t||t.structured!==!1,a={temperature:0,maxOutputTokens:Number(e.apiMaxTokens)||4096};return i&&(a.responseMimeType="application/json",a.responseJsonSchema=j(!1)),{systemInstruction:{parts:[{text:r}]},contents:[{role:"user",parts:[{text:n}]}],generationConfig:a}}function St(r,n){let t=(Array.isArray(r?.content)?r.content:[]).find(i=>i&&i.type==="tool_use"&&i.name===te);return t?typeof t.input=="string"?E(t.input,n):t.input&&typeof t.input=="object"?H(t.input):[]:null}async function Et(r,n,e,t){let i=De(D(t),["/messages"]),a=await pe(r,"Anthropic-compatible",i,de(t,{"anthropic-version":"2023-06-01"}),oe(n,e,t),oe(n,e,t,{structured:!1}),t),s=St(a,t);if(s)return s;let o=(a.content||[]).map(l=>Ie(l)).join("").trim();return E(o,t)}async function kt(r,n,e,t){let i=De(D(t),["/chat/completions"]),s=((await pe(r,"OpenAI-compatible Chat",i,de(t),le(n,e,t),le(n,e,t,{structured:!1}),t)).choices||[])[0]||{},o=Ie(s.message?.content||s.text||"").trim();return E(o,t)}async function Ft(r,n,e,t){let i=De(D(t),["/responses"]),a=await pe(r,"OpenAI Responses",i,de(t),ce(n,e,t),ce(n,e,t,{structured:!1}),t);return E(Tt(a).trim(),t)}async function Nt(r,n,e,t){let i=encodeURIComponent(I(t)),a=D(t);/:generateContent(?:\?|$)/.test(a)||(a=`${a.replace(/\/+$/,"")}/models/${i}:generateContent`);let s=de(t),p=((((await pe(r,"Google Gemini",a,s,ue(n,e,t),ue(n,e,t,{structured:!1}),t)).candidates||[])[0]||{}).content?.parts||[]).map(d=>Ie(d)).join("").trim();return E(p,t)}async function z(r,n,e,t){switch(T(t)){case"openai-chat":return kt(r,n,e,t);case"openai-responses":return Ft(r,n,e,t);case"google-generative-ai":return Nt(r,n,e,t);default:return Et(r,n,e,t)}}async function rt(r,n){await z(r,'\u53EA\u8F93\u51FA JSON\uFF1A{"cards":[]}','\u8FDE\u901A\u6027\u6D4B\u8BD5\uFF1A\u8BF7\u539F\u6837\u8F93\u51FA {"cards":[]}',n);let e=T(n);return`${w(n).label} / ${x[e].label}`}function Le(r,n=80,e=.1){let t=Number(r?.top)||0,i=Math.max(0,Number(r?.height)||0),a=Math.min(Number(n)||0,i*e);return t+Math.max(0,a)}function Mt(r){return typeof requestAnimationFrame=="function"?requestAnimationFrame(r):setTimeout(()=>r(Date.now()),16)}function Dt(r){if(typeof cancelAnimationFrame=="function"){cancelAnimationFrame(r);return}clearTimeout(r)}function Oe(r,n=Mt,e=Dt){let t=null,i=()=>{t===null&&(t=n(()=>{t=null,r()}))};return i.cancel=()=>{t!==null&&(e(t),t=null)},i}var h=require("obsidian");async function It(r){if(r.backend==="codex"){let n=M("codex",r.cliPath),{stdout:e}=await G(n,["--version"],"",1e4);return`codex @ ${n} +${e.trim()}`}if(r.backend==="claude-code"){let n=M("claude",r.cliPath),{stdout:e}=await G(n,["--version"],"",1e4);return`claude @ ${n} +${e.trim()}`}if(B(r.backend))return rt(h.requestUrl,r);throw new Error("Unknown backend: "+r.backend)}var he=class extends h.PluginSettingTab{constructor(n,e){super(n,e),this.plugin=e}display(){let{containerEl:n}=this,e=(a,s)=>this.plugin.t(a,s);n.empty(),n.createEl("h2",{text:e("settingsTitle")}),new h.Setting(n).setName(e("settingUiLanguageName")).setDesc(e("settingUiLanguageDesc")).addDropdown(a=>{for(let[s,o]of Object.entries(Te))a.addOption(s,o);return a.setValue(this.plugin.settings.uiLanguage||m.uiLanguage).onChange(async s=>{this.plugin.settings.uiLanguage=s,await this.plugin.saveSettings(),this.display()})}),new h.Setting(n).setName(e("settingBackendName")).setDesc(e("settingBackendDesc")).addDropdown(a=>a.addOption("claude-code","Claude Code CLI").addOption("codex","Codex CLI").addOption("api","API / Provider").addOption("anthropic-api","Anthropic API (legacy)").setValue(this.plugin.settings.backend).onChange(async s=>{this.plugin.settings.backend=s,s==="api"&&!this.plugin.settings.apiBaseUrl&&ke(this.plugin.settings,this.plugin.settings.apiProvider||"anthropic"),await this.plugin.saveSettings(),this.display()}));let t=B(this.plugin.settings.backend);if(!t)new h.Setting(n).setName(e("settingCliPathName")).setDesc(e("settingCliPathDesc")).addText(a=>a.setPlaceholder(e("settingCliPathPlaceholder")).setValue(this.plugin.settings.cliPath).onChange(async s=>{this.plugin.settings.cliPath=s.trim(),this.plugin.saveSettingsDebounced()})),new h.Setting(n).setName(e("settingCliTimeoutName")).addText(a=>a.setValue(String(this.plugin.settings.cliTimeoutMs)).onChange(async s=>{let o=parseInt(s,10);!Number.isNaN(o)&&o>0&&(this.plugin.settings.cliTimeoutMs=o,this.plugin.saveSettingsDebounced())}));else{n.createEl("h3",{text:e("apiProviderHeader")});let a=w(this.plugin.settings);new h.Setting(n).setName(e("settingProviderPresetName")).setDesc(e("settingProviderPresetDesc")).addDropdown(s=>{for(let[o,l]of Object.entries(k))s.addOption(o,l.label);return s.setValue(this.plugin.settings.apiProvider).onChange(async o=>{ke(this.plugin.settings,o),await this.plugin.saveSettings(),this.display()})}),new h.Setting(n).setName(e("settingApiFormatName")).setDesc(e("settingApiFormatDesc")).addDropdown(s=>{for(let[o,l]of Object.entries(x))s.addOption(o,l.label);return s.setValue(T(this.plugin.settings)).onChange(async o=>{this.plugin.settings.apiFormat=o,await this.plugin.saveSettings(),this.display()})}),new h.Setting(n).setName(e("settingBaseUrlName")).setDesc(e("settingBaseUrlDesc")).addText(s=>s.setPlaceholder((this.plugin.settings.apiProvider||"").startsWith("custom-")?"https://your-provider.example/v1":a.baseUrl||x[T(this.plugin.settings)].defaultBaseUrl).setValue(this.plugin.settings.apiBaseUrl).onChange(async o=>{this.plugin.settings.apiBaseUrl=o.trim(),this.plugin.saveSettingsDebounced()})),new h.Setting(n).setName(e("settingApiKeyName")).setDesc(e("settingApiKeyDesc")).addText(s=>(s.inputEl.type="password",s.setPlaceholder("sk-...").setValue(this.plugin.settings.apiKey).onChange(async o=>{this.plugin.settings.apiKey=o.trim(),this.plugin.saveSettingsDebounced()}))),new h.Setting(n).setName(e("settingApiKeyEnvName")).setDesc(e("settingApiKeyEnvDesc")).addText(s=>s.setPlaceholder(a.envVar||"OPENAI_API_KEY").setValue(this.plugin.settings.apiKeyEnvVar).onChange(async o=>{this.plugin.settings.apiKeyEnvVar=o.trim(),this.plugin.saveSettingsDebounced()})),new h.Setting(n).setName(e("settingAuthTypeName")).setDesc(e("settingAuthTypeDesc")).addDropdown(s=>{for(let[o,l]of Object.entries(Se))s.addOption(o,l);return s.setValue(this.plugin.settings.apiAuthType||"auto").onChange(async o=>{this.plugin.settings.apiAuthType=o,await this.plugin.saveSettings()})}),new h.Setting(n).setName(e("settingHeadersName")).setDesc(e("settingHeadersDesc")).addTextArea(s=>s.setPlaceholder("cf-aig-authorization: Bearer ...").setValue(this.plugin.settings.apiHeaders).onChange(async o=>{this.plugin.settings.apiHeaders=o,this.plugin.saveSettingsDebounced()})),new h.Setting(n).setName(e("settingMaxTokensName")).addText(s=>s.setValue(String(this.plugin.settings.apiMaxTokens)).onChange(async o=>{let l=parseInt(o,10);!Number.isNaN(l)&&l>0&&(this.plugin.settings.apiMaxTokens=l,this.plugin.saveSettingsDebounced())}))}new h.Setting(n).setName(e("settingModelName")).setDesc(e(t?"settingModelDescApi":"settingModelDescCli")).addText(a=>a.setPlaceholder(t?w(this.plugin.settings).model||"model-id":m.model).setValue(this.plugin.settings.model).onChange(async s=>{this.plugin.settings.model=s.trim()||(t?"":m.model),this.plugin.saveSettingsDebounced()})),new h.Setting(n).setName(e("settingMaxInputName")).setDesc(e("settingMaxInputDesc")).addText(a=>a.setValue(String(this.plugin.settings.maxDocChars||m.maxDocChars)).onChange(async s=>{let o=parseInt(s,10);!Number.isNaN(o)&&o>=1e3&&(this.plugin.settings.maxDocChars=o,this.plugin.saveSettingsDebounced())})),n.createEl("h3",{text:e("promptHeader")}),new h.Setting(n).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||m.promptLanguage).onChange(async s=>{this.plugin.settings.promptLanguage=s,await this.plugin.saveSettings()})}),new h.Setting(n).setName(e("settingCardRangeName")).setDesc(e("settingCardRangeDesc")).addText(a=>a.setPlaceholder("min").setValue(String(this.plugin.settings.minCards||m.minCards)).onChange(async 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||m.maxCards)).onChange(async s=>{let o=parseInt(s,10);!Number.isNaN(o)&&o>0&&(this.plugin.settings.maxCards=Math.max(o,this.plugin.settings.minCards||m.minCards),this.plugin.saveSettingsDebounced())})),new h.Setting(n).setName(e("settingCustomPromptName")).setDesc(e("settingCustomPromptDesc")).addTextArea(a=>(a.inputEl.rows=8,a.setPlaceholder(e("settingCustomPromptPlaceholder")).setValue(this.plugin.settings.customSystemPrompt||"").onChange(async s=>{this.plugin.settings.customSystemPrompt=s,this.plugin.saveSettingsDebounced()}))),new h.Setting(n).setName(e("settingTestBackendName")).setDesc(e(t?"settingTestBackendDescApi":"settingTestBackendDescCli")).addButton(a=>a.setButtonText("Test").onClick(async()=>{try{let s=await It(this.plugin.settings);new h.Notice(`\u2713 ${s.slice(0,180)}`,8e3)}catch(s){new h.Notice(e("backendTestFailed",{error:s.message}),1e4)}})),new h.Setting(n).setName(e("settingExportFolderName")).setDesc(e("settingExportFolderDesc")).addText(a=>a.setValue(this.plugin.settings.exportFolder).onChange(async s=>{this.plugin.settings.exportFolder=s.trim()||m.exportFolder,this.plugin.saveSettingsDebounced()})),n.createEl("h3",{text:e("cacheHeader")}),new h.Setting(n).setName(e("settingMaxCacheName")).setDesc(e("settingMaxCacheDesc")).addText(a=>{a.setValue(String(this.plugin.settings.maxCacheEntries||V));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 l=await this.plugin.pruneCacheIfNeeded();l.length>0&&new h.Notice(e("cachePruned",{count:l.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 h.Setting(n).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 h.Notice(e("cacheClearedAll",{count:s})),this.display()}))}};var S=require("obsidian");function R(r,n,e,t){let i=r.createEl("button",{cls:"parallel-reader-icon-button",attr:{type:"button","aria-label":e}});return i.title=e,typeof S.setIcon=="function"?(0,S.setIcon)(i,n):i.textContent=e,i.addEventListener("click",async a=>{a.preventDefault(),a.stopPropagation();try{await t()}catch(s){console.error(s),new S.Notice(`${e} failed: `+(s.message||s))}}),i}function F(r,n,e,t,i){let a=r.createEl("button",{cls:i||"parallel-reader-text-button",attr:{type:"button"}});return n&&typeof S.setIcon=="function"&&(0,S.setIcon)(a,n),a.createSpan({text:e}),a.addEventListener("click",async s=>{s.preventDefault(),s.stopPropagation();try{await t()}catch(o){console.error(o),new S.Notice(`${e} failed: `+(o.message||o))}}),a}async function L(r,n){try{await navigator.clipboard.writeText(r),new S.Notice(n)}catch(e){new S.Notice("Copy failed: "+(e.message||e))}}function _e(r){return String(r||"").split("/").map(n=>n.trim()).filter(Boolean).join("/")}function Ve(r){let n=_e(r);if(!n)return[];let e=n.split("/");return e.map((t,i)=>e.slice(0,i+1).join("/"))}async function nt(r,n){for(let e of Ve(n))if(!r.vault.getAbstractFileByPath(e))try{await r.vault.createFolder(e)}catch(t){if(!r.vault.getAbstractFileByPath(e))throw t}}var v=require("obsidian");var at=require("obsidian");var me=class extends at.Modal{constructor(n,e,t,i){super(n),this.plugin=e,this.card=t||{},this.onSave=i}onOpen(){let{contentEl:n}=this;n.empty(),n.createEl("h2",{text:this.plugin.t("editCardTitle")});let e=this.createLabeledInput(n,this.plugin.t("editCardTitleField"),this.card.title||""),t=this.createLabeledTextarea(n,this.plugin.t("editCardGistField"),this.card.gist||"",3),i=this.createLabeledTextarea(n,this.plugin.t("editCardBulletsField"),(this.card.bullets||[]).join(` +`),8),a=n.createDiv({cls:"parallel-reader-modal-actions"});F(a,null,this.plugin.t("editCardCancel"),()=>this.close(),"parallel-reader-text-button"),F(a,null,this.plugin.t("editCardSave"),async()=>{await this.onSave({title:e.value.trim()||this.card.title||"",gist:t.value.trim(),bullets:i.value.split(/\r?\n/).map(s=>s.trim()).filter(Boolean)}),this.close()},"parallel-reader-text-button")}createLabeledInput(n,e,t){let i=n.createDiv({cls:"parallel-reader-modal-field"});i.createEl("label",{text:e});let a=i.createEl("input",{attr:{type:"text"}});return a.value=t,a}createLabeledTextarea(n,e,t,i){let a=n.createDiv({cls:"parallel-reader-modal-field"});a.createEl("label",{text:e});let s=a.createEl("textarea");return s.rows=i,s.value=t,s}};var N="parallel-reader-view",ge=class extends v.ItemView{constructor(e,t){super(e);this.stale=!1;this.loadingMessage="";this.errorMessage="";this.plugin=t,this.sections=[],this.sourceFile=null,this.cards=[],this.activeIdx=-1}getViewType(){return N}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",t=>this.handleKeydown(t)),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 t=e.createDiv({cls:"parallel-reader-empty"});t.createEl("h3",{text:this.plugin.t("appTitle")}),t.createEl("p",{text:this.plugin.t("emptyOpenNote")}),t.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)}async loadFor(e,t,i){this.sourceFile=e,this.sections=t,this.stale=!!i,this.loadingMessage="",this.errorMessage="",this.render()}async renderLoading(e,t){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage=t||this.plugin.t("loadingDefault"),this.errorMessage="",this.render()}async renderError(e,t){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage=t||this.plugin.t("errorTitle"),this.render()}renderEmptyWithHint(e){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let t=this.containerEl.children[1];t.empty();let i=t.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)?R(a,"square",this.plugin.t("actionCancel"),()=>{this.plugin.cancelGenerationForFile(this.sourceFile)}):R(a,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0)),R(a,"copy",this.plugin.t("actionCopyAll"),()=>this.plugin.copyCurrentViewMarkdown()),R(a,"download",this.plugin.t("actionExport"),()=>this.exportToVault())),this.stale){let l=e.createDiv({cls:"parallel-reader-stale-banner"});l.createSpan({text:this.plugin.t("staleBanner")}),F(l,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-stale-button")}if(this.loadingMessage){let l=e.createDiv({cls:"parallel-reader-state parallel-reader-loading"});l.createDiv({cls:"parallel-reader-spinner"}),l.createEl("div",{text:this.loadingMessage,cls:"parallel-reader-state-title"}),l.createEl("div",{text:this.plugin.t("loadingSubtitle"),cls:"parallel-reader-state-subtitle"});return}if(this.errorMessage){let l=e.createDiv({cls:"parallel-reader-state parallel-reader-error"});l.createEl("div",{text:this.plugin.t("errorTitle"),cls:"parallel-reader-state-title"}),l.createEl("div",{text:this.errorMessage,cls:"parallel-reader-state-subtitle"}),F(l,"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((l,f)=>{let p=s.createDiv({cls:"parallel-reader-card"});p.dataset.idx=String(f),l.startLine<0&&p.addClass("parallel-reader-card-unanchored");let d=p.createEl("div",{cls:"parallel-reader-card-title"});if(d.createSpan({text:l.title}),l.startLine<0&&d.createEl("span",{text:" \u26A0",cls:"parallel-reader-warn",title:this.plugin.t("anchorMismatch")}),l.gist){let y=p.createEl("div",{cls:"parallel-reader-gist"});v.MarkdownRenderer.render(this.app,l.gist,y,o,this).catch(()=>{y.setText(l.gist)})}let b=l.bullets||[];if(b.length>0){let y=p.createEl("div",{cls:"parallel-reader-bullets-md"}),c=b.map(g=>`- ${g}`).join(` +`);v.MarkdownRenderer.render(this.app,c,y,o,this).catch(()=>{y.setText(c)})}else l.gist||p.createEl("div",{cls:"parallel-reader-empty-li",text:this.plugin.t("emptyCard")});p.addEventListener("click",y=>{let c=window.getSelection();if(c&&c.toString().length>0)return;let g=y.target;g&&g.tagName==="A"||l.startLine>=0&&this.plugin.scrollEditorToLine(l.startLine,this.sourceFile)}),p.addEventListener("contextmenu",y=>{y.preventDefault();let c=new v.Menu;c.addItem(g=>g.setTitle(this.plugin.t("menuCopyMarkdown")).setIcon("copy").onClick(()=>L(Ae(l),this.plugin.t("copiedMarkdown")))),c.addItem(g=>g.setTitle(this.plugin.t("menuCopyPlain")).setIcon("clipboard-copy").onClick(()=>L(We(l),this.plugin.t("copiedPlain")))),l.anchor&&c.addItem(g=>g.setTitle(this.plugin.t("menuCopyAnchor")).setIcon("quote-glyph").onClick(()=>L(l.anchor,this.plugin.t("copiedAnchor")))),c.addSeparator(),l.startLine>=0&&c.addItem(g=>g.setTitle(this.plugin.t("menuJumpSource")).setIcon("arrow-right").onClick(()=>this.plugin.scrollEditorToLine(l.startLine,this.sourceFile))),c.addSeparator(),c.addItem(g=>g.setTitle(this.plugin.t("menuEditCard")).setIcon("pencil").onClick(()=>this.openEditCardModal(f))),c.addItem(g=>g.setTitle(this.plugin.t("menuDeleteCard")).setIcon("trash").onClick(()=>this.deleteCard(f))),c.showAtMouseEvent(y)}),this.cards.push(p)}),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 t=ne(this.activeIdx,this.sections.length,e);return this.setActiveSection(t),this.focusSummaryPane(),t}jumpToActiveSection(){let e=ae(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 t=X(this.sections,e);if(t.length===this.sections.length)return!1;let i=this.sections.length;return this.sections=t,this.activeIdx=Z(e,i,this.activeIdx),await this.plugin.cacheReplaceCards(this.sourceFile.path,t),this.render(),new v.Notice(this.plugin.t("cardDeleted")),!0}openEditCardModal(e){return!this.sourceFile||!this.sections[e]?!1:(new me(this.app,this.plugin,this.sections[e],async t=>{await this.updateCard(e,t)}).open(),!0)}async updateCard(e,t){if(!this.sourceFile)return!1;let i=Q(this.sections,e,t);return i.length!==this.sections.length?!1:(this.sections=i,await this.plugin.cacheReplaceCards(this.sourceFile.path,i),this.render(),new v.Notice(this.plugin.t("cardSaved")),!0)}async exportToVault(){if(!this.sourceFile)return;let e=_e(this.plugin.settings.exportFolder),t=`${this.sourceFile.basename} - ${this.plugin.t("displayName")}.md`,i=`${e}/${t}`,a=["---",`source: [[${this.sourceFile.basename}]]`,`generated: ${new Date().toISOString().slice(0,10)}`,"tool: parallel-reader","---","",J(`${this.sourceFile.basename} \xB7 ${this.plugin.t("displayName")}`,this.sections),""].join(` +`),s=this.plugin.app;await nt(s,e);let o=s.vault.getAbstractFileByPath(i);o instanceof v.TFile?await s.vault.modify(o,a):await s.vault.create(i,a),new v.Notice(this.plugin.t("exported",{path:i}))}};async function Rt(r,n,e){let{system:t,user:i}=Me(r,n),a;switch(n.backend){case"codex":a=await qe(t,i,n,e);break;case"api":a=await z(u.requestUrl,t,i,n);break;case"anthropic-api":a=await z(u.requestUrl,t,i,n);break;default:a=await ze(t,i,n,e);break}let s=a.map(o=>({title:o.title,level:2,anchor:o.anchor,gist:o.gist,startLine:Y(r,o.anchor),bullets:o.bullets}));return s.sort((o,l)=>o.startLine<0&&l.startLine<0?0:o.startLine<0?1:l.startLine<0?-1:o.startLine-l.startLine),s}function it(r,n){return n?.phase==="generating"&&r&&B(r.backend)?"cancelRequestedApiInFlight":"cancelRequested"}var Be=class extends u.Plugin{constructor(){super(...arguments);this._scrollDispose=null;this._settingsSaveTimer=null;this._cacheSaveTimer=null;this._cacheDirty=!1}t(e,t){return C(this.settings||m,e,t)}async onload(){await this.loadSettings(),this.jobs=new U,this._cacheSaveTimer=null,this._cacheDirty=!1,this.addRibbonIcon("book-open",this.t("ribbonOpen"),async()=>{let e=this.getActiveView();await this.ensureView(),e?.file&&await this.syncViewToFile(e.file)}),this.registerView(N,e=>new ge(e,this)),this.addCommand({id:"parallel-reader-run",name:this.t("cmdRun"),callback:()=>this.runForActiveFile(!1)}),this.addCommand({id:"parallel-reader-regen",name:this.t("cmdRegen"),callback:()=>this.runForActiveFile(!0)}),this.addCommand({id:"parallel-reader-open-view",name:this.t("cmdOpenView"),callback:async()=>{let e=this.getActiveView();await this.ensureView(),e?.file&&this.syncViewToFile(e.file)}}),this.addCommand({id:"parallel-reader-export-current",name:this.t("cmdExport"),callback:()=>this.exportCurrentView()}),this.addCommand({id:"parallel-reader-copy-current-markdown",name:this.t("cmdCopyMarkdown"),callback:()=>this.copyCurrentViewMarkdown()}),this.addCommand({id:"parallel-reader-cancel-current",name:this.t("cmdCancel"),callback:()=>this.cancelActiveGeneration()}),this.addCommand({id:"parallel-reader-clear-current",name:this.t("cmdClearCurrent"),callback:async()=>{let e=this.getActiveView();if(!e?.file)return new u.Notice(this.t("noCurrentNote"));await this.cacheDelete(e.file.path),new u.Notice(this.t("cacheClearedFile",{name:e.file.basename}))}}),this.addCommand({id:"parallel-reader-clear-all",name:this.t("cmdClearAll"),callback:async()=>{let e=Object.keys(this.cache).length;await this.cacheClear(),new u.Notice(this.t("cacheClearedAll",{count:e}))}}),this.addCommand({id:"parallel-reader-card-prev",name:this.t("cmdCardPrev"),hotkeys:[{modifiers:["Alt"],key:"ArrowUp"}],callback:()=>this.moveActiveCard(-1)}),this.addCommand({id:"parallel-reader-card-next",name:this.t("cmdCardNext"),hotkeys:[{modifiers:["Alt"],key:"ArrowDown"}],callback:()=>this.moveActiveCard(1)}),this.addCommand({id:"parallel-reader-card-jump",name:this.t("cmdCardJump"),callback:()=>this.jumpActiveCard()}),this.addSettingTab(new he(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,t)=>this.addFileMenuItems(e,t))),this.registerEvent(this.app.vault.on("rename",(e,t)=>this.handleFileRename(e,t))),this.registerEvent(this.app.vault.on("delete",e=>this.handleFileDelete(e))),this.bindScrollSync()}async onunload(){await this.flushSettingsSave(),await this.flushCacheSave(),this.app.workspace.detachLeavesOfType(N)}async loadSettings(){let t=(await this.loadData()||{}).settings||{};this.settings=Fe(Object.assign({},m,t)),await this.loadCache()}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(t=>console.error("[parallel-reader] failed to save settings",t))},e)}async flushSettingsSave(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null,await this.saveSettings())}async saveCache(){this._cacheSaveTimer&&(clearTimeout(this._cacheSaveTimer),this._cacheSaveTimer=null),this.pruneCache(),await this.writeCacheFile(),this._cacheDirty=!1}scheduleCacheSave(e=5e3){this._cacheDirty=!0,!this._cacheSaveTimer&&(this._cacheSaveTimer=setTimeout(()=>{this._cacheSaveTimer=null,this._cacheDirty&&this.saveCache().catch(t=>console.error("[parallel-reader] failed to save cache",t))},e))}async flushCacheSave(){this._cacheSaveTimer&&(clearTimeout(this._cacheSaveTimer),this._cacheSaveTimer=null),this._cacheDirty&&await this.saveCache()}cacheFilePath(){let e=this.app.vault.configDir||".obsidian",t=this.manifest?.id||"parallel-reader";return`${e}/plugins/${t}/cache.json`}async ensurePluginDataDir(){let e=this.app.vault.adapter,t=this.app.vault.configDir||".obsidian",i=this.manifest?.id||"parallel-reader",a=`${t}/plugins/${i}`;try{if(typeof e.exists=="function"&&await e.exists(a))return;await e.mkdir(a)}catch{}}async readCacheFile(){let e=this.app.vault.adapter;try{let t=await e.read(this.cacheFilePath()),i=JSON.parse(t);if(i&&typeof i=="object"&&i.entries&&typeof i.entries=="object")return i.entries}catch(t){let i=String(t?.message||t||"");/not found|does not exist|ENOENT/i.test(i)||console.warn("[parallel-reader] failed to read cache.json",t)}return{}}async writeCacheFile(){await this.ensurePluginDataDir(),await this.app.vault.adapter.write(this.cacheFilePath(),ye(this.cache))}async loadCache(){this.cache=await this.readCacheFile(),this.pruneCache().length>0&&await this.writeCacheFile()}pruneCache(){return Ne(this.cache,this.settings?.maxCacheEntries||V)}async pruneCacheIfNeeded(){let e=this.pruneCache();return e.length>0&&await this.saveCache(),e}cacheGet(e){return this.cache[e]||null}async cacheTouch(e){let t=fe(this.cache[e]||null);return t?(this.scheduleCacheSave(),t):null}async cachePut(e,t,i,a){let s=new Date().toISOString();this.cache[e]={schemaVersion:K,contentHash:_(t),settingsHash:ie(a||this.settings),cards:i,generatedAt:s,lastAccessedAt:s},await this.saveCache()}async cacheReplaceCards(e,t){let i=this.cache[e];if(!i)return!1;let a=new Date().toISOString();return i.cards=(t||[]).map(s=>({title:s.title,anchor:s.anchor,gist:s.gist,bullets:s.bullets||[]})),i.updatedAt=a,i.lastAccessedAt=a,await this.saveCache(),!0}async cacheDelete(e){this.cache[e]&&(delete this.cache[e],await this.saveCache())}async cacheClear(){this.cache={},await this.saveCache()}async ensureView(){let{workspace:e}=this.app,t=e.getLeavesOfType(N)[0];return t||(t=e.getRightLeaf(!1),await t.setViewState({type:N,active:!0})),e.revealLeaf(t),t.view}getActiveView(){return this.app.workspace.getActiveViewOfType(u.MarkdownView)}getParallelView(){return this.app.workspace.getLeavesOfType(N)[0]?.view}moveActiveCard(e){let t=this.getParallelView();return t?.sections.length?t.moveActiveSection(e):(new u.Notice(this.t("noActiveCard")),-1)}jumpActiveCard(){let e=this.getParallelView();return!e||e.jumpToActiveSection()<0?(new u.Notice(this.t("noActiveCard")),!1):!0}isGeneratingFile(e){return!!e&&!!e.path&&this.jobs.isRunning(e.path)}cancelGenerationForFile(e){if(!e?.path)return new u.Notice(this.t("noCancelableJob")),!1;let t=this.jobs.get(e.path),i=it(this.settings,t),a=this.jobs.cancel(e.path);return new u.Notice(a?this.t(i):this.t("noCancelableJob")),a}viewIsShowingFile(e,t){return!!e&&!!t&&e.sourceFile?.path===t.path}activeFileStillMatches(e){let t=this.getActiveView();return!t?.file||t.file.path===e.path}cancelActiveGeneration(){let e=this.getActiveView();if(e?.file&&this.cancelGenerationForFile(e.file))return;let t=this.getParallelView();t?.sourceFile?this.cancelGenerationForFile(t.sourceFile):new u.Notice(this.t("noCancelableJob"))}confirmRegenerateEditedCards(){let e=this.t("confirmRegenerateEditedCards");return typeof window<"u"&&typeof window.confirm=="function"?window.confirm(e):!0}addFileMenuItems(e,t){!(t instanceof u.TFile)||!t.path.endsWith(".md")||(e.addSeparator(),e.addItem(i=>i.setTitle(this.t("fileMenuGenerate")).setIcon("book-open").onClick(()=>this.runForFile(t,!1))),e.addItem(i=>i.setTitle(this.t("fileMenuRegen")).setIcon("refresh-cw").onClick(()=>this.runForFile(t,!0))),this.cacheGet(t.path)&&e.addItem(i=>i.setTitle(this.t("fileMenuClear")).setIcon("trash").onClick(async()=>{await this.cacheDelete(t.path),new u.Notice(this.t("cacheClearedFile",{name:t.basename}))})))}async handleFileRename(e,t){if(!(e instanceof u.TFile)||!t)return;let i=t.endsWith(".md"),a=e.path.endsWith(".md");if(!i&&!a)return;if(i&&!a){this.cache[t]&&(delete this.cache[t],await this.saveCache());let o=this.getParallelView();o&&o.sourceFile?.path===t&&o.renderEmpty();return}if(!i)return;this.cache[t]&&(this.cache[e.path]=this.cache[t],delete this.cache[t],await this.saveCache());let s=this.getParallelView();s?.sourceFile&&(s.sourceFile.path===t||s.sourceFile.path===e.path)&&(s.sourceFile=e,await this.syncViewToFile(e))}async handleFileDelete(e){if(!(e instanceof u.TFile))return;this.cache[e.path]&&(delete this.cache[e.path],await this.saveCache());let t=this.getParallelView();t?.sourceFile?.path===e.path&&t.renderEmpty()}async exportCurrentView(){let e=this.getActiveView(),t=await this.ensureView();if((!t.sourceFile||!t.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!t.sourceFile||!t.sections.length){new u.Notice(this.t("noExportContent"));return}await t.exportToVault()}async copyCurrentViewMarkdown(){let e=this.getActiveView(),t=await this.ensureView();if((!t.sourceFile||!t.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!t.sourceFile||!t.sections.length){new u.Notice(this.t("noCopyContent"));return}await L(J(`${t.sourceFile.basename} \xB7 ${this.t("displayName")}`,t.sections),this.t("copiedAllMarkdown"))}async runForActiveFile(e){let t=this.getActiveView();if(!t?.file){new u.Notice(this.t("openNoteFirst"));return}return this.runForFile(t.file,e)}async runForFile(e,t){if(!e){new u.Notice(this.t("openNoteFirst"));return}if(this.jobs.isRunning(e.path)){new u.Notice(this.t("alreadyGenerating"));return}if(Ce(this.cacheGet(e.path),t)&&!this.confirmRegenerateEditedCards()){new u.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 u.Notice(this.t("emptyNote"));return}if(i=await this.ensureView(),a.throwIfCancelled(),a.setPhase("cache-check"),!t){let d=this.cacheGet(e.path);if(se(d,s,this.settings)){await this.cacheTouch(e.path),this.activeFileStillMatches(e)&&await i.loadFor(e,this.resolveCardAnchors(s,d.cards),!1);return}}await i.renderLoading(e,this.t("loadingGenerating"));let o=Number(this.settings.maxDocChars)||m.maxDocChars;s.length>o&&new u.Notice(this.t("longNoteTruncated",{count:o})),new u.Notice(this.t("generatingNotice")),a.setPhase("generating");let l=await Rt(s,this.settings,a);if(a.throwIfCancelled(),l.length===0){new u.Notice(this.t("noCardsReturned"));return}let f=l.map(d=>({title:d.title,anchor:d.anchor,gist:d.gist,bullets:d.bullets}));a.setPhase("saving"),await this.cachePut(e.path,s,f,this.settings),a.throwIfCancelled(),this.viewIsShowingFile(i,e)&&await i.loadFor(e,l,!1);let p=l.filter(d=>d.startLine<0).length;new u.Notice(this.t("generationDone",{count:l.length,suffix:p?this.t("unanchoredSuffix",{count:p}):""}))}).catch(async a=>{if(a instanceof O){new u.Notice(a.message);return}if(a instanceof A){i&&this.viewIsShowingFile(i,e)&&await i.renderError(e,this.t("cancelledError")),new u.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 u.Notice(this.t("generationFailed",{kind:s==="unknown"?"":` (${s})`,error:a.message||a}))})}resolveCardAnchors(e,t){let i=(t||[]).map(a=>({title:a.title,level:2,anchor:a.anchor,gist:a.gist,startLine:Y(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 t=this.app.workspace.getLeavesOfType(N);if(t.length===0)return;let i=t[0].view;if(!i||!this.activeFileStillMatches(e))return;let a=this.cacheGet(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=!se(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 t=e.editor,i=t&&t.cm,a=i?.scrollDOM?i.scrollDOM:e.contentEl.querySelector(".cm-scroller");if(!a)return;let s=Oe(()=>this.handleEditorScroll(e));a.addEventListener("scroll",s,{passive:!0}),this._scrollDispose=()=>{s.cancel(),a.removeEventListener("scroll",s)}}handleEditorScroll(e){let t=this.getParallelView();if(!t||!e.file||t.sourceFile?.path!==e.file.path)return;let i=e.editor,a=i&&i.cm;if(!a?.scrollDOM)return;let s=a.scrollDOM.getBoundingClientRect(),o=Le(s),l=0;try{let p=a.posAtCoords({x:s.left+20,y:o});p!=null&&(l=a.state.doc.lineAt(p).number-1)}catch{return}let f=-1;for(let p=0;p; - jobs: GenerationJobManager; - _scrollDispose: (() => void) | null; - _settingsSaveTimer: ReturnType | null; - _cacheSaveTimer: ReturnType | null; - _cacheDirty: boolean; + settings!: PluginSettings; + cache!: Record; + jobs!: GenerationJobManager; + _scrollDispose: (() => void) | null = null; + _settingsSaveTimer: ReturnType | null = null; + _cacheSaveTimer: ReturnType | null = null; + _cacheDirty = false; t(key: string, vars?: Record) { return translate(this.settings || DEFAULT_SETTINGS, key, vars); @@ -296,8 +296,8 @@ class ParallelReaderPlugin extends Plugin { const parsed = JSON.parse(raw); if (parsed && typeof parsed === 'object' && parsed.entries && typeof parsed.entries === 'object') return parsed.entries; - } catch (e) { - const message = String(e?.message || e || ''); + } catch (e: unknown) { + const message = String((e as Error)?.message || e || ''); if (!/not found|does not exist|ENOENT/i.test(message)) console.warn('[parallel-reader] failed to read cache.json', e); } diff --git a/src/cli.ts b/src/cli.ts index 46b64d5..86c4852 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -72,8 +72,8 @@ export function runCli( .join(':'), }, }); - } catch (e) { - return reject(new Error(`Failed to start ${cmd}: ${e.message}`)); + } catch (e: unknown) { + return reject(new Error(`Failed to start ${cmd}: ${(e as Error).message}`)); } let stdout = ''; diff --git a/src/settings-tab.ts b/src/settings-tab.ts index 9ed88f7..8e2f787 100644 --- a/src/settings-tab.ts +++ b/src/settings-tab.ts @@ -315,8 +315,8 @@ export class ParallelReaderSettingTab extends PluginSettingTab { try { const result = await testBackend(this.plugin.settings); new Notice(`✓ ${result.slice(0, 180)}`, 8000); - } catch (e) { - new Notice(tr('backendTestFailed', { error: e.message }), 10000); + } catch (e: unknown) { + new Notice(tr('backendTestFailed', { error: (e as Error).message }), 10000); } }), ); diff --git a/src/ui-helpers.ts b/src/ui-helpers.ts index 2c1afc6..fbf071e 100644 --- a/src/ui-helpers.ts +++ b/src/ui-helpers.ts @@ -18,9 +18,9 @@ export function addIconButton(parent: HTMLElement, icon: string, title: string, e.stopPropagation(); try { await onClick(); - } catch (err) { + } catch (err: unknown) { console.error(err); - new Notice(`${title} failed: ` + (err.message || err)); + new Notice(`${title} failed: ` + ((err as Error).message || err)); } }); return button; @@ -44,9 +44,9 @@ export function addTextButton( e.stopPropagation(); try { await onClick(); - } catch (err) { + } catch (err: unknown) { console.error(err); - new Notice(`${label} failed: ` + (err.message || err)); + new Notice(`${label} failed: ` + ((err as Error).message || err)); } }); return button; @@ -56,7 +56,7 @@ export async function copyToClipboard(text: string, successMsg: string) { try { await navigator.clipboard.writeText(text); new Notice(successMsg); - } catch (e) { - new Notice('Copy failed: ' + (e.message || e)); + } catch (e: unknown) { + new Notice('Copy failed: ' + ((e as Error).message || e)); } } diff --git a/src/view.ts b/src/view.ts index b2eb317..02f69f0 100644 --- a/src/view.ts +++ b/src/view.ts @@ -17,9 +17,9 @@ export class ParallelReaderView extends ItemView { sourceFile: TFile | null; cards: HTMLElement[]; activeIdx: number; - stale: boolean; - loadingMessage: string; - errorMessage: string; + stale = false; + loadingMessage = ''; + errorMessage = ''; constructor(leaf: WorkspaceLeaf, plugin: PluginHost) { super(leaf); @@ -28,8 +28,6 @@ export class ParallelReaderView extends ItemView { this.sourceFile = null; this.cards = []; this.activeIdx = -1; - this.loadingMessage = ''; - this.errorMessage = ''; } getViewType() { diff --git a/tsconfig.json b/tsconfig.json index c2c321a..b31e624 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,12 +6,7 @@ "moduleResolution": "Node", "lib": ["ES2022", "DOM"], "types": ["node"], - "strict": false, - "noImplicitAny": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "strictBindCallApply": true, - "noImplicitThis": true, + "strict": true, "noImplicitReturns": false, "skipLibCheck": true, "esModuleInterop": true,