From 1d8ea77fa4bd8f454f4afeeaa58b353ec110dead Mon Sep 17 00:00:00 2001 From: megan-blue Date: Tue, 7 Jul 2026 16:05:12 +0800 Subject: [PATCH] Improve agent terminal reuse and diff refresh --- main.js | 174 ++++++++++++++++++----- src/agent/TerminalLauncher.ts | 251 +++++++++++++++++++++++++++++----- src/diff/DiffModal.ts | 85 ++++++++++-- src/i18n/locales/en.ts | 4 + src/i18n/locales/zh-CN.ts | 4 + src/main.ts | 10 +- src/utils/nodeApi.ts | 3 +- styles.css | 52 ++++++- 8 files changed, 502 insertions(+), 81 deletions(-) diff --git a/main.js b/main.js index c489ee7..ac88bf6 100644 --- a/main.js +++ b/main.js @@ -3,22 +3,22 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var Ke=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var Ut=Object.prototype.hasOwnProperty;var Jt=(s,i)=>()=>(s&&(i=s(s=0)),i);var lt=(s,i)=>{for(var e in i)Ke(s,e,{get:i[e],enumerable:!0})},Yt=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let n of Gt(i))!Ut.call(s,n)&&n!==e&&Ke(s,n,{get:()=>i[n],enumerable:!(t=Kt(i,n))||t.enumerable});return s};var Zt=s=>Yt(Ke({},"__esModule",{value:!0}),s);var Mt={};lt(Mt,{API_SYSTEM_PROMPT:()=>Ie,PROVIDER_DEFAULTS:()=>E,buildAPIUserMessage:()=>Qe,callAPI:()=>Xe});async function Xe(s,i){try{switch(s.provider){case"anthropic":return await Sn(s,i);case"openai":case"deepseek":case"custom":return await kn(s,i);case"gemini":return await Pn(s,i)}}catch(e){return{success:!1,error:String(e)}}}async function Sn(s,i){let e=E.anthropic.endpoint,t=JSON.stringify({model:s.model||E.anthropic.model,max_tokens:s.maxTokens,system:i.systemPrompt,messages:[{role:"user",content:i.userMessage}]});try{let r=(await(0,Re.requestUrl)({url:e,method:"POST",headers:{"Content-Type":"application/json","x-api-key":s.apiKey,"anthropic-version":"2023-06-01"},body:t})).json;return r.error?{success:!1,error:r.error.message??"Anthropic error"}:{success:!0,text:r.content?.find(l=>l.type==="text")?.text??""}}catch(n){return{success:!1,error:String(n)}}}async function kn(s,i){let e;s.provider==="custom"&&s.customEndpoint?e=s.customEndpoint:E[s.provider]?e=E[s.provider].endpoint:e=E.openai.endpoint;let t=JSON.stringify({model:s.model||E[s.provider]?.model||E.openai.model,max_tokens:s.maxTokens,messages:[{role:"system",content:i.systemPrompt},{role:"user",content:i.userMessage}]});try{let r=(await(0,Re.requestUrl)({url:e,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.apiKey}`},body:t})).json;return r.error?{success:!1,error:r.error.message??"OpenAI error"}:{success:!0,text:r.choices?.[0]?.message?.content??""}}catch(n){return{success:!1,error:String(n)}}}async function Pn(s,i){let e=s.model||E.gemini.model,n=`${E.gemini.endpoint.replace("{{model}}",e)}?key=${encodeURIComponent(s.apiKey)}`,r=JSON.stringify({system_instruction:{parts:[{text:i.systemPrompt}]},contents:[{role:"user",parts:[{text:i.userMessage}]}],generationConfig:{maxOutputTokens:s.maxTokens}});try{let l=(await(0,Re.requestUrl)({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:r})).json;return l.error?{success:!1,error:l.error.message??"Gemini error"}:{success:!0,text:l.candidates?.[0]?.content?.parts?.[0]?.text??""}}catch(o){return{success:!1,error:String(o)}}}function Qe(s,i){return`## \u539F\u6587 +var Je=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var en=Object.prototype.hasOwnProperty;var tn=(s,i)=>()=>(s&&(i=s(s=0)),i);var dt=(s,i)=>{for(var e in i)Je(s,e,{get:i[e],enumerable:!0})},nn=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let n of Qt(i))!en.call(s,n)&&n!==e&&Je(s,n,{get:()=>i[n],enumerable:!(t=Xt(i,n))||t.enumerable});return s};var rn=s=>nn(Je({},"__esModule",{value:!0}),s);var Ht={};dt(Ht,{API_SYSTEM_PROMPT:()=>Fe,PROVIDER_DEFAULTS:()=>P,buildAPIUserMessage:()=>tt,callAPI:()=>et});async function et(s,i){try{switch(s.provider){case"anthropic":return await Rn(s,i);case"openai":case"deepseek":case"custom":return await In(s,i);case"gemini":return await Mn(s,i)}}catch(e){return{success:!1,error:String(e)}}}async function Rn(s,i){let e=P.anthropic.endpoint,t=JSON.stringify({model:s.model||P.anthropic.model,max_tokens:s.maxTokens,system:i.systemPrompt,messages:[{role:"user",content:i.userMessage}]});try{let r=(await(0,Me.requestUrl)({url:e,method:"POST",headers:{"Content-Type":"application/json","x-api-key":s.apiKey,"anthropic-version":"2023-06-01"},body:t})).json;return r.error?{success:!1,error:r.error.message??"Anthropic error"}:{success:!0,text:r.content?.find(l=>l.type==="text")?.text??""}}catch(n){return{success:!1,error:String(n)}}}async function In(s,i){let e;s.provider==="custom"&&s.customEndpoint?e=s.customEndpoint:P[s.provider]?e=P[s.provider].endpoint:e=P.openai.endpoint;let t=JSON.stringify({model:s.model||P[s.provider]?.model||P.openai.model,max_tokens:s.maxTokens,messages:[{role:"system",content:i.systemPrompt},{role:"user",content:i.userMessage}]});try{let r=(await(0,Me.requestUrl)({url:e,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.apiKey}`},body:t})).json;return r.error?{success:!1,error:r.error.message??"OpenAI error"}:{success:!0,text:r.choices?.[0]?.message?.content??""}}catch(n){return{success:!1,error:String(n)}}}async function Mn(s,i){let e=s.model||P.gemini.model,n=`${P.gemini.endpoint.replace("{{model}}",e)}?key=${encodeURIComponent(s.apiKey)}`,r=JSON.stringify({system_instruction:{parts:[{text:i.systemPrompt}]},contents:[{role:"user",parts:[{text:i.userMessage}]}],generationConfig:{maxOutputTokens:s.maxTokens}});try{let l=(await(0,Me.requestUrl)({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:r})).json;return l.error?{success:!1,error:l.error.message??"Gemini error"}:{success:!0,text:l.candidates?.[0]?.content?.parts?.[0]?.text??""}}catch(o){return{success:!1,error:String(o)}}}function tt(s,i){return`## \u539F\u6587 ${s} --- -${i}`}var Re,E,Ie,ce=Jt(()=>{Re=require("obsidian"),E={anthropic:{model:"claude-opus-4-5",endpoint:"https://api.anthropic.com/v1/messages"},openai:{model:"gpt-4o",endpoint:"https://api.openai.com/v1/chat/completions"},deepseek:{model:"deepseek-v4-flash",endpoint:"https://api.deepseek.com/chat/completions"},gemini:{model:"gemini-1.5-pro",endpoint:"https://generativelanguage.googleapis.com/v1beta/models/{{model}}:generateContent"},custom:{model:"gpt-4o",endpoint:""}};Ie=`\u4F60\u662F\u4E13\u4E1A\u6587\u6863\u7F16\u8F91\u52A9\u624B\u3002 +${i}`}var Me,P,Fe,ue=tn(()=>{Me=require("obsidian"),P={anthropic:{model:"claude-opus-4-5",endpoint:"https://api.anthropic.com/v1/messages"},openai:{model:"gpt-4o",endpoint:"https://api.openai.com/v1/chat/completions"},deepseek:{model:"deepseek-v4-flash",endpoint:"https://api.deepseek.com/chat/completions"},gemini:{model:"gemini-1.5-pro",endpoint:"https://generativelanguage.googleapis.com/v1beta/models/{{model}}:generateContent"},custom:{model:"gpt-4o",endpoint:""}};Fe=`\u4F60\u662F\u4E13\u4E1A\u6587\u6863\u7F16\u8F91\u52A9\u624B\u3002 \u8BF7\u4E25\u683C\u6309\u7167\u6279\u9605\u610F\u89C1\u4FEE\u6539\u6587\u6863\uFF0C\u9075\u5FAA\u4EE5\u4E0B\u89C4\u5219\uFF1A 1. \u53EA\u4FEE\u6539\u6709\u6279\u9605\u610F\u89C1\u8986\u76D6\u7684\u5185\u5BB9\u3002 2. \u5220\u9664\u7EBF (strike: true) \u8868\u793A\u5F3A\u5220\u9664/\u5408\u5E76\u610F\u56FE\uFF0C\u7ED3\u5408\u4E0A\u4E0B\u6587\u5224\u65AD\u3002 3. \u8F93\u51FA\u5B8C\u6574\u4FEE\u6539\u540E\u7684 Markdown \u6587\u6863\uFF0C\u4E0D\u6DFB\u52A0\u4EFB\u4F55\u989D\u5916\u8BF4\u660E\u6587\u5B57\u3002 -4. \u76F4\u63A5\u8F93\u51FA\u4FEE\u6539\u540E\u7684 Markdown\uFF0C\u4E0D\u8981\u7528\u4EE3\u7801\u5757\u5305\u88F9\u3002`});var Kn={};lt(Kn,{default:()=>je});module.exports=Zt(Kn);var w=require("obsidian");var J=require("obsidian"),Xt='',Qt='',en='',tn='';function ct(){(0,J.addIcon)("prm-highlighter",Xt),(0,J.addIcon)("prm-check-check",Qt),(0,J.addIcon)("prm-diff",en),(0,J.addIcon)("prm-diya",tn)}var nn={"main.ribbonTooltip":"Promptuary \u4FA7\u8FB9\u680F","main.cmd.openSidebar":"\u6253\u5F00\u4FA7\u8FB9\u680F","main.cmd.highlightYellow":"\u9AD8\u4EAE\uFF08\u9EC4\uFF09","main.cmd.highlightGreen":"\u9AD8\u4EAE\uFF08\u7EFF\uFF09","main.cmd.highlightBlue":"\u9AD8\u4EAE\uFF08\u84DD\uFF09","main.cmd.highlightPink":"\u9AD8\u4EAE\uFF08\u7C89\uFF09","main.cmd.highlightOrange":"\u9AD8\u4EAE\uFF08\u6A59\uFF09","main.cmd.addNote":"\u6DFB\u52A0\u7B14\u8BB0","main.cmd.addReview":"\u6DFB\u52A0\u6279\u9605\u610F\u89C1","main.cmd.exportReview":"\u5BFC\u51FA\u6279\u9605\u6587\u4EF6","main.cmd.copyPrompt":"\u590D\u5236 Prompt","main.cmd.apiExecute":"API Key \u76F4\u8C03\u6267\u884C","main.cmd.runAgent":"\u4F7F\u7528 {{label}} \u6267\u884C","main.cmd.copyAgentCommand":"\u590D\u5236 Agent \u547D\u4EE4","main.notice.openMdFile":"\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A Markdown \u6587\u4EF6","main.notice.noReviewAnnotations":"\u5F53\u524D\u6587\u4EF6\u6CA1\u6709\u6279\u9605\u610F\u89C1","main.notice.allAccepted":"\u5DF2\u63A5\u53D7\u6240\u6709\u4FEE\u6539","main.notice.selectedApplied":"\u5DF2\u5E94\u7528\u9009\u4E2D\u7684\u4FEE\u6539","main.notice.allRolledBack":"\u5DF2\u56DE\u6EDA\u6240\u6709\u4FEE\u6539","main.notice.mobileNoAgent":"\u79FB\u52A8\u7AEF\u6682\u4E0D\u652F\u6301 Agent \u6267\u884C\uFF0C\u8BF7\u4F7F\u7528\u300C\u590D\u5236 Prompt\u300D","main.notice.monitoringChanges":"\u6B63\u5728\u76D1\u542C\u6587\u4EF6\u53D8\u66F4\uFF085 \u5206\u949F\u8D85\u65F6\uFF09\u2026","main.notice.autoHealed":"\u5DF2\u81EA\u52A8\u4FEE\u590D {{n}} \u6761\u6279\u6CE8\u4F4D\u7F6E","main.notice.reviewExecuted":"{{n}} \u6761\u6279\u9605\u610F\u89C1\u5DF2\u6267\u884C\u5E76\u81EA\u52A8\u79FB\u9664","main.notice.invalidReadingRemoved":"{{n}} \u6761\u5931\u6548\u9605\u8BFB\u6279\u6CE8\u5DF2\u81EA\u52A8\u79FB\u9664","main.notice.noChangesDetected":"\u672A\u68C0\u6D4B\u5230\u6587\u4EF6\u53D8\u66F4","main.notice.selectTextFirst":"\u8BF7\u5148\u9009\u4E2D\u8981\u6279\u6CE8\u7684\u6587\u5B57","main.notice.selectReviewTextFirst":"\u8BF7\u5148\u9009\u4E2D\u8981\u6279\u9605\u7684\u6587\u5B57","main.notice.noChangesNeeded":"API \u8FD4\u56DE\u5185\u5BB9\u4E0E\u539F\u6587\u76F8\u540C\uFF0C\u65E0\u9700\u4FEE\u6539","main.notice.cancelledNoChange":"\u5DF2\u53D6\u6D88\uFF0C\u6587\u4EF6\u672A\u4FEE\u6539","main.notice.noOriginalSnapshot":"\u6CA1\u6709\u4FDD\u5B58\u7684\u539F\u6587\u5FEB\u7167","main.notice.ruleNotFound":"\u672A\u627E\u5230\u89C4\u5219: {{id}}","main.notice.noAgentCLI":"\u672A\u68C0\u6D4B\u5230\u5DF2\u5B89\u88C5\u7684 Agent CLI\uFF0C\u8BF7\u5148\u5B89\u88C5 Claude Code / Codex / Aider / Gemini CLI","main.notice.exportSuccess":"\u5BFC\u51FA\u6210\u529F\uFF0C\u6B63\u5728\u6253\u5F00: {{target}}","main.notice.exportFailed":"\u5BFC\u51FA\u5931\u8D25\uFF1A\u672A\u751F\u6210\u6587\u4EF6","main.notice.changeDetected":"\u68C0\u6D4B\u5230\u6587\u4EF6\u53D8\u66F4\uFF0C\u6B63\u5728\u751F\u6210 Diff\u2026","main.notice.monitorTimeout":"\u76D1\u542C\u8D85\u65F6\uFF0C\u672A\u68C0\u6D4B\u5230\u66F4\u591A\u53D8\u66F4","main.notice.commandCopied":"{{label}} \u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","main.notice.configureAPIKey":"\u8BF7\u5728\u8BBE\u7F6E\u9762\u677F\u4E2D\u914D\u7F6E API Key\uFF08\u8BBE\u7F6E \u2192 API Key \u76F4\u8C03\uFF09","main.notice.reviewCleanupDone":"\u5DF2\u6E05\u7406 {{n}} \u6761\u5DF2\u5904\u7406\u6279\u9605","sidebar.empty.openFile":"\u8BF7\u6253\u5F00\u4E00\u4E2A Markdown \u6587\u4EF6","sidebar.mode.reading":"\u9605\u8BFB","sidebar.mode.review":"\u6279\u9605","sidebar.mode.all":"\u5168\u90E8","sidebar.tag.highlight":"\u9AD8\u4EAE","sidebar.tag.note":"\u7B14\u8BB0","sidebar.tag.delete":"\u5220\u9664","sidebar.tag.review":"\u6279\u9605","sidebar.empty.reading":`\u8FD8\u6CA1\u6709\u9605\u8BFB\u6807\u6CE8\u3002 +4. \u76F4\u63A5\u8F93\u51FA\u4FEE\u6539\u540E\u7684 Markdown\uFF0C\u4E0D\u8981\u7528\u4EE3\u7801\u5757\u5305\u88F9\u3002`});var ii={};dt(ii,{default:()=>Ke});module.exports=rn(ii);var w=require("obsidian");var J=require("obsidian"),on='',sn='',an='',ln='';function pt(){(0,J.addIcon)("prm-highlighter",on),(0,J.addIcon)("prm-check-check",sn),(0,J.addIcon)("prm-diff",an),(0,J.addIcon)("prm-diya",ln)}var cn={"main.ribbonTooltip":"Promptuary \u4FA7\u8FB9\u680F","main.cmd.openSidebar":"\u6253\u5F00\u4FA7\u8FB9\u680F","main.cmd.highlightYellow":"\u9AD8\u4EAE\uFF08\u9EC4\uFF09","main.cmd.highlightGreen":"\u9AD8\u4EAE\uFF08\u7EFF\uFF09","main.cmd.highlightBlue":"\u9AD8\u4EAE\uFF08\u84DD\uFF09","main.cmd.highlightPink":"\u9AD8\u4EAE\uFF08\u7C89\uFF09","main.cmd.highlightOrange":"\u9AD8\u4EAE\uFF08\u6A59\uFF09","main.cmd.addNote":"\u6DFB\u52A0\u7B14\u8BB0","main.cmd.addReview":"\u6DFB\u52A0\u6279\u9605\u610F\u89C1","main.cmd.exportReview":"\u5BFC\u51FA\u6279\u9605\u6587\u4EF6","main.cmd.copyPrompt":"\u590D\u5236 Prompt","main.cmd.apiExecute":"API Key \u76F4\u8C03\u6267\u884C","main.cmd.runAgent":"\u4F7F\u7528 {{label}} \u6267\u884C","main.cmd.copyAgentCommand":"\u590D\u5236 Agent \u547D\u4EE4","main.notice.openMdFile":"\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A Markdown \u6587\u4EF6","main.notice.noReviewAnnotations":"\u5F53\u524D\u6587\u4EF6\u6CA1\u6709\u6279\u9605\u610F\u89C1","main.notice.allAccepted":"\u5DF2\u63A5\u53D7\u6240\u6709\u4FEE\u6539","main.notice.selectedApplied":"\u5DF2\u5E94\u7528\u9009\u4E2D\u7684\u4FEE\u6539","main.notice.allRolledBack":"\u5DF2\u56DE\u6EDA\u6240\u6709\u4FEE\u6539","main.notice.mobileNoAgent":"\u79FB\u52A8\u7AEF\u6682\u4E0D\u652F\u6301 Agent \u6267\u884C\uFF0C\u8BF7\u4F7F\u7528\u300C\u590D\u5236 Prompt\u300D","main.notice.monitoringChanges":"\u6B63\u5728\u76D1\u542C\u6587\u4EF6\u53D8\u66F4\uFF085 \u5206\u949F\u8D85\u65F6\uFF09\u2026","main.notice.autoHealed":"\u5DF2\u81EA\u52A8\u4FEE\u590D {{n}} \u6761\u6279\u6CE8\u4F4D\u7F6E","main.notice.reviewExecuted":"{{n}} \u6761\u6279\u9605\u610F\u89C1\u5DF2\u6267\u884C\u5E76\u81EA\u52A8\u79FB\u9664","main.notice.invalidReadingRemoved":"{{n}} \u6761\u5931\u6548\u9605\u8BFB\u6279\u6CE8\u5DF2\u81EA\u52A8\u79FB\u9664","main.notice.noChangesDetected":"\u672A\u68C0\u6D4B\u5230\u6587\u4EF6\u53D8\u66F4","main.notice.selectTextFirst":"\u8BF7\u5148\u9009\u4E2D\u8981\u6279\u6CE8\u7684\u6587\u5B57","main.notice.selectReviewTextFirst":"\u8BF7\u5148\u9009\u4E2D\u8981\u6279\u9605\u7684\u6587\u5B57","main.notice.noChangesNeeded":"API \u8FD4\u56DE\u5185\u5BB9\u4E0E\u539F\u6587\u76F8\u540C\uFF0C\u65E0\u9700\u4FEE\u6539","main.notice.cancelledNoChange":"\u5DF2\u53D6\u6D88\uFF0C\u6587\u4EF6\u672A\u4FEE\u6539","main.notice.noOriginalSnapshot":"\u6CA1\u6709\u4FDD\u5B58\u7684\u539F\u6587\u5FEB\u7167","main.notice.ruleNotFound":"\u672A\u627E\u5230\u89C4\u5219: {{id}}","main.notice.noAgentCLI":"\u672A\u68C0\u6D4B\u5230\u5DF2\u5B89\u88C5\u7684 Agent CLI\uFF0C\u8BF7\u5148\u5B89\u88C5 Claude Code / Codex / Aider / Gemini CLI","main.notice.exportSuccess":"\u5BFC\u51FA\u6210\u529F\uFF0C\u6B63\u5728\u6253\u5F00: {{target}}","main.notice.exportFailed":"\u5BFC\u51FA\u5931\u8D25\uFF1A\u672A\u751F\u6210\u6587\u4EF6","main.notice.changeDetected":"\u68C0\u6D4B\u5230\u6587\u4EF6\u53D8\u66F4\uFF0C\u6B63\u5728\u751F\u6210 Diff\u2026","main.notice.monitorTimeout":"\u76D1\u542C\u8D85\u65F6\uFF0C\u672A\u68C0\u6D4B\u5230\u66F4\u591A\u53D8\u66F4","main.notice.commandCopied":"{{label}} \u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","main.notice.configureAPIKey":"\u8BF7\u5728\u8BBE\u7F6E\u9762\u677F\u4E2D\u914D\u7F6E API Key\uFF08\u8BBE\u7F6E \u2192 API Key \u76F4\u8C03\uFF09","main.notice.reviewCleanupDone":"\u5DF2\u6E05\u7406 {{n}} \u6761\u5DF2\u5904\u7406\u6279\u9605","sidebar.empty.openFile":"\u8BF7\u6253\u5F00\u4E00\u4E2A Markdown \u6587\u4EF6","sidebar.mode.reading":"\u9605\u8BFB","sidebar.mode.review":"\u6279\u9605","sidebar.mode.all":"\u5168\u90E8","sidebar.tag.highlight":"\u9AD8\u4EAE","sidebar.tag.note":"\u7B14\u8BB0","sidebar.tag.delete":"\u5220\u9664","sidebar.tag.review":"\u6279\u9605","sidebar.empty.reading":`\u8FD8\u6CA1\u6709\u9605\u8BFB\u6807\u6CE8\u3002 \u9009\u4E2D\u6587\u5B57\u540E\u9009\u62E9\u9AD8\u4EAE\u989C\u8272\u6216\u6DFB\u52A0\u7B14\u8BB0\u3002`,"sidebar.empty.review":`\u8FD8\u6CA1\u6709\u6279\u9605\u610F\u89C1\u3002 -\u5207\u5230\u6279\u9605\u6A21\u5F0F\u540E\u9009\u4E2D\u6587\u5B57\u5199\u4E00\u53E5\u610F\u89C1\u3002`,"sidebar.empty.all":"\u8FD9\u4E2A\u6587\u6863\u8FD8\u6CA1\u6709\u4EFB\u4F55\u6807\u6CE8\u3002","sidebar.status.agentRunning":"Agent \u6279\u9605\u4E2D\u2026","sidebar.status.apiRunning":"API \u6279\u9605\u4E2D\u2026","sidebar.status.pendingReview":"{{n}} \u6761\u6279\u9605\u5F85\u6267\u884C","sidebar.card.ambiguous":"\u4F4D\u7F6E\u6B67\u4E49","sidebar.card.autoHealed":"\u5DF2\u81EA\u52A8\u4FEE\u590D","sidebar.card.drifted":"\u5DF2\u6F02\u79FB","sidebar.card.delete":"\u5220\u9664","sidebar.notice.cannotLocate":"\u65E0\u6CD5\u5B9A\u4F4D\u8BE5\u6279\u6CE8\uFF0C\u53EF\u80FD\u5DF2\u6F02\u79FB","sidebar.banner.drifted":"{{n}} \u6761\u5DF2\u6F02\u79FB","sidebar.banner.ambiguous":"{{n}} \u6761\u4F4D\u7F6E\u5B58\u5728\u6B67\u4E49","sidebar.banner.changed":"\u539F\u6587\u53D8\u66F4\u540E\u6709\u2026","sidebar.banner.changedFull":"\u539F\u6587\u5DF2\u53D8\u66F4\uFF0C\u8BF7\u68C0\u67E5\u6279\u6CE8","sidebar.banner.confirmAll":"\u5168\u90E8\u786E\u8BA4","sidebar.banner.baselineUpdated":"baseline \u5DF2\u66F4\u65B0","sidebar.notice.autoHealed":"\u5DF2\u81EA\u52A8\u4FEE\u590D {{n}} \u6761\u6279\u6CE8\u4F4D\u7F6E","sidebar.notice.reviewAutoRemoved":"{{n}} \u6761\u6279\u9605\u610F\u89C1\u5DF2\u81EA\u52A8\u79FB\u9664","sidebar.notice.invalidReadingRemoved":"{{n}} \u6761\u5931\u6548\u9605\u8BFB\u6279\u6CE8\u5DF2\u81EA\u52A8\u79FB\u9664","sidebar.notice.ambiguousCheck":"{{n}} \u6761\u4F4D\u7F6E\u5B58\u5728\u6B67\u4E49\uFF0C\u9700\u68C0\u67E5","sidebar.cleanup.title":"Agent \u5DF2\u8FD4\u56DE\u4FEE\u6539","sidebar.cleanup.desc":"\u662F\u5426\u6E05\u7406\u672C\u8F6E\u5DF2\u5904\u7406\u7684 {{n}} \u6761\u6279\u9605\uFF1F","sidebar.cleanup.clean":"\u6E05\u7406","sidebar.cleanup.keep":"\u4FDD\u7559","popover.mode.reading":"\u9605\u8BFB","popover.mode.review":"\u6279\u9605","popover.title.edit":"\u7F16\u8F91\u8BB0\u5F55","popover.title.add":"\u6DFB\u52A0\u8BB0\u5F55","popover.btn.addNote":"Add Note","popover.btn.addNoteTitle":"\u6DFB\u52A0\u7B14\u8BB0","popover.btn.delete":"Delete","popover.btn.deleteTitle":"\u6807\u8BB0\u4E3A\u5220\u9664","popover.btn.reviewNote":"Add Note","popover.btn.reviewNoteTitle":"\u6DFB\u52A0\u6279\u9605\u610F\u89C1","popover.btn.confirmDelete":"\u786E\u8BA4\u5220\u9664","popover.color.highlight":"{{color}} \u9AD8\u4EAE","popover.placeholder.review":"\u8F93\u5165\u6279\u9605\u610F\u89C1\uFF0CAI \u4F1A\u63A8\u65AD\u8981\u600E\u4E48\u6539\u2026","popover.placeholder.note":"\u4E3A\u8FD9\u6BB5\u9AD8\u4EAE\u6DFB\u52A0\u7B14\u8BB0\u2026","popover.label.review":"\u6279\u9605","popover.label.note":"\u7B14\u8BB0","popover.btn.save":"Save","popover.btn.saveTitle":"\u4FDD\u5B58","toolbar.mode.reading":"\u9605\u8BFB","toolbar.mode.review":"\u6279\u9605","toolbar.label.review":"\u6279\u9605","toolbar.label.note":"\u7B14\u8BB0","toolbar.label.delete":"\u5220\u9664","toolbar.btn.addNote":"Add Note","toolbar.btn.addNoteTitle":"\u6DFB\u52A0\u7B14\u8BB0","toolbar.btn.delete":"Delete","toolbar.btn.deleteTitle":"\u6807\u8BB0\u4E3A\u5220\u9664","toolbar.btn.reviewNote":"Add Note","toolbar.btn.reviewNoteTitle":"\u6DFB\u52A0\u6279\u9605\u610F\u89C1","toolbar.btn.confirmDelete":"\u786E\u8BA4\u5220\u9664","toolbar.color.highlight":"{{color}} \u9AD8\u4EAE","toolbar.placeholder.review":"\u8F93\u5165\u6279\u9605\u610F\u89C1\u2026","toolbar.placeholder.note":"\u4E3A\u8FD9\u6BB5\u9AD8\u4EAE\u6DFB\u52A0\u7B14\u8BB0\u2026","toolbar.btn.save":"Save","notemodal.note.title":"\u8BB0\u5F55\u7B14\u8BB0","notemodal.note.content":"\u5185\u5BB9","notemodal.review.title":"\u6DFB\u52A0\u6279\u9605\u610F\u89C1","notemodal.review.content":"\u610F\u89C1","notemodal.review.strikethrough":"\u6807\u8BB0\u4E3A\u5220\u9664\u7EBF","notemodal.review.strikethroughDesc":"\u8868\u8FBE\u5F3A\u5220\u9664/\u5408\u5E76\u610F\u56FE\uFF0C\u6700\u7EC8\u7531 AI \u7ED3\u5408\u4E0A\u4E0B\u6587\u5224\u65AD\u3002","notemodal.btn.cancel":"\u53D6\u6D88","notemodal.btn.save":"\u4FDD\u5B58","settings.section.basic":"\u57FA\u7840\u8BBE\u7F6E","settings.section.basicDesc":"\u6279\u6CE8\u5B58\u50A8\u3001\u5BFC\u51FA\u8DEF\u5F84\u4E0E\u9ED8\u8BA4\u6A21\u5F0F","settings.section.agent":"Agent \u4E0E\u7EC8\u7AEF","settings.section.agentDesc":"CLI Agent \u68C0\u6D4B\u3001\u547D\u4EE4\u89C4\u5219\u4E0E\u7EC8\u7AEF\u914D\u7F6E","settings.section.api":"API \u76F4\u8C03","settings.section.apiDesc":"\u914D\u7F6E API Key \u540E\u65E0\u9700\u5B89\u88C5 CLI\uFF0C\u76F4\u63A5\u5728\u63D2\u4EF6\u5185\u8C03\u7528\u6A21\u578B","settings.language.name":"\u754C\u9762\u8BED\u8A00","settings.language.desc":"\u66F4\u6539\u540E\u5C06\u91CD\u65B0\u52A0\u8F7D\u63D2\u4EF6\u4EE5\u5E94\u7528\u65B0\u8BED\u8A00","settings.language.auto":"\u8DDF\u968F\u7CFB\u7EDF","settings.language.zhCN":"\u7B80\u4F53\u4E2D\u6587","settings.language.en":"English","settings.defaultMode.name":"\u9ED8\u8BA4\u6A21\u5F0F","settings.defaultMode.desc":"\u6253\u5F00\u6587\u6863\u65F6\u7684\u9ED8\u8BA4\u6279\u6CE8\u6A21\u5F0F","settings.defaultMode.reading":"\u9605\u8BFB","settings.defaultMode.review":"\u6279\u9605","settings.contextSpan.name":"\u4E0A\u4E0B\u6587\u957F\u5EA6","settings.contextSpan.desc":"\u951A\u70B9\u5B9A\u4F4D\u65F6\u622A\u53D6\u7684\u4E0A\u4E0B\u6587\u5B57\u7B26\u6570\uFF08\u8D8A\u5927\u8D8A\u7CBE\u786E\uFF0C\u4F46\u5360\u66F4\u591A token\uFF09","settings.sidecarDir.name":"\u6279\u6CE8\u5B58\u50A8\u76EE\u5F55","settings.sidecarDir.desc":"\u76F8\u5BF9\u4E8E Vault \u6839\u76EE\u5F55\uFF0C\u4EE5 . \u5F00\u5934\u7684\u76EE\u5F55\u4E3A\u9690\u85CF\u76EE\u5F55","settings.exportDir.name":"\u5BFC\u51FA\u76EE\u5F55","settings.exportDir.desc":"\u6279\u9605\u6587\u4EF6\u5BFC\u51FA\u8DEF\u5F84\uFF0C\u76F8\u5BF9\u4E8E Vault \u6839\u76EE\u5F55","settings.includeReadingNotes.name":"\u5BFC\u51FA\u5305\u542B\u9605\u8BFB\u7B14\u8BB0","settings.includeReadingNotes.desc":"\u5BFC\u51FA\u6279\u9605\u6587\u4EF6\u65F6\u540C\u65F6\u5305\u542B\u9605\u8BFB\u6A21\u5F0F\u7684\u7B14\u8BB0\u548C\u9AD8\u4EAE","settings.terminalApp.name":"\u7EC8\u7AEF\u5E94\u7528","settings.terminalApp.desc":"\u6267\u884C Agent \u547D\u4EE4\u65F6\u4F7F\u7528\u7684\u7EC8\u7AEF","settings.terminalApp.terminal":"Terminal","settings.terminalApp.iterm":"iTerm2","settings.terminalApp.defaultSuffix":"\uFF08\u9ED8\u8BA4\uFF09","settings.detectedAgents.name":"\u5DF2\u68C0\u6D4B\u5230\u7684 Agent","settings.detectedAgents.desc":"\u81EA\u52A8\u68C0\u6D4B\u7CFB\u7EDF\u4E2D\u5DF2\u5B89\u88C5\u7684 CLI Agent","settings.detectedAgents.installed":"\u5DF2\u5B89\u88C5","settings.detectedAgents.notFound":"\u672A\u68C0\u6D4B\u5230\u4EFB\u4F55 Agent CLI\uFF0C\u53EF\u5B89\u88C5\u540E\u91CD\u542F Obsidian","settings.commandRules.name":"\u547D\u4EE4\u89C4\u5219","settings.commandRules.desc":"\u9884\u8BBE\u548C\u81EA\u5B9A\u4E49 Agent CLI \u547D\u4EE4\u6A21\u677F","settings.commandRules.addRule":"\u6DFB\u52A0\u547D\u4EE4\u89C4\u5219","settings.commandRules.editRule":"\u7F16\u8F91\u89C4\u5219","settings.commandRules.deleteRule":"\u5220\u9664\u89C4\u5219","settings.api.provider.name":"API Provider","settings.api.provider.desc":"\u9009\u62E9\u6A21\u578B\u63D0\u4F9B\u5546","settings.api.provider.anthropic":"Anthropic","settings.api.provider.openai":"OpenAI","settings.api.provider.deepseek":"DeepSeek","settings.api.provider.custom":"\u81EA\u5B9A\u4E49\u7AEF\u70B9","settings.api.key.name":"API Key","settings.api.key.desc":"\u5BC6\u94A5\u4EC5\u5B58\u50A8\u5728\u672C\u5730\uFF0C\u4E0D\u4F1A\u53D1\u9001\u5230\u7B2C\u4E09\u65B9\u670D\u52A1","settings.api.key.placeholder":"sk-\u2026","settings.api.model.name":"\u6A21\u578B","settings.api.model.desc":"\u7559\u7A7A\u5219\u4F7F\u7528 Provider \u9ED8\u8BA4\u6A21\u578B","settings.api.model.placeholder":"claude-sonnet-4-20250514","settings.api.customEndpoint.name":"\u81EA\u5B9A\u4E49\u7AEF\u70B9","settings.api.customEndpoint.desc":"\u4EC5\u5728\u9009\u62E9\u300C\u81EA\u5B9A\u4E49\u7AEF\u70B9\u300D\u65F6\u751F\u6548","settings.api.customEndpoint.placeholder":"https://api.example.com/v1/chat/completions","settings.api.maxTokens.name":"\u6700\u5927\u8F93\u51FA Tokens","settings.api.maxTokens.desc":"\u6A21\u578B\u8FD4\u56DE\u7684\u6700\u5927 token \u6570","settings.api.test.name":"\u6D4B\u8BD5\u8FDE\u63A5","settings.api.test.desc":"\u53D1\u9001\u4E00\u4E2A\u7B80\u77ED\u8BF7\u6C42\u9A8C\u8BC1 API Key \u548C\u7AEF\u70B9\u662F\u5426\u53EF\u7528","settings.api.test.running":"\u6D4B\u8BD5\u4E2D\u2026","settings.api.test.success":"\u8FDE\u63A5\u6210\u529F\uFF01\u6A21\u578B: {{model}}","settings.api.test.failed":"\u8FDE\u63A5\u5931\u8D25: {{error}}","addrule.title":"\u6DFB\u52A0\u547D\u4EE4\u89C4\u5219","addrule.subtitle":"\u81EA\u5B9A\u4E49 Agent CLI \u547D\u4EE4\u6A21\u677F","addrule.id.name":"\u89C4\u5219 ID","addrule.id.desc":"\u552F\u4E00\u6807\u8BC6\u7B26\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26","addrule.id.placeholder":"my-agent","addrule.detectCmd.name":"\u68C0\u6D4B\u547D\u4EE4","addrule.detectCmd.desc":"\u7528\u4E8E\u5224\u65AD\u8BE5 Agent \u662F\u5426\u5DF2\u5B89\u88C5\u7684 shell \u547D\u4EE4","addrule.detectCmd.placeholder":"which my-agent","addrule.label.name":"\u663E\u793A\u540D\u79F0","addrule.label.desc":"\u5728\u4FA7\u8FB9\u680F\u548C\u547D\u4EE4\u9762\u677F\u4E2D\u663E\u793A\u7684\u540D\u79F0","addrule.label.placeholder":"My Agent","addrule.command.name":"\u547D\u4EE4\u6A21\u677F","addrule.command.desc":"\u53EF\u7528\u53D8\u91CF: {{instructionFile}} (\u6307\u4EE4\u6587\u4EF6\u8DEF\u5F84), {{targetFile}} (\u76EE\u6807\u6587\u4EF6\u8DEF\u5F84)","addrule.command.placeholder":"my-agent --file {{targetFile}} < {{instructionFile}}","addrule.installHint.name":"\u5B89\u88C5\u63D0\u793A","addrule.installHint.desc":"\u672A\u5B89\u88C5\u65F6\u663E\u793A\u7684\u5B89\u88C5\u547D\u4EE4\uFF08\u53EF\u9009\uFF09","addrule.installHint.placeholder":"npm i -g my-agent","addrule.instruction.name":"\u6307\u4EE4\u524D\u7F00","addrule.instruction.desc":"\u9644\u52A0\u5728\u6307\u4EE4\u6587\u4EF6\u5F00\u5934\u7684\u63D0\u793A\u8BED","addrule.instruction.placeholder":"\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6","addrule.defaultInstallHint":"\u81EA\u5B9A\u4E49\u5B89\u88C5\u65B9\u5F0F","addrule.varTitle":"\u53EF\u7528\u6A21\u677F\u53D8\u91CF","addrule.var.vaultPath":"Vault \u6839\u76EE\u5F55","addrule.var.instructionFile":"\u6307\u4EE4\u6587\u4EF6\u8DEF\u5F84","addrule.var.filePath":"\u6587\u4EF6\u76F8\u5BF9\u8DEF\u5F84","addrule.var.fileName":"\u6587\u4EF6\u540D","addrule.var.prompt":"\u5185\u8054 Prompt","addrule.btn.cancel":"\u53D6\u6D88","addrule.btn.add":"\u6DFB\u52A0\u89C4\u5219","addrule.notice.idExists":'\u89C4\u5219 ID "{{id}}" \u5DF2\u5B58\u5728',"addrule.notice.idEmpty":"\u8BF7\u8F93\u5165\u89C4\u5219 ID","addrule.notice.labelEmpty":"\u8BF7\u8F93\u5165\u663E\u793A\u540D\u79F0","addrule.notice.commandEmpty":"\u8BF7\u8F93\u5165\u547D\u4EE4\u6A21\u677F","addrule.notice.requiredFields":"\u8BF7\u586B\u5199\u6240\u6709\u5FC5\u586B\u5B57\u6BB5","addrule.notice.validationFailed":"\u9A8C\u8BC1\u5931\u8D25: {{error}}","settings.agentInstall":"\u5B89\u88C5\uFF1A","settings.redetectAgent.name":"\u91CD\u65B0\u68C0\u6D4B Agent","settings.redetectAgent.desc":"\u91CD\u65B0\u626B\u63CF\u5DF2\u5B89\u88C5\u7684 Agent CLI","settings.redetectAgent.btn":"\u68C0\u6D4B","settings.redetectAgent.done":"\u68C0\u6D4B\u5B8C\u6210","settings.customRules.title":"\u81EA\u5B9A\u4E49\u547D\u4EE4\u89C4\u5219","settings.customRules.added":'\u89C4\u5219 "{{label}}" \u5DF2\u6DFB\u52A0',"settings.customRules.addFailed":"\u6DFB\u52A0\u5931\u8D25: {{error}}","settings.customRules.empty":"\u6682\u65E0\u81EA\u5B9A\u4E49\u89C4\u5219\uFF0C\u70B9\u51FB\u4E0A\u65B9\u300C+ \u6DFB\u52A0\u300D\u6309\u94AE\u521B\u5EFA\u3002","settings.varRef.title":"\u53EF\u7528\u6A21\u677F\u53D8\u91CF\u53C2\u8003","settings.varRef.vaultPath":"Vault \u6839\u76EE\u5F55\u7EDD\u5BF9\u8DEF\u5F84","settings.varRef.instructionFile":"\u751F\u6210\u7684\u6279\u6CE8\u6307\u4EE4\u6587\u4EF6\u8DEF\u5F84","settings.varRef.filePath":"\u5F53\u524D\u6587\u4EF6\u76F8\u5BF9\u8DEF\u5F84","settings.varRef.fileName":"\u5F53\u524D\u6587\u4EF6\u540D","settings.varRef.prompt":"\u5185\u8054 prompt \u6587\u672C","settings.ruleCard.detect":"\u68C0\u6D4B","settings.ruleCard.template":"\u6A21\u677F","settings.api.test.btn":"\u6D4B\u8BD5","settings.api.test.noKey":"\u8BF7\u5148\u586B\u5199 API Key","export.reviewTitle":"AI \u6279\u9605\u6307\u4EE4","export.originalFile":"\u539F\u6587\u4EF6","export.exportTime":"\u5BFC\u51FA\u65F6\u95F4","export.reviewCount":"\u6279\u9605\u6570\u91CF","export.includeReading":"\u9644\u5E26\u9605\u8BFB\u7B14\u8BB0","export.yes":"\u662F","export.no":"\u5426","export.reviewSection":"\u6279\u9605\u610F\u89C1","export.strikethrough":"\u5220\u9664\u7EBF","export.original":"\u539F\u6587","export.context":"\u4E0A\u4E0B\u6587","export.opinion":"\u610F\u89C1","export.execRequirement":"\u6267\u884C\u8981\u6C42","export.execRequirementText":"\u8BF7\u6839\u636E\u4EE5\u4E0A\u6279\u9605\u610F\u89C1\u4FEE\u6539\u539F\u6587\u4EF6\u3002\u6BCF\u6761\u610F\u89C1\u5BF9\u5E94\u539F\u6587\u4E2D\u7684\u4E00\u6BB5\u6587\u5B57\uFF0C\u8BF7\u9010\u6761\u6267\u884C\u4FEE\u6539\u3002\u5220\u9664\u7EBF\u8868\u793A\u9700\u8981\u5220\u9664\u8BE5\u6BB5\u6587\u5B57\uFF0C\u5176\u4ED6\u610F\u89C1\u8BF7\u6839\u636E\u4E0A\u4E0B\u6587\u7406\u89E3\u610F\u56FE\u5E76\u6267\u884C\u4FEE\u6539\u3002\u4FEE\u6539\u5B8C\u6210\u540E\u8BF7\u8F93\u51FA\u5B8C\u6574\u7684\u4FEE\u6539\u540E\u6587\u4EF6\u5185\u5BB9\u3002","export.promptHeader":"\u8BF7\u6839\u636E\u4EE5\u4E0B\u6279\u9605\u610F\u89C1\u4FEE\u6539\u6307\u5B9A\u6587\u4EF6\uFF1A","export.promptFile":"\u6587\u4EF6\uFF1A{{path}}","export.promptReviews":"\u6279\u9605\u610F\u89C1\uFF1A","export.promptFooter":"\u8BF7\u9010\u6761\u6267\u884C\u4E0A\u8FF0\u4FEE\u6539\uFF0C\u8F93\u51FA\u5B8C\u6574\u7684\u4FEE\u6539\u540E\u6587\u4EF6\u3002","export.notice.fileNotFound":"\u627E\u4E0D\u5230\u539F\u6587\u4EF6","export.notice.exportedTokens":"\u5DF2\u5BFC\u51FA\uFF08\u7EA6 {{n}} tokens\uFF09","export.notice.promptCopied":"Prompt \u5DF2\u590D\u5236\uFF08\u7EA6 {{n}} tokens\uFF09","agent.confirm.title":"\u786E\u8BA4\u6267\u884C","agent.confirm.subtitle":"{{label}} \xB7 \u5373\u5C06\u5728\u7EC8\u7AEF\u4E2D\u8FD0\u884C","agent.confirm.warning":"\u8BF7\u4ED4\u7EC6\u68C0\u67E5\u547D\u4EE4\u5185\u5BB9\uFF0C\u786E\u8BA4\u540E\u5C06\u5728\u7EC8\u7AEF\u4E2D\u6267\u884C\u3002Agent \u5C06\u76F4\u63A5\u4FEE\u6539\u78C1\u76D8\u4E0A\u7684\u6587\u4EF6\u3002","agent.confirm.instructionFile":"\u6307\u4EE4\u6587\u4EF6: {{path}}","agent.confirm.commandLabel":"\u547D\u4EE4","agent.confirm.installed":"\u5DF2\u5B89\u88C5","agent.confirm.btn.cancel":"\u53D6\u6D88","agent.confirm.btn.copyCommand":"\u590D\u5236\u547D\u4EE4","agent.confirm.btn.execute":"\u6267\u884C","agent.confirm.notice.copied":"\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","agent.select.title":"\u9009\u62E9 Agent","agent.select.subtitle":"\u9009\u62E9\u4E00\u4E2A AI Agent \u6765\u6267\u884C\u7F16\u8F91","agent.select.installed":"\u5DF2\u5B89\u88C5","agent.select.missing":"\u672A\u5B89\u88C5","agent.select.addCustom":"+ \u914D\u7F6E\u81EA\u5B9A\u4E49 Agent","agent.select.btn.confirm":"\u786E\u8BA4","diff.title":"Diff \u9884\u89C8","diff.subtitle":"{{file}} \u2014 {{n}} \u5904\u53D8\u66F4","diff.noChanges":"\u672A\u68C0\u6D4B\u5230\u53D8\u66F4\u3002","diff.changesLabel":"\u53D8\u66F4\u5185\u5BB9\uFF1A","diff.btn.rollbackAll":"\u5168\u90E8\u56DE\u6EDA","diff.btn.applySelected":"\u5E94\u7528\u9009\u4E2D","diff.btn.reject":"\u62D2\u7EDD","diff.btn.accept":"\u63A5\u53D7","diff.hunks":"\u4E2A\u53D8\u66F4","api.execute.title":"API \u6279\u9605\u786E\u8BA4","api.execute.subtitle":"\u5373\u5C06\u53D1\u9001\u81F3 API","api.execute.provider":"Provider","api.execute.model":"Model","api.execute.reviews":"Reviews","api.execute.reviewCount":"{{n}} \u6761\u6279\u9605","api.execute.tokens":"Tokens","api.execute.warning":"\u539F\u6587\u4E0E\u6279\u9605\u610F\u89C1\u5C06\u53D1\u9001\u81F3\u6240\u9009 Provider\uFF0C\u8BF7\u786E\u8BA4\u4E0D\u542B\u654F\u611F\u4FE1\u606F\u3002\u6570\u636E\u5C06\u79BB\u5F00\u672C\u5730 Vault\u3002","api.execute.btn.cancel":"\u53D6\u6D88","api.execute.btn.confirm":"\u786E\u8BA4\u6267\u884C","api.progress.title":"API \u6279\u9605\u4E2D\u2026","api.progress.subtitle":"\u6B63\u5728\u8C03\u7528 API","api.progress.calling":"\u6B63\u5728\u8C03\u7528 API\uFF0C\u8BF7\u7A0D\u5019\u2026","api.progress.failed":"\u8C03\u7528\u5931\u8D25\uFF1A{{error}}","api.progress.success":"API \u8FD4\u56DE\u6210\u529F\uFF0C\u5373\u5C06\u6253\u5F00 Diff \u9884\u89C8","api.progress.btn.close":"\u5173\u95ED","api.progress.btn.viewDiff":"\u67E5\u770B Diff","api.progress.cancelled":"API \u8C03\u7528\u5DF2\u53D6\u6D88","cmdrule.error.idExists":'\u89C4\u5219 ID "{{id}}" \u5DF2\u5B58\u5728',"cmdrule.error.presetNotEditable":"\u9884\u8BBE\u89C4\u5219\u4E0D\u53EF\u7F16\u8F91","cmdrule.error.notFound":'\u81EA\u5B9A\u4E49\u89C4\u5219 "{{id}}" \u4E0D\u5B58\u5728',"cmdrule.error.presetNotDeletable":"\u9884\u8BBE\u89C4\u5219\u4E0D\u53EF\u5220\u9664","terminal.notice.copied":"\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","terminal.notice.copiedWin":"\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF08Windows \u6682\u4E0D\u652F\u6301\u4E00\u952E\u6267\u884C\uFF09","terminal.notice.copiedLinux":"\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF08Linux \u6682\u4E0D\u652F\u6301\u4E00\u952E\u6267\u884C\uFF09","terminal.notice.launched":"\u5DF2\u901A\u8FC7 {{app}} \u6267\u884C\u547D\u4EE4","terminal.notice.launchFailed":"\u7EC8\u7AEF\u542F\u52A8\u5931\u8D25\uFF0C\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","folder.notice.mobileNotSupported":"\u79FB\u52A8\u7AEF\u4E0D\u652F\u6301\u6253\u5F00\u672C\u5730\u6587\u4EF6\u5939","folder.notice.cannotResolveFile":"\u65E0\u6CD5\u89E3\u6790\u6587\u4EF6\u7EDD\u5BF9\u8DEF\u5F84","folder.notice.cannotResolveFolder":"\u65E0\u6CD5\u89E3\u6790\u6587\u4EF6\u5939\u7EDD\u5BF9\u8DEF\u5F84","folder.notice.openFailed":"\u6253\u5F00\u6587\u4EF6\u5939\u5931\u8D25: {{error}}","shell.error.forbiddenChar":"\u547D\u4EE4\u6A21\u677F\u5305\u542B\u7981\u7528\u5B57\u7B26: {{chars}}","shell.error.unknownVariable":"\u672A\u77E5\u6A21\u677F\u53D8\u91CF: {{var}}","common.cancel":"\u53D6\u6D88","common.save":"\u4FDD\u5B58","common.delete":"\u5220\u9664","common.confirm":"\u786E\u8BA4","common.close":"\u5173\u95ED","common.yes":"\u662F","common.no":"\u5426","common.add":"\u6DFB\u52A0","common.edit":"\u7F16\u8F91","common.loading":"\u52A0\u8F7D\u4E2D\u2026","common.error":"\u9519\u8BEF","common.success":"\u6210\u529F","common.warning":"\u8B66\u544A","color.yellow":"\u9EC4\u8272","color.green":"\u7EFF\u8272","color.blue":"\u84DD\u8272","color.pink":"\u7C89\u8272","color.orange":"\u6A59\u8272","sidebar.action.agentTitle":"\u9009\u62E9 Agent CLI \u6267\u884C\u6279\u9605\u4FEE\u6539","sidebar.action.agentReview":"Agent \u6279\u9605","sidebar.action.apiTitle":"\u901A\u8FC7 API \u76F4\u8C03\u6267\u884C\u6279\u9605\u4FEE\u6539","sidebar.action.noApiKey":"\u8BF7\u5148\u5728\u8BBE\u7F6E\u4E2D\u914D\u7F6E API Key","sidebar.action.copy":"\u590D\u5236","sidebar.action.copyTitle":"\u590D\u5236\u6279\u9605 Prompt \u5230\u526A\u8D34\u677F","sidebar.action.exportTitle":"\u5BFC\u51FA\u6279\u6CE8\u6587\u4EF6","sidebar.action.exportFile":"\u5BFC\u51FA\u6279\u6CE8\u6587\u4EF6","export.none":"\uFF08\u65E0\uFF09"},dt=nn;var rn={"main.ribbonTooltip":"Promptuary Sidebar","main.cmd.openSidebar":"Open sidebar","main.cmd.highlightYellow":"Highlight (Yellow)","main.cmd.highlightGreen":"Highlight (Green)","main.cmd.highlightBlue":"Highlight (Blue)","main.cmd.highlightPink":"Highlight (Pink)","main.cmd.highlightOrange":"Highlight (Orange)","main.cmd.addNote":"Add note","main.cmd.addReview":"Add review comment","main.cmd.exportReview":"Export review file","main.cmd.copyPrompt":"Copy Prompt","main.cmd.apiExecute":"API Key direct execute","main.cmd.runAgent":"Execute with {{label}}","main.cmd.copyAgentCommand":"Copy Agent command","main.notice.openMdFile":"Please open a Markdown file first","main.notice.noReviewAnnotations":"No review comments in this file","main.notice.allAccepted":"All changes accepted","main.notice.selectedApplied":"Selected changes applied","main.notice.allRolledBack":"All changes rolled back","main.notice.mobileNoAgent":'Agent execution is not supported on mobile. Please use "Copy Prompt"',"main.notice.monitoringChanges":"Monitoring file changes (5 min timeout)\u2026","main.notice.autoHealed":"Auto-healed {{n}} annotation positions","main.notice.reviewExecuted":"{{n}} review comments executed and removed","main.notice.invalidReadingRemoved":"{{n}} invalid reading annotations removed","main.notice.noChangesDetected":"No file changes detected","main.notice.selectTextFirst":"Please select text to annotate first","main.notice.selectReviewTextFirst":"Please select text to review first","main.notice.noChangesNeeded":"API returned content identical to original, no changes needed","main.notice.cancelledNoChange":"Cancelled, file unchanged","main.notice.noOriginalSnapshot":"No saved original text snapshot","main.notice.ruleNotFound":"Rule not found: {{id}}","main.notice.noAgentCLI":"No Agent CLI detected. Please install Claude Code / Codex / Aider / Gemini CLI first","main.notice.exportSuccess":"Exported successfully, opening: {{target}}","main.notice.exportFailed":"Export failed: no file generated","main.notice.changeDetected":"File change detected, generating diff\u2026","main.notice.monitorTimeout":"Monitor timeout, no further changes detected","main.notice.commandCopied":"{{label}} command copied to clipboard","main.notice.configureAPIKey":"Please configure API Key in Settings \u2192 API Direct Call","main.notice.reviewCleanupDone":"Cleaned {{n}} processed review comment(s)","sidebar.empty.openFile":"Please open a Markdown file","sidebar.mode.reading":"Reading","sidebar.mode.review":"Review","sidebar.mode.all":"All","sidebar.tag.highlight":"Highlight","sidebar.tag.note":"Note","sidebar.tag.delete":"Delete","sidebar.tag.review":"Review","sidebar.empty.reading":`No reading annotations yet. +\u5207\u5230\u6279\u9605\u6A21\u5F0F\u540E\u9009\u4E2D\u6587\u5B57\u5199\u4E00\u53E5\u610F\u89C1\u3002`,"sidebar.empty.all":"\u8FD9\u4E2A\u6587\u6863\u8FD8\u6CA1\u6709\u4EFB\u4F55\u6807\u6CE8\u3002","sidebar.status.agentRunning":"Agent \u6279\u9605\u4E2D\u2026","sidebar.status.apiRunning":"API \u6279\u9605\u4E2D\u2026","sidebar.status.pendingReview":"{{n}} \u6761\u6279\u9605\u5F85\u6267\u884C","sidebar.card.ambiguous":"\u4F4D\u7F6E\u6B67\u4E49","sidebar.card.autoHealed":"\u5DF2\u81EA\u52A8\u4FEE\u590D","sidebar.card.drifted":"\u5DF2\u6F02\u79FB","sidebar.card.delete":"\u5220\u9664","sidebar.notice.cannotLocate":"\u65E0\u6CD5\u5B9A\u4F4D\u8BE5\u6279\u6CE8\uFF0C\u53EF\u80FD\u5DF2\u6F02\u79FB","sidebar.banner.drifted":"{{n}} \u6761\u5DF2\u6F02\u79FB","sidebar.banner.ambiguous":"{{n}} \u6761\u4F4D\u7F6E\u5B58\u5728\u6B67\u4E49","sidebar.banner.changed":"\u539F\u6587\u53D8\u66F4\u540E\u6709\u2026","sidebar.banner.changedFull":"\u539F\u6587\u5DF2\u53D8\u66F4\uFF0C\u8BF7\u68C0\u67E5\u6279\u6CE8","sidebar.banner.confirmAll":"\u5168\u90E8\u786E\u8BA4","sidebar.banner.baselineUpdated":"baseline \u5DF2\u66F4\u65B0","sidebar.notice.autoHealed":"\u5DF2\u81EA\u52A8\u4FEE\u590D {{n}} \u6761\u6279\u6CE8\u4F4D\u7F6E","sidebar.notice.reviewAutoRemoved":"{{n}} \u6761\u6279\u9605\u610F\u89C1\u5DF2\u81EA\u52A8\u79FB\u9664","sidebar.notice.invalidReadingRemoved":"{{n}} \u6761\u5931\u6548\u9605\u8BFB\u6279\u6CE8\u5DF2\u81EA\u52A8\u79FB\u9664","sidebar.notice.ambiguousCheck":"{{n}} \u6761\u4F4D\u7F6E\u5B58\u5728\u6B67\u4E49\uFF0C\u9700\u68C0\u67E5","sidebar.cleanup.title":"Agent \u5DF2\u8FD4\u56DE\u4FEE\u6539","sidebar.cleanup.desc":"\u662F\u5426\u6E05\u7406\u672C\u8F6E\u5DF2\u5904\u7406\u7684 {{n}} \u6761\u6279\u9605\uFF1F","sidebar.cleanup.clean":"\u6E05\u7406","sidebar.cleanup.keep":"\u4FDD\u7559","popover.mode.reading":"\u9605\u8BFB","popover.mode.review":"\u6279\u9605","popover.title.edit":"\u7F16\u8F91\u8BB0\u5F55","popover.title.add":"\u6DFB\u52A0\u8BB0\u5F55","popover.btn.addNote":"Add Note","popover.btn.addNoteTitle":"\u6DFB\u52A0\u7B14\u8BB0","popover.btn.delete":"Delete","popover.btn.deleteTitle":"\u6807\u8BB0\u4E3A\u5220\u9664","popover.btn.reviewNote":"Add Note","popover.btn.reviewNoteTitle":"\u6DFB\u52A0\u6279\u9605\u610F\u89C1","popover.btn.confirmDelete":"\u786E\u8BA4\u5220\u9664","popover.color.highlight":"{{color}} \u9AD8\u4EAE","popover.placeholder.review":"\u8F93\u5165\u6279\u9605\u610F\u89C1\uFF0CAI \u4F1A\u63A8\u65AD\u8981\u600E\u4E48\u6539\u2026","popover.placeholder.note":"\u4E3A\u8FD9\u6BB5\u9AD8\u4EAE\u6DFB\u52A0\u7B14\u8BB0\u2026","popover.label.review":"\u6279\u9605","popover.label.note":"\u7B14\u8BB0","popover.btn.save":"Save","popover.btn.saveTitle":"\u4FDD\u5B58","toolbar.mode.reading":"\u9605\u8BFB","toolbar.mode.review":"\u6279\u9605","toolbar.label.review":"\u6279\u9605","toolbar.label.note":"\u7B14\u8BB0","toolbar.label.delete":"\u5220\u9664","toolbar.btn.addNote":"Add Note","toolbar.btn.addNoteTitle":"\u6DFB\u52A0\u7B14\u8BB0","toolbar.btn.delete":"Delete","toolbar.btn.deleteTitle":"\u6807\u8BB0\u4E3A\u5220\u9664","toolbar.btn.reviewNote":"Add Note","toolbar.btn.reviewNoteTitle":"\u6DFB\u52A0\u6279\u9605\u610F\u89C1","toolbar.btn.confirmDelete":"\u786E\u8BA4\u5220\u9664","toolbar.color.highlight":"{{color}} \u9AD8\u4EAE","toolbar.placeholder.review":"\u8F93\u5165\u6279\u9605\u610F\u89C1\u2026","toolbar.placeholder.note":"\u4E3A\u8FD9\u6BB5\u9AD8\u4EAE\u6DFB\u52A0\u7B14\u8BB0\u2026","toolbar.btn.save":"Save","notemodal.note.title":"\u8BB0\u5F55\u7B14\u8BB0","notemodal.note.content":"\u5185\u5BB9","notemodal.review.title":"\u6DFB\u52A0\u6279\u9605\u610F\u89C1","notemodal.review.content":"\u610F\u89C1","notemodal.review.strikethrough":"\u6807\u8BB0\u4E3A\u5220\u9664\u7EBF","notemodal.review.strikethroughDesc":"\u8868\u8FBE\u5F3A\u5220\u9664/\u5408\u5E76\u610F\u56FE\uFF0C\u6700\u7EC8\u7531 AI \u7ED3\u5408\u4E0A\u4E0B\u6587\u5224\u65AD\u3002","notemodal.btn.cancel":"\u53D6\u6D88","notemodal.btn.save":"\u4FDD\u5B58","settings.section.basic":"\u57FA\u7840\u8BBE\u7F6E","settings.section.basicDesc":"\u6279\u6CE8\u5B58\u50A8\u3001\u5BFC\u51FA\u8DEF\u5F84\u4E0E\u9ED8\u8BA4\u6A21\u5F0F","settings.section.agent":"Agent \u4E0E\u7EC8\u7AEF","settings.section.agentDesc":"CLI Agent \u68C0\u6D4B\u3001\u547D\u4EE4\u89C4\u5219\u4E0E\u7EC8\u7AEF\u914D\u7F6E","settings.section.api":"API \u76F4\u8C03","settings.section.apiDesc":"\u914D\u7F6E API Key \u540E\u65E0\u9700\u5B89\u88C5 CLI\uFF0C\u76F4\u63A5\u5728\u63D2\u4EF6\u5185\u8C03\u7528\u6A21\u578B","settings.language.name":"\u754C\u9762\u8BED\u8A00","settings.language.desc":"\u66F4\u6539\u540E\u5C06\u91CD\u65B0\u52A0\u8F7D\u63D2\u4EF6\u4EE5\u5E94\u7528\u65B0\u8BED\u8A00","settings.language.auto":"\u8DDF\u968F\u7CFB\u7EDF","settings.language.zhCN":"\u7B80\u4F53\u4E2D\u6587","settings.language.en":"English","settings.defaultMode.name":"\u9ED8\u8BA4\u6A21\u5F0F","settings.defaultMode.desc":"\u6253\u5F00\u6587\u6863\u65F6\u7684\u9ED8\u8BA4\u6279\u6CE8\u6A21\u5F0F","settings.defaultMode.reading":"\u9605\u8BFB","settings.defaultMode.review":"\u6279\u9605","settings.contextSpan.name":"\u4E0A\u4E0B\u6587\u957F\u5EA6","settings.contextSpan.desc":"\u951A\u70B9\u5B9A\u4F4D\u65F6\u622A\u53D6\u7684\u4E0A\u4E0B\u6587\u5B57\u7B26\u6570\uFF08\u8D8A\u5927\u8D8A\u7CBE\u786E\uFF0C\u4F46\u5360\u66F4\u591A token\uFF09","settings.sidecarDir.name":"\u6279\u6CE8\u5B58\u50A8\u76EE\u5F55","settings.sidecarDir.desc":"\u76F8\u5BF9\u4E8E Vault \u6839\u76EE\u5F55\uFF0C\u4EE5 . \u5F00\u5934\u7684\u76EE\u5F55\u4E3A\u9690\u85CF\u76EE\u5F55","settings.exportDir.name":"\u5BFC\u51FA\u76EE\u5F55","settings.exportDir.desc":"\u6279\u9605\u6587\u4EF6\u5BFC\u51FA\u8DEF\u5F84\uFF0C\u76F8\u5BF9\u4E8E Vault \u6839\u76EE\u5F55","settings.includeReadingNotes.name":"\u5BFC\u51FA\u5305\u542B\u9605\u8BFB\u7B14\u8BB0","settings.includeReadingNotes.desc":"\u5BFC\u51FA\u6279\u9605\u6587\u4EF6\u65F6\u540C\u65F6\u5305\u542B\u9605\u8BFB\u6A21\u5F0F\u7684\u7B14\u8BB0\u548C\u9AD8\u4EAE","settings.terminalApp.name":"\u7EC8\u7AEF\u5E94\u7528","settings.terminalApp.desc":"\u6267\u884C Agent \u547D\u4EE4\u65F6\u4F7F\u7528\u7684\u7EC8\u7AEF","settings.terminalApp.terminal":"Terminal","settings.terminalApp.iterm":"iTerm2","settings.terminalApp.defaultSuffix":"\uFF08\u9ED8\u8BA4\uFF09","settings.detectedAgents.name":"\u5DF2\u68C0\u6D4B\u5230\u7684 Agent","settings.detectedAgents.desc":"\u81EA\u52A8\u68C0\u6D4B\u7CFB\u7EDF\u4E2D\u5DF2\u5B89\u88C5\u7684 CLI Agent","settings.detectedAgents.installed":"\u5DF2\u5B89\u88C5","settings.detectedAgents.notFound":"\u672A\u68C0\u6D4B\u5230\u4EFB\u4F55 Agent CLI\uFF0C\u53EF\u5B89\u88C5\u540E\u91CD\u542F Obsidian","settings.commandRules.name":"\u547D\u4EE4\u89C4\u5219","settings.commandRules.desc":"\u9884\u8BBE\u548C\u81EA\u5B9A\u4E49 Agent CLI \u547D\u4EE4\u6A21\u677F","settings.commandRules.addRule":"\u6DFB\u52A0\u547D\u4EE4\u89C4\u5219","settings.commandRules.editRule":"\u7F16\u8F91\u89C4\u5219","settings.commandRules.deleteRule":"\u5220\u9664\u89C4\u5219","settings.api.provider.name":"API Provider","settings.api.provider.desc":"\u9009\u62E9\u6A21\u578B\u63D0\u4F9B\u5546","settings.api.provider.anthropic":"Anthropic","settings.api.provider.openai":"OpenAI","settings.api.provider.deepseek":"DeepSeek","settings.api.provider.custom":"\u81EA\u5B9A\u4E49\u7AEF\u70B9","settings.api.key.name":"API Key","settings.api.key.desc":"\u5BC6\u94A5\u4EC5\u5B58\u50A8\u5728\u672C\u5730\uFF0C\u4E0D\u4F1A\u53D1\u9001\u5230\u7B2C\u4E09\u65B9\u670D\u52A1","settings.api.key.placeholder":"sk-\u2026","settings.api.model.name":"\u6A21\u578B","settings.api.model.desc":"\u7559\u7A7A\u5219\u4F7F\u7528 Provider \u9ED8\u8BA4\u6A21\u578B","settings.api.model.placeholder":"claude-sonnet-4-20250514","settings.api.customEndpoint.name":"\u81EA\u5B9A\u4E49\u7AEF\u70B9","settings.api.customEndpoint.desc":"\u4EC5\u5728\u9009\u62E9\u300C\u81EA\u5B9A\u4E49\u7AEF\u70B9\u300D\u65F6\u751F\u6548","settings.api.customEndpoint.placeholder":"https://api.example.com/v1/chat/completions","settings.api.maxTokens.name":"\u6700\u5927\u8F93\u51FA Tokens","settings.api.maxTokens.desc":"\u6A21\u578B\u8FD4\u56DE\u7684\u6700\u5927 token \u6570","settings.api.test.name":"\u6D4B\u8BD5\u8FDE\u63A5","settings.api.test.desc":"\u53D1\u9001\u4E00\u4E2A\u7B80\u77ED\u8BF7\u6C42\u9A8C\u8BC1 API Key \u548C\u7AEF\u70B9\u662F\u5426\u53EF\u7528","settings.api.test.running":"\u6D4B\u8BD5\u4E2D\u2026","settings.api.test.success":"\u8FDE\u63A5\u6210\u529F\uFF01\u6A21\u578B: {{model}}","settings.api.test.failed":"\u8FDE\u63A5\u5931\u8D25: {{error}}","addrule.title":"\u6DFB\u52A0\u547D\u4EE4\u89C4\u5219","addrule.subtitle":"\u81EA\u5B9A\u4E49 Agent CLI \u547D\u4EE4\u6A21\u677F","addrule.id.name":"\u89C4\u5219 ID","addrule.id.desc":"\u552F\u4E00\u6807\u8BC6\u7B26\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26","addrule.id.placeholder":"my-agent","addrule.detectCmd.name":"\u68C0\u6D4B\u547D\u4EE4","addrule.detectCmd.desc":"\u7528\u4E8E\u5224\u65AD\u8BE5 Agent \u662F\u5426\u5DF2\u5B89\u88C5\u7684 shell \u547D\u4EE4","addrule.detectCmd.placeholder":"which my-agent","addrule.label.name":"\u663E\u793A\u540D\u79F0","addrule.label.desc":"\u5728\u4FA7\u8FB9\u680F\u548C\u547D\u4EE4\u9762\u677F\u4E2D\u663E\u793A\u7684\u540D\u79F0","addrule.label.placeholder":"My Agent","addrule.command.name":"\u547D\u4EE4\u6A21\u677F","addrule.command.desc":"\u53EF\u7528\u53D8\u91CF: {{instructionFile}} (\u6307\u4EE4\u6587\u4EF6\u8DEF\u5F84), {{targetFile}} (\u76EE\u6807\u6587\u4EF6\u8DEF\u5F84)","addrule.command.placeholder":"my-agent --file {{targetFile}} < {{instructionFile}}","addrule.installHint.name":"\u5B89\u88C5\u63D0\u793A","addrule.installHint.desc":"\u672A\u5B89\u88C5\u65F6\u663E\u793A\u7684\u5B89\u88C5\u547D\u4EE4\uFF08\u53EF\u9009\uFF09","addrule.installHint.placeholder":"npm i -g my-agent","addrule.instruction.name":"\u6307\u4EE4\u524D\u7F00","addrule.instruction.desc":"\u9644\u52A0\u5728\u6307\u4EE4\u6587\u4EF6\u5F00\u5934\u7684\u63D0\u793A\u8BED","addrule.instruction.placeholder":"\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6","addrule.defaultInstallHint":"\u81EA\u5B9A\u4E49\u5B89\u88C5\u65B9\u5F0F","addrule.varTitle":"\u53EF\u7528\u6A21\u677F\u53D8\u91CF","addrule.var.vaultPath":"Vault \u6839\u76EE\u5F55","addrule.var.instructionFile":"\u6307\u4EE4\u6587\u4EF6\u8DEF\u5F84","addrule.var.filePath":"\u6587\u4EF6\u76F8\u5BF9\u8DEF\u5F84","addrule.var.fileName":"\u6587\u4EF6\u540D","addrule.var.prompt":"\u5185\u8054 Prompt","addrule.btn.cancel":"\u53D6\u6D88","addrule.btn.add":"\u6DFB\u52A0\u89C4\u5219","addrule.notice.idExists":'\u89C4\u5219 ID "{{id}}" \u5DF2\u5B58\u5728',"addrule.notice.idEmpty":"\u8BF7\u8F93\u5165\u89C4\u5219 ID","addrule.notice.labelEmpty":"\u8BF7\u8F93\u5165\u663E\u793A\u540D\u79F0","addrule.notice.commandEmpty":"\u8BF7\u8F93\u5165\u547D\u4EE4\u6A21\u677F","addrule.notice.requiredFields":"\u8BF7\u586B\u5199\u6240\u6709\u5FC5\u586B\u5B57\u6BB5","addrule.notice.validationFailed":"\u9A8C\u8BC1\u5931\u8D25: {{error}}","settings.agentInstall":"\u5B89\u88C5\uFF1A","settings.redetectAgent.name":"\u91CD\u65B0\u68C0\u6D4B Agent","settings.redetectAgent.desc":"\u91CD\u65B0\u626B\u63CF\u5DF2\u5B89\u88C5\u7684 Agent CLI","settings.redetectAgent.btn":"\u68C0\u6D4B","settings.redetectAgent.done":"\u68C0\u6D4B\u5B8C\u6210","settings.customRules.title":"\u81EA\u5B9A\u4E49\u547D\u4EE4\u89C4\u5219","settings.customRules.added":'\u89C4\u5219 "{{label}}" \u5DF2\u6DFB\u52A0',"settings.customRules.addFailed":"\u6DFB\u52A0\u5931\u8D25: {{error}}","settings.customRules.empty":"\u6682\u65E0\u81EA\u5B9A\u4E49\u89C4\u5219\uFF0C\u70B9\u51FB\u4E0A\u65B9\u300C+ \u6DFB\u52A0\u300D\u6309\u94AE\u521B\u5EFA\u3002","settings.varRef.title":"\u53EF\u7528\u6A21\u677F\u53D8\u91CF\u53C2\u8003","settings.varRef.vaultPath":"Vault \u6839\u76EE\u5F55\u7EDD\u5BF9\u8DEF\u5F84","settings.varRef.instructionFile":"\u751F\u6210\u7684\u6279\u6CE8\u6307\u4EE4\u6587\u4EF6\u8DEF\u5F84","settings.varRef.filePath":"\u5F53\u524D\u6587\u4EF6\u76F8\u5BF9\u8DEF\u5F84","settings.varRef.fileName":"\u5F53\u524D\u6587\u4EF6\u540D","settings.varRef.prompt":"\u5185\u8054 prompt \u6587\u672C","settings.ruleCard.detect":"\u68C0\u6D4B","settings.ruleCard.template":"\u6A21\u677F","settings.api.test.btn":"\u6D4B\u8BD5","settings.api.test.noKey":"\u8BF7\u5148\u586B\u5199 API Key","export.reviewTitle":"AI \u6279\u9605\u6307\u4EE4","export.originalFile":"\u539F\u6587\u4EF6","export.exportTime":"\u5BFC\u51FA\u65F6\u95F4","export.reviewCount":"\u6279\u9605\u6570\u91CF","export.includeReading":"\u9644\u5E26\u9605\u8BFB\u7B14\u8BB0","export.yes":"\u662F","export.no":"\u5426","export.reviewSection":"\u6279\u9605\u610F\u89C1","export.strikethrough":"\u5220\u9664\u7EBF","export.original":"\u539F\u6587","export.context":"\u4E0A\u4E0B\u6587","export.opinion":"\u610F\u89C1","export.execRequirement":"\u6267\u884C\u8981\u6C42","export.execRequirementText":"\u8BF7\u6839\u636E\u4EE5\u4E0A\u6279\u9605\u610F\u89C1\u4FEE\u6539\u539F\u6587\u4EF6\u3002\u6BCF\u6761\u610F\u89C1\u5BF9\u5E94\u539F\u6587\u4E2D\u7684\u4E00\u6BB5\u6587\u5B57\uFF0C\u8BF7\u9010\u6761\u6267\u884C\u4FEE\u6539\u3002\u5220\u9664\u7EBF\u8868\u793A\u9700\u8981\u5220\u9664\u8BE5\u6BB5\u6587\u5B57\uFF0C\u5176\u4ED6\u610F\u89C1\u8BF7\u6839\u636E\u4E0A\u4E0B\u6587\u7406\u89E3\u610F\u56FE\u5E76\u6267\u884C\u4FEE\u6539\u3002\u4FEE\u6539\u5B8C\u6210\u540E\u8BF7\u8F93\u51FA\u5B8C\u6574\u7684\u4FEE\u6539\u540E\u6587\u4EF6\u5185\u5BB9\u3002","export.promptHeader":"\u8BF7\u6839\u636E\u4EE5\u4E0B\u6279\u9605\u610F\u89C1\u4FEE\u6539\u6307\u5B9A\u6587\u4EF6\uFF1A","export.promptFile":"\u6587\u4EF6\uFF1A{{path}}","export.promptReviews":"\u6279\u9605\u610F\u89C1\uFF1A","export.promptFooter":"\u8BF7\u9010\u6761\u6267\u884C\u4E0A\u8FF0\u4FEE\u6539\uFF0C\u8F93\u51FA\u5B8C\u6574\u7684\u4FEE\u6539\u540E\u6587\u4EF6\u3002","export.notice.fileNotFound":"\u627E\u4E0D\u5230\u539F\u6587\u4EF6","export.notice.exportedTokens":"\u5DF2\u5BFC\u51FA\uFF08\u7EA6 {{n}} tokens\uFF09","export.notice.promptCopied":"Prompt \u5DF2\u590D\u5236\uFF08\u7EA6 {{n}} tokens\uFF09","agent.confirm.title":"\u786E\u8BA4\u6267\u884C","agent.confirm.subtitle":"{{label}} \xB7 \u5373\u5C06\u5728\u7EC8\u7AEF\u4E2D\u8FD0\u884C","agent.confirm.warning":"\u8BF7\u4ED4\u7EC6\u68C0\u67E5\u547D\u4EE4\u5185\u5BB9\uFF0C\u786E\u8BA4\u540E\u5C06\u5728\u7EC8\u7AEF\u4E2D\u6267\u884C\u3002Agent \u5C06\u76F4\u63A5\u4FEE\u6539\u78C1\u76D8\u4E0A\u7684\u6587\u4EF6\u3002","agent.confirm.instructionFile":"\u6307\u4EE4\u6587\u4EF6: {{path}}","agent.confirm.commandLabel":"\u547D\u4EE4","agent.confirm.installed":"\u5DF2\u5B89\u88C5","agent.confirm.btn.cancel":"\u53D6\u6D88","agent.confirm.btn.copyCommand":"\u590D\u5236\u547D\u4EE4","agent.confirm.btn.execute":"\u6267\u884C","agent.confirm.notice.copied":"\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","agent.select.title":"\u9009\u62E9 Agent","agent.select.subtitle":"\u9009\u62E9\u4E00\u4E2A AI Agent \u6765\u6267\u884C\u7F16\u8F91","agent.select.installed":"\u5DF2\u5B89\u88C5","agent.select.missing":"\u672A\u5B89\u88C5","agent.select.addCustom":"+ \u914D\u7F6E\u81EA\u5B9A\u4E49 Agent","agent.select.btn.confirm":"\u786E\u8BA4","diff.title":"Diff \u9884\u89C8","diff.subtitle":"{{file}} \u2014 {{n}} \u5904\u53D8\u66F4","diff.noChanges":"\u672A\u68C0\u6D4B\u5230\u53D8\u66F4\u3002","diff.changesLabel":"\u53D8\u66F4\u5185\u5BB9\uFF1A","diff.btn.rollbackAll":"\u5168\u90E8\u56DE\u6EDA","diff.btn.applySelected":"\u5E94\u7528\u9009\u4E2D","diff.btn.reject":"\u62D2\u7EDD","diff.btn.accept":"\u63A5\u53D7","diff.btn.refresh":"\u5237\u65B0","diff.notice.refreshed":"\u5DF2\u5237\u65B0 Diff","diff.notice.refreshFailed":"\u5237\u65B0 Diff \u5931\u8D25","diff.notice.changedBeforeApply":"\u6587\u4EF6\u6709\u65B0\u53D8\u5316\uFF0C\u5DF2\u5237\u65B0 Diff\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4","diff.hunks":"\u4E2A\u53D8\u66F4","api.execute.title":"API \u6279\u9605\u786E\u8BA4","api.execute.subtitle":"\u5373\u5C06\u53D1\u9001\u81F3 API","api.execute.provider":"Provider","api.execute.model":"Model","api.execute.reviews":"Reviews","api.execute.reviewCount":"{{n}} \u6761\u6279\u9605","api.execute.tokens":"Tokens","api.execute.warning":"\u539F\u6587\u4E0E\u6279\u9605\u610F\u89C1\u5C06\u53D1\u9001\u81F3\u6240\u9009 Provider\uFF0C\u8BF7\u786E\u8BA4\u4E0D\u542B\u654F\u611F\u4FE1\u606F\u3002\u6570\u636E\u5C06\u79BB\u5F00\u672C\u5730 Vault\u3002","api.execute.btn.cancel":"\u53D6\u6D88","api.execute.btn.confirm":"\u786E\u8BA4\u6267\u884C","api.progress.title":"API \u6279\u9605\u4E2D\u2026","api.progress.subtitle":"\u6B63\u5728\u8C03\u7528 API","api.progress.calling":"\u6B63\u5728\u8C03\u7528 API\uFF0C\u8BF7\u7A0D\u5019\u2026","api.progress.failed":"\u8C03\u7528\u5931\u8D25\uFF1A{{error}}","api.progress.success":"API \u8FD4\u56DE\u6210\u529F\uFF0C\u5373\u5C06\u6253\u5F00 Diff \u9884\u89C8","api.progress.btn.close":"\u5173\u95ED","api.progress.btn.viewDiff":"\u67E5\u770B Diff","api.progress.cancelled":"API \u8C03\u7528\u5DF2\u53D6\u6D88","cmdrule.error.idExists":'\u89C4\u5219 ID "{{id}}" \u5DF2\u5B58\u5728',"cmdrule.error.presetNotEditable":"\u9884\u8BBE\u89C4\u5219\u4E0D\u53EF\u7F16\u8F91","cmdrule.error.notFound":'\u81EA\u5B9A\u4E49\u89C4\u5219 "{{id}}" \u4E0D\u5B58\u5728',"cmdrule.error.presetNotDeletable":"\u9884\u8BBE\u89C4\u5219\u4E0D\u53EF\u5220\u9664","terminal.notice.copied":"\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","terminal.notice.copiedWin":"\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF08Windows \u6682\u4E0D\u652F\u6301\u4E00\u952E\u6267\u884C\uFF09","terminal.notice.copiedLinux":"\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF08Linux \u6682\u4E0D\u652F\u6301\u4E00\u952E\u6267\u884C\uFF09","terminal.notice.launched":"\u5DF2\u901A\u8FC7 {{app}} \u6267\u884C\u547D\u4EE4","terminal.notice.launchFailed":"\u7EC8\u7AEF\u542F\u52A8\u5931\u8D25\uFF0C\u547D\u4EE4\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","folder.notice.mobileNotSupported":"\u79FB\u52A8\u7AEF\u4E0D\u652F\u6301\u6253\u5F00\u672C\u5730\u6587\u4EF6\u5939","folder.notice.cannotResolveFile":"\u65E0\u6CD5\u89E3\u6790\u6587\u4EF6\u7EDD\u5BF9\u8DEF\u5F84","folder.notice.cannotResolveFolder":"\u65E0\u6CD5\u89E3\u6790\u6587\u4EF6\u5939\u7EDD\u5BF9\u8DEF\u5F84","folder.notice.openFailed":"\u6253\u5F00\u6587\u4EF6\u5939\u5931\u8D25: {{error}}","shell.error.forbiddenChar":"\u547D\u4EE4\u6A21\u677F\u5305\u542B\u7981\u7528\u5B57\u7B26: {{chars}}","shell.error.unknownVariable":"\u672A\u77E5\u6A21\u677F\u53D8\u91CF: {{var}}","common.cancel":"\u53D6\u6D88","common.save":"\u4FDD\u5B58","common.delete":"\u5220\u9664","common.confirm":"\u786E\u8BA4","common.close":"\u5173\u95ED","common.yes":"\u662F","common.no":"\u5426","common.add":"\u6DFB\u52A0","common.edit":"\u7F16\u8F91","common.loading":"\u52A0\u8F7D\u4E2D\u2026","common.error":"\u9519\u8BEF","common.success":"\u6210\u529F","common.warning":"\u8B66\u544A","color.yellow":"\u9EC4\u8272","color.green":"\u7EFF\u8272","color.blue":"\u84DD\u8272","color.pink":"\u7C89\u8272","color.orange":"\u6A59\u8272","sidebar.action.agentTitle":"\u9009\u62E9 Agent CLI \u6267\u884C\u6279\u9605\u4FEE\u6539","sidebar.action.agentReview":"Agent \u6279\u9605","sidebar.action.apiTitle":"\u901A\u8FC7 API \u76F4\u8C03\u6267\u884C\u6279\u9605\u4FEE\u6539","sidebar.action.noApiKey":"\u8BF7\u5148\u5728\u8BBE\u7F6E\u4E2D\u914D\u7F6E API Key","sidebar.action.copy":"\u590D\u5236","sidebar.action.copyTitle":"\u590D\u5236\u6279\u9605 Prompt \u5230\u526A\u8D34\u677F","sidebar.action.exportTitle":"\u5BFC\u51FA\u6279\u6CE8\u6587\u4EF6","sidebar.action.exportFile":"\u5BFC\u51FA\u6279\u6CE8\u6587\u4EF6","export.none":"\uFF08\u65E0\uFF09"},mt=cn;var dn={"main.ribbonTooltip":"Promptuary Sidebar","main.cmd.openSidebar":"Open sidebar","main.cmd.highlightYellow":"Highlight (Yellow)","main.cmd.highlightGreen":"Highlight (Green)","main.cmd.highlightBlue":"Highlight (Blue)","main.cmd.highlightPink":"Highlight (Pink)","main.cmd.highlightOrange":"Highlight (Orange)","main.cmd.addNote":"Add note","main.cmd.addReview":"Add review comment","main.cmd.exportReview":"Export review file","main.cmd.copyPrompt":"Copy Prompt","main.cmd.apiExecute":"API Key direct execute","main.cmd.runAgent":"Execute with {{label}}","main.cmd.copyAgentCommand":"Copy Agent command","main.notice.openMdFile":"Please open a Markdown file first","main.notice.noReviewAnnotations":"No review comments in this file","main.notice.allAccepted":"All changes accepted","main.notice.selectedApplied":"Selected changes applied","main.notice.allRolledBack":"All changes rolled back","main.notice.mobileNoAgent":'Agent execution is not supported on mobile. Please use "Copy Prompt"',"main.notice.monitoringChanges":"Monitoring file changes (5 min timeout)\u2026","main.notice.autoHealed":"Auto-healed {{n}} annotation positions","main.notice.reviewExecuted":"{{n}} review comments executed and removed","main.notice.invalidReadingRemoved":"{{n}} invalid reading annotations removed","main.notice.noChangesDetected":"No file changes detected","main.notice.selectTextFirst":"Please select text to annotate first","main.notice.selectReviewTextFirst":"Please select text to review first","main.notice.noChangesNeeded":"API returned content identical to original, no changes needed","main.notice.cancelledNoChange":"Cancelled, file unchanged","main.notice.noOriginalSnapshot":"No saved original text snapshot","main.notice.ruleNotFound":"Rule not found: {{id}}","main.notice.noAgentCLI":"No Agent CLI detected. Please install Claude Code / Codex / Aider / Gemini CLI first","main.notice.exportSuccess":"Exported successfully, opening: {{target}}","main.notice.exportFailed":"Export failed: no file generated","main.notice.changeDetected":"File change detected, generating diff\u2026","main.notice.monitorTimeout":"Monitor timeout, no further changes detected","main.notice.commandCopied":"{{label}} command copied to clipboard","main.notice.configureAPIKey":"Please configure API Key in Settings \u2192 API Direct Call","main.notice.reviewCleanupDone":"Cleaned {{n}} processed review comment(s)","sidebar.empty.openFile":"Please open a Markdown file","sidebar.mode.reading":"Reading","sidebar.mode.review":"Review","sidebar.mode.all":"All","sidebar.tag.highlight":"Highlight","sidebar.tag.note":"Note","sidebar.tag.delete":"Delete","sidebar.tag.review":"Review","sidebar.empty.reading":`No reading annotations yet. Select text to highlight or add a note.`,"sidebar.empty.review":`No review comments yet. -Switch to Review mode, select text, and write a comment.`,"sidebar.empty.all":"No annotations in this document yet.","sidebar.status.agentRunning":"Agent processing\u2026","sidebar.status.apiRunning":"API processing\u2026","sidebar.status.pendingReview":"{{n}} review(s) pending","sidebar.card.ambiguous":"Ambiguous","sidebar.card.autoHealed":"Auto-healed","sidebar.card.drifted":"Drifted","sidebar.card.delete":"Delete","sidebar.notice.cannotLocate":"Cannot locate annotation, it may have drifted","sidebar.banner.drifted":"{{n}} drifted","sidebar.banner.ambiguous":"{{n}} ambiguous","sidebar.banner.changed":"Changed after\u2026","sidebar.banner.changedFull":"Original text has changed, please check annotations","sidebar.banner.confirmAll":"Confirm all","sidebar.banner.baselineUpdated":"Baseline updated","sidebar.notice.autoHealed":"Auto-healed {{n}} annotation positions","sidebar.notice.reviewAutoRemoved":"{{n}} review comments auto-removed","sidebar.notice.invalidReadingRemoved":"{{n}} invalid reading annotations removed","sidebar.notice.ambiguousCheck":"{{n}} annotations have ambiguous positions, please check","sidebar.cleanup.title":"Agent changes returned","sidebar.cleanup.desc":"Clean up {{n}} processed review comment(s) from this run?","sidebar.cleanup.clean":"Clean","sidebar.cleanup.keep":"Keep","popover.mode.reading":"Reading","popover.mode.review":"Review","popover.title.edit":"Edit annotation","popover.title.add":"Add annotation","popover.btn.addNote":"Add Note","popover.btn.addNoteTitle":"Add note","popover.btn.delete":"Delete","popover.btn.deleteTitle":"Mark for deletion","popover.btn.reviewNote":"Add Note","popover.btn.reviewNoteTitle":"Add review comment","popover.btn.confirmDelete":"Confirm delete","popover.color.highlight":"{{color}} highlight","popover.placeholder.review":"Enter review comment, AI will infer how to edit\u2026","popover.placeholder.note":"Add a note for this highlight\u2026","popover.label.review":"Review","popover.label.note":"Note","popover.btn.save":"Save","popover.btn.saveTitle":"Save","toolbar.mode.reading":"Reading","toolbar.mode.review":"Review","toolbar.label.review":"Review","toolbar.label.note":"Note","toolbar.label.delete":"Delete","toolbar.btn.addNote":"Add Note","toolbar.btn.addNoteTitle":"Add note","toolbar.btn.delete":"Delete","toolbar.btn.deleteTitle":"Mark for deletion","toolbar.btn.reviewNote":"Add Note","toolbar.btn.reviewNoteTitle":"Add review comment","toolbar.btn.confirmDelete":"Confirm delete","toolbar.color.highlight":"{{color}} highlight","toolbar.placeholder.review":"Enter review comment\u2026","toolbar.placeholder.note":"Add a note for this highlight\u2026","toolbar.btn.save":"Save","notemodal.note.title":"Add Note","notemodal.note.content":"Content","notemodal.review.title":"Add Review Comment","notemodal.review.content":"Comment","notemodal.review.strikethrough":"Mark as strikethrough","notemodal.review.strikethroughDesc":"Expresses strong delete/merge intent. AI will combine with context to decide.","notemodal.btn.cancel":"Cancel","notemodal.btn.save":"Save","settings.section.basic":"Basic Settings","settings.section.basicDesc":"Annotation storage, export path, and default mode","settings.section.agent":"Agent & Terminal","settings.section.agentDesc":"CLI Agent detection, command rules, and terminal config","settings.section.api":"API Direct Call","settings.section.apiDesc":"Configure API Key to call models directly without installing CLI","settings.language.name":"Language","settings.language.desc":"The plugin will reload to apply the new language","settings.language.auto":"Follow system","settings.language.zhCN":"\u7B80\u4F53\u4E2D\u6587","settings.language.en":"English","settings.defaultMode.name":"Default mode","settings.defaultMode.desc":"Default annotation mode when opening a document","settings.defaultMode.reading":"Reading","settings.defaultMode.review":"Review","settings.contextSpan.name":"Context span","settings.contextSpan.desc":"Number of context characters for anchor matching (larger = more accurate but more tokens)","settings.sidecarDir.name":"Annotation storage directory","settings.sidecarDir.desc":"Relative to vault root. Directories starting with . are hidden","settings.exportDir.name":"Export directory","settings.exportDir.desc":"Export path for review files, relative to vault root","settings.includeReadingNotes.name":"Include reading notes in export","settings.includeReadingNotes.desc":"Include reading-mode notes and highlights when exporting review files","settings.terminalApp.name":"Terminal app","settings.terminalApp.desc":"Terminal application for executing Agent commands","settings.terminalApp.terminal":"Terminal","settings.terminalApp.iterm":"iTerm2","settings.terminalApp.defaultSuffix":" (default)","settings.detectedAgents.name":"Detected Agents","settings.detectedAgents.desc":"Automatically detected CLI Agents on your system","settings.detectedAgents.installed":"Installed","settings.detectedAgents.notFound":"No Agent CLI detected. Install one and restart Obsidian.","settings.commandRules.name":"Command rules","settings.commandRules.desc":"Preset and custom Agent CLI command templates","settings.commandRules.addRule":"Add command rule","settings.commandRules.editRule":"Edit rule","settings.commandRules.deleteRule":"Delete rule","settings.api.provider.name":"API Provider","settings.api.provider.desc":"Select model provider","settings.api.provider.anthropic":"Anthropic","settings.api.provider.openai":"OpenAI","settings.api.provider.deepseek":"DeepSeek","settings.api.provider.custom":"Custom endpoint","settings.api.key.name":"API Key","settings.api.key.desc":"The key is stored locally only and never sent to third parties","settings.api.key.placeholder":"sk-\u2026","settings.api.model.name":"Model","settings.api.model.desc":"Leave empty to use the provider's default model","settings.api.model.placeholder":"claude-sonnet-4-20250514","settings.api.customEndpoint.name":"Custom endpoint","settings.api.customEndpoint.desc":'Only effective when "Custom endpoint" is selected',"settings.api.customEndpoint.placeholder":"https://api.example.com/v1/chat/completions","settings.api.maxTokens.name":"Max output tokens","settings.api.maxTokens.desc":"Maximum number of tokens the model can return","settings.api.test.name":"Test connection","settings.api.test.desc":"Send a short request to verify the API Key and endpoint","settings.api.test.running":"Testing\u2026","settings.api.test.success":"Connection successful! Model: {{model}}","settings.api.test.failed":"Connection failed: {{error}}","addrule.title":"Add Command Rule","addrule.subtitle":"Custom Agent CLI command template","addrule.id.name":"Rule ID","addrule.id.desc":"Unique identifier, letters, numbers, and hyphens only","addrule.id.placeholder":"my-agent","addrule.detectCmd.name":"Detect command","addrule.detectCmd.desc":"Shell command to check if the Agent is installed","addrule.detectCmd.placeholder":"which my-agent","addrule.label.name":"Display name","addrule.label.desc":"Name shown in sidebar and command palette","addrule.label.placeholder":"My Agent","addrule.command.name":"Command template","addrule.command.desc":"Available variables: {{instructionFile}} (instruction file path), {{targetFile}} (target file path)","addrule.command.placeholder":"my-agent --file {{targetFile}} < {{instructionFile}}","addrule.installHint.name":"Install hint","addrule.installHint.desc":"Install command shown when not installed (optional)","addrule.installHint.placeholder":"npm i -g my-agent","addrule.instruction.name":"Instruction prefix","addrule.instruction.desc":"Prepended to the instruction file","addrule.instruction.placeholder":"Read {{instructionFile}} and modify the corresponding file per review instructions","addrule.defaultInstallHint":"Custom install method","addrule.varTitle":"Available template variables","addrule.var.vaultPath":"Vault root directory","addrule.var.instructionFile":"Instruction file path","addrule.var.filePath":"File relative path","addrule.var.fileName":"File name","addrule.var.prompt":"Inline Prompt","addrule.btn.cancel":"Cancel","addrule.btn.add":"Add rule","addrule.notice.idExists":'Rule ID "{{id}}" already exists',"addrule.notice.idEmpty":"Please enter a rule ID","addrule.notice.labelEmpty":"Please enter a display name","addrule.notice.commandEmpty":"Please enter a command template","addrule.notice.requiredFields":"Please fill in all required fields","addrule.notice.validationFailed":"Validation failed: {{error}}","settings.agentInstall":"Install: ","settings.redetectAgent.name":"Re-detect Agents","settings.redetectAgent.desc":"Re-scan for installed Agent CLIs","settings.redetectAgent.btn":"Detect","settings.redetectAgent.done":"Detection complete","settings.customRules.title":"Custom command rules","settings.customRules.added":'Rule "{{label}}" added',"settings.customRules.addFailed":"Add failed: {{error}}","settings.customRules.empty":'No custom rules yet. Click the "+ Add" button above to create one.',"settings.varRef.title":"Available template variables reference","settings.varRef.vaultPath":"Vault root absolute path","settings.varRef.instructionFile":"Generated instruction file path","settings.varRef.filePath":"Current file relative path","settings.varRef.fileName":"Current file name","settings.varRef.prompt":"Inline prompt text","settings.ruleCard.detect":"Detect","settings.ruleCard.template":"Template","settings.api.test.btn":"Test","settings.api.test.noKey":"Please enter an API Key first","export.reviewTitle":"AI Review Instructions","export.originalFile":"Original file","export.exportTime":"Export time","export.reviewCount":"Review count","export.includeReading":"Includes reading notes","export.yes":"Yes","export.no":"No","export.reviewSection":"Review comments","export.strikethrough":"Strikethrough","export.original":"Original","export.context":"Context","export.opinion":"Comment","export.execRequirement":"Execution requirements","export.execRequirementText":"Please modify the original file based on the review comments above. Each comment corresponds to a text segment in the original file. Strikethrough indicates the text should be deleted. For other comments, infer the intent from context and apply the changes. Output the complete modified file after making all changes.","export.promptHeader":"Please modify the specified file based on the following review comments:","export.promptFile":"File: {{path}}","export.promptReviews":"Review comments:","export.promptFooter":"Please apply the above changes one by one and output the complete modified file.","export.notice.fileNotFound":"Original file not found","export.notice.exportedTokens":"Exported (~{{n}} tokens)","export.notice.promptCopied":"Prompt copied (~{{n}} tokens)","agent.confirm.title":"Confirm Execution","agent.confirm.subtitle":"{{label}} \xB7 about to run in Terminal","agent.confirm.warning":"Please review the command carefully. Once confirmed, it will execute in the terminal. The Agent will directly modify files on disk.","agent.confirm.instructionFile":"Instruction file: {{path}}","agent.confirm.commandLabel":"COMMAND","agent.confirm.installed":"installed","agent.confirm.btn.cancel":"Cancel","agent.confirm.btn.copyCommand":"Copy Command","agent.confirm.btn.execute":"Execute","agent.confirm.notice.copied":"Command copied to clipboard","agent.select.title":"Select Agent","agent.select.subtitle":"Choose an AI agent to execute edits","agent.select.installed":"installed","agent.select.missing":"missing","agent.select.addCustom":"+ Configure custom agent","agent.select.btn.confirm":"Confirm","diff.title":"Diff Preview","diff.subtitle":"{{file}} \u2014 {{n}} changes proposed","diff.noChanges":"No changes detected.","diff.changesLabel":"Changes:","diff.btn.rollbackAll":"Rollback all","diff.btn.applySelected":"Apply selected","diff.btn.reject":"Reject","diff.btn.accept":"Accept","diff.hunks":"changes","api.execute.title":"API Review Confirmation","api.execute.subtitle":"About to send to API","api.execute.provider":"Provider","api.execute.model":"Model","api.execute.reviews":"Reviews","api.execute.reviewCount":"{{n}} review(s)","api.execute.tokens":"Tokens","api.execute.warning":"The original text and review comments will be sent to the selected Provider. Please ensure no sensitive information is included. Data will leave your local Vault.","api.execute.btn.cancel":"Cancel","api.execute.btn.confirm":"Confirm execution","api.progress.title":"API processing\u2026","api.progress.subtitle":"Calling API","api.progress.calling":"Calling API, please wait\u2026","api.progress.failed":"API call failed: {{error}}","api.progress.success":"API call successful, opening Diff preview","api.progress.btn.close":"Close","api.progress.btn.viewDiff":"View Diff","api.progress.cancelled":"API call cancelled","cmdrule.error.idExists":'Rule ID "{{id}}" already exists',"cmdrule.error.presetNotEditable":"Preset rules cannot be edited","cmdrule.error.notFound":'Custom rule "{{id}}" not found',"cmdrule.error.presetNotDeletable":"Preset rules cannot be deleted","terminal.notice.copied":"Command copied to clipboard","terminal.notice.copiedWin":"Command copied to clipboard (one-click execution not supported on Windows yet)","terminal.notice.copiedLinux":"Command copied to clipboard (one-click execution not supported on Linux yet)","terminal.notice.launched":"Command executed via {{app}}","terminal.notice.launchFailed":"Terminal launch failed, command copied to clipboard","folder.notice.mobileNotSupported":"Opening local folders is not supported on mobile","folder.notice.cannotResolveFile":"Cannot resolve file absolute path","folder.notice.cannotResolveFolder":"Cannot resolve folder absolute path","folder.notice.openFailed":"Failed to open folder: {{error}}","shell.error.forbiddenChar":"Command template contains forbidden characters: {{chars}}","shell.error.unknownVariable":"Unknown template variable: {{var}}","common.cancel":"Cancel","common.save":"Save","common.delete":"Delete","common.confirm":"Confirm","common.close":"Close","common.yes":"Yes","common.no":"No","common.add":"Add","common.edit":"Edit","common.loading":"Loading\u2026","common.error":"Error","common.success":"Success","common.warning":"Warning","color.yellow":"Yellow","color.green":"Green","color.blue":"Blue","color.pink":"Pink","color.orange":"Orange","sidebar.action.agentTitle":"Select Agent CLI to execute review edits","sidebar.action.agentReview":"Agent Review","sidebar.action.apiTitle":"Execute review edits via API direct call","sidebar.action.noApiKey":"Please configure API Key in Settings first","sidebar.action.copy":"Copy","sidebar.action.copyTitle":"Copy review Prompt to clipboard","sidebar.action.exportTitle":"Export review file","sidebar.action.exportFile":"Export review file","export.none":"(None)"},pt=rn;var mt={"zh-CN":dt,en:pt},ne="zh-CN";function a(s,i){let e=mt[ne]?.[s]??mt["zh-CN"][s]??s;if(i)for(let[t,n]of Object.entries(i))e=e.replace(new RegExp(`\\{\\{${t}\\}\\}`,"g"),String(n));return e}function ge(s){if(s!=="auto"){ne=s;return}let i=localStorage.getItem("language");if(i){ne=i.startsWith("zh")?"zh-CN":"en";return}let e=navigator.language;if(e){ne=e.startsWith("zh")?"zh-CN":"en";return}ne="zh-CN"}var ut=` -`;var ht=` -`;var Z=require("obsidian");function fe(s){return{version:1,filePath:s,baselineHash:"",annotations:[]}}function Y(s,i){return`${s}/${i}.json`}async function ie(s,i){let e=i.split("/"),t="";for(let n of e)n&&(t=t?`${t}/${n}`:n,await s.exists(t)||await s.mkdir(t))}async function Ge(s,i,e){let t=e;for(;t&&t!==i&&t.length>i.length&&await s.exists(t);){try{let r=await s.list(t);if(r.files.length===0&&r.folders.length===0)await s.rmdir(t);else break}catch{break}let n=t.lastIndexOf("/");if(n<0)break;t=t.slice(0,n)}}async function re(s){if(typeof crypto<"u"&&crypto.subtle){let i=new TextEncoder().encode(s),e=await crypto.subtle.digest("SHA-256",i);return an(e)}return"fallback:"+ln(s).toString(16)}function an(s){return Array.from(new Uint8Array(s)).map(e=>e.toString(16).padStart(2,"0")).join("")}function ln(s){let i=0;for(let e=0;e>>0}function gt(){let s=Date.now(),i=Math.random().toString(36).slice(2,6);return`ann_${s}_${i}`}var cn=300,ve=class extends Z.Events{constructor(e,t){super();this.app=e;this.getRootDir=t;this.cache=new Map;this.writeTimers=new Map;this.pendingFlush=new Set;this.vaultRefs=[]}get rootDir(){return this.getRootDir()}registerVaultEvents(){this.vaultRefs.push(this.app.vault.on("rename",(e,t)=>this.handleRename(e,t))),this.vaultRefs.push(this.app.vault.on("delete",e=>this.handleDelete(e)))}destroy(){for(let e of this.writeTimers.values())window.clearTimeout(e);this.writeTimers.clear();for(let e of this.vaultRefs)this.app.vault.offref(e);this.vaultRefs=[]}async getFile(e){let t=this.cache.get(e);if(t)return t;let n=await this.loadFromDisk(e);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}async addAnnotation(e,t){let n=await this.getFile(e);n.annotations.push(t),n.baselineHash||(n.baselineHash=t.baselineHash),this.scheduleWrite(e),this.trigger("change",e)}async updateAnnotation(e,t,n){let r=await this.getFile(e),o=r.annotations.findIndex(l=>l.id===t);o<0||(r.annotations[o]={...r.annotations[o],...n,updatedAt:Date.now()},this.scheduleWrite(e),this.trigger("change",e))}async removeAnnotation(e,t){let n=await this.getFile(e);n.annotations=n.annotations.filter(r=>r.id!==t),this.scheduleWrite(e),this.trigger("change",e)}async confirmBaseline(e,t,n=!1){let r=await this.getFile(e);r.baselineHash=t;for(let o of r.annotations)o.baselineHash=t;this.scheduleWrite(e),n||this.trigger("change",e)}scheduleWrite(e){this.pendingFlush.add(e);let t=this.writeTimers.get(e);t&&window.clearTimeout(t);let n=window.setTimeout(()=>{this.flush(e)},cn);this.writeTimers.set(e,n)}async flushAll(){let e=Array.from(this.pendingFlush);await Promise.all(e.map(t=>this.flush(t)))}async flush(e){this.pendingFlush.delete(e),this.writeTimers.delete(e);let t=this.cache.get(e);t&&await this.writeToDisk(e,t)}async loadFromDisk(e){let t=Y(this.rootDir,e),n=this.app.vault.adapter;try{if(!await n.exists(t))return fe(e);let r=await n.read(t),o=JSON.parse(r);if(!o||o.version!==1||!Array.isArray(o.annotations)){let l=Array.isArray(o?.annotations)?o.annotations:[];return{...fe(e),annotations:l,version:1}}return o.filePath=e,o}catch(r){return console.warn("[Promptuary] failed to load sidecar",t,r),fe(e)}}async writeToDisk(e,t){let n=this.app.vault.adapter,r=Y(this.rootDir,e),o=r.slice(0,r.lastIndexOf("/"));try{await ie(n,o);let l=JSON.stringify(t,null,2);await n.write(r,l)}catch(l){console.error("[Promptuary] failed to write sidecar",r,l)}}async handleRename(e,t){if(!(e instanceof Z.TFile)||!t.endsWith(".md"))return;await this.flush(t);let n=this.app.vault.adapter,r=Y(this.rootDir,t),o=Y(this.rootDir,e.path);try{if(await n.exists(r)){let l=await n.read(r),c=JSON.parse(l);c.filePath=e.path;for(let m of c.annotations)m.filePath=e.path;let d=o.slice(0,o.lastIndexOf("/"));await ie(n,d),await n.write(o,JSON.stringify(c,null,2)),await n.remove(r);let p=r.slice(0,r.lastIndexOf("/"));await Ge(n,this.rootDir,p)}}catch(l){console.warn("[Promptuary] rename sidecar failed",l)}if(this.cache.has(t)){let l=this.cache.get(t);l.filePath=e.path,this.cache.delete(t),this.cache.set(e.path,l)}this.trigger("change",e.path)}async handleDelete(e){if(!(e instanceof Z.TFile)||!e.path.endsWith(".md"))return;await this.flush(e.path);let t=this.app.vault.adapter,n=Y(this.rootDir,e.path),r=`${this.rootDir}/orphans`;try{if(await t.exists(n)){await ie(t,r);let o=n.slice(this.rootDir.length+1),l=`${r}/${o}`,c=l.slice(0,l.lastIndexOf("/"));await ie(t,c),await t.rename(n,l);let d=n.slice(0,n.lastIndexOf("/"));await Ge(t,this.rootDir,d)}}catch(o){console.warn("[Promptuary] orphan sidecar move failed",o)}this.cache.delete(e.path),this.trigger("change",e.path)}async fileHash(e){let t=this.app.vault.getAbstractFileByPath(e);if(!(t instanceof Z.TFile))return"";let n=await this.app.vault.read(t);return re(n)}};function we(s,i){if(!i)return[];let e=[],t=0;for(;t<=s.length-i.length;){let n=s.indexOf(i,t);if(n<0)break;e.push({from:n,to:n+i.length,line:xt(s,n)}),t=n+Math.max(1,i.length)}return e}function xt(s,i){let e=1;for(let t=0;t1){let c=[...t].sort((p,m)=>Math.abs(p.line-i.lineHint)-Math.abs(m.line-i.lineHint))[0].from+i.contextBefore.length,d=c+i.selectedText.length;return{status:"strict",from:c,to:d}}if(t=we(s,i.contextBefore+i.selectedText),t.length===1){let l=t[0].from+i.contextBefore.length,c=l+i.selectedText.length;return{status:"strict",from:l,to:c}}if(t=we(s,i.selectedText+i.contextAfter),t.length===1){let l=t[0].from,c=l+i.selectedText.length;return{status:"strict",from:l,to:c}}let n=we(s,i.selectedText);if(n.length===0)return{status:"drifted"};if(n.length===1)return{status:"fuzzy",from:n[0].from,to:n[0].to};let r;return i.occurrenceIndex>=0&&i.occurrenceIndexMath.abs(o.line-i.lineHint)-Math.abs(l.line-i.lineHint))[0],{status:"fuzzy",from:r.from,to:r.to,candidates:n.filter(o=>o!==r).map(o=>({from:o.from,to:o.to}))}}var vt=.5,dn=500,Ue=8;function be(s,i){if(!i.selectedText)return{status:"drifted"};if(i.selectedText.length>dn)return{status:"drifted"};if(s.length===0)return{status:"drifted"};let e=i.selectedText,t=e.length,n=0,r=s.length;if(i.lineHint>0){let p=1,m=0;for(let g=0;g=i.lineHint-50){m=g;break}s.charCodeAt(g)===10&&p++}let u=s.length;p=1;for(let g=0;g=i.lineHint+50){u=g;break}s.charCodeAt(g)===10&&p++}n=Math.max(0,m-200),r=Math.min(s.length,u+200)}let o=-1,l=0;for(let p=n;p<=r-t;p+=Ue){let m=s.slice(p,p+t),u=wt(e,m);u>l&&(l=u,o=p)}if(o>=0&&l>=vt*.8){let p=Math.max(n,o-Ue*2),m=Math.min(r-t,o+Ue*2);for(let u=p;u<=m;u++){let g=s.slice(u,u+t),h=wt(e,g);h>l&&(l=h,o=u)}}if(o<0||l0?n/r:0}function bt(s){let i=new Set;for(let e=0;e<=s.length-3;e++){let t=s.charCodeAt(e)<<16|s.charCodeAt(e+1)<<8|s.charCodeAt(e+2);i.add(t)}return i}function X(s,i,e){if(!i)return 0;let t=0,n=0;for(;n<=e;){let r=s.indexOf(i,n);if(r<0||r>e)break;if(r===e)return t;t++,n=r+Math.max(1,i.length)}return t}function Q(s,i){return xt(s,i)}function yt(s,i,e,t=50){let n=Math.max(0,i-t),r=Math.min(s.length,e+t);return{contextBefore:s.slice(n,i),contextAfter:s.slice(e,r)}}function pn(s,i){let e=[],t=s.split(` +`;var Z=require("obsidian");function xe(s){return{version:1,filePath:s,baselineHash:"",annotations:[]}}function Y(s,i){return`${s}/${i}.json`}async function se(s,i){let e=i.split("/"),t="";for(let n of e)n&&(t=t?`${t}/${n}`:n,await s.exists(t)||await s.mkdir(t))}async function Ye(s,i,e){let t=e;for(;t&&t!==i&&t.length>i.length&&await s.exists(t);){try{let r=await s.list(t);if(r.files.length===0&&r.folders.length===0)await s.rmdir(t);else break}catch{break}let n=t.lastIndexOf("/");if(n<0)break;t=t.slice(0,n)}}async function ae(s){if(typeof crypto<"u"&&crypto.subtle){let i=new TextEncoder().encode(s),e=await crypto.subtle.digest("SHA-256",i);return un(e)}return"fallback:"+hn(s).toString(16)}function un(s){return Array.from(new Uint8Array(s)).map(e=>e.toString(16).padStart(2,"0")).join("")}function hn(s){let i=0;for(let e=0;e>>0}function vt(){let s=Date.now(),i=Math.random().toString(36).slice(2,6);return`ann_${s}_${i}`}var fn=300,ye=class extends Z.Events{constructor(e,t){super();this.app=e;this.getRootDir=t;this.cache=new Map;this.writeTimers=new Map;this.pendingFlush=new Set;this.vaultRefs=[]}get rootDir(){return this.getRootDir()}registerVaultEvents(){this.vaultRefs.push(this.app.vault.on("rename",(e,t)=>this.handleRename(e,t))),this.vaultRefs.push(this.app.vault.on("delete",e=>this.handleDelete(e)))}destroy(){for(let e of this.writeTimers.values())window.clearTimeout(e);this.writeTimers.clear();for(let e of this.vaultRefs)this.app.vault.offref(e);this.vaultRefs=[]}async getFile(e){let t=this.cache.get(e);if(t)return t;let n=await this.loadFromDisk(e);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}async addAnnotation(e,t){let n=await this.getFile(e);n.annotations.push(t),n.baselineHash||(n.baselineHash=t.baselineHash),this.scheduleWrite(e),this.trigger("change",e)}async updateAnnotation(e,t,n){let r=await this.getFile(e),o=r.annotations.findIndex(l=>l.id===t);o<0||(r.annotations[o]={...r.annotations[o],...n,updatedAt:Date.now()},this.scheduleWrite(e),this.trigger("change",e))}async removeAnnotation(e,t){let n=await this.getFile(e);n.annotations=n.annotations.filter(r=>r.id!==t),this.scheduleWrite(e),this.trigger("change",e)}async confirmBaseline(e,t,n=!1){let r=await this.getFile(e);r.baselineHash=t;for(let o of r.annotations)o.baselineHash=t;this.scheduleWrite(e),n||this.trigger("change",e)}scheduleWrite(e){this.pendingFlush.add(e);let t=this.writeTimers.get(e);t&&window.clearTimeout(t);let n=window.setTimeout(()=>{this.flush(e)},fn);this.writeTimers.set(e,n)}async flushAll(){let e=Array.from(this.pendingFlush);await Promise.all(e.map(t=>this.flush(t)))}async flush(e){this.pendingFlush.delete(e),this.writeTimers.delete(e);let t=this.cache.get(e);t&&await this.writeToDisk(e,t)}async loadFromDisk(e){let t=Y(this.rootDir,e),n=this.app.vault.adapter;try{if(!await n.exists(t))return xe(e);let r=await n.read(t),o=JSON.parse(r);if(!o||o.version!==1||!Array.isArray(o.annotations)){let l=Array.isArray(o?.annotations)?o.annotations:[];return{...xe(e),annotations:l,version:1}}return o.filePath=e,o}catch(r){return console.warn("[Promptuary] failed to load sidecar",t,r),xe(e)}}async writeToDisk(e,t){let n=this.app.vault.adapter,r=Y(this.rootDir,e),o=r.slice(0,r.lastIndexOf("/"));try{await se(n,o);let l=JSON.stringify(t,null,2);await n.write(r,l)}catch(l){console.error("[Promptuary] failed to write sidecar",r,l)}}async handleRename(e,t){if(!(e instanceof Z.TFile)||!t.endsWith(".md"))return;await this.flush(t);let n=this.app.vault.adapter,r=Y(this.rootDir,t),o=Y(this.rootDir,e.path);try{if(await n.exists(r)){let l=await n.read(r),c=JSON.parse(l);c.filePath=e.path;for(let m of c.annotations)m.filePath=e.path;let d=o.slice(0,o.lastIndexOf("/"));await se(n,d),await n.write(o,JSON.stringify(c,null,2)),await n.remove(r);let p=r.slice(0,r.lastIndexOf("/"));await Ye(n,this.rootDir,p)}}catch(l){console.warn("[Promptuary] rename sidecar failed",l)}if(this.cache.has(t)){let l=this.cache.get(t);l.filePath=e.path,this.cache.delete(t),this.cache.set(e.path,l)}this.trigger("change",e.path)}async handleDelete(e){if(!(e instanceof Z.TFile)||!e.path.endsWith(".md"))return;await this.flush(e.path);let t=this.app.vault.adapter,n=Y(this.rootDir,e.path),r=`${this.rootDir}/orphans`;try{if(await t.exists(n)){await se(t,r);let o=n.slice(this.rootDir.length+1),l=`${r}/${o}`,c=l.slice(0,l.lastIndexOf("/"));await se(t,c),await t.rename(n,l);let d=n.slice(0,n.lastIndexOf("/"));await Ye(t,this.rootDir,d)}}catch(o){console.warn("[Promptuary] orphan sidecar move failed",o)}this.cache.delete(e.path),this.trigger("change",e.path)}async fileHash(e){let t=this.app.vault.getAbstractFileByPath(e);if(!(t instanceof Z.TFile))return"";let n=await this.app.vault.read(t);return ae(n)}};function Ae(s,i){if(!i)return[];let e=[],t=0;for(;t<=s.length-i.length;){let n=s.indexOf(i,t);if(n<0)break;e.push({from:n,to:n+i.length,line:At(s,n)}),t=n+Math.max(1,i.length)}return e}function At(s,i){let e=1;for(let t=0;t1){let c=[...t].sort((p,m)=>Math.abs(p.line-i.lineHint)-Math.abs(m.line-i.lineHint))[0].from+i.contextBefore.length,d=c+i.selectedText.length;return{status:"strict",from:c,to:d}}if(t=Ae(s,i.contextBefore+i.selectedText),t.length===1){let l=t[0].from+i.contextBefore.length,c=l+i.selectedText.length;return{status:"strict",from:l,to:c}}if(t=Ae(s,i.selectedText+i.contextAfter),t.length===1){let l=t[0].from,c=l+i.selectedText.length;return{status:"strict",from:l,to:c}}let n=Ae(s,i.selectedText);if(n.length===0)return{status:"drifted"};if(n.length===1)return{status:"fuzzy",from:n[0].from,to:n[0].to};let r;return i.occurrenceIndex>=0&&i.occurrenceIndexMath.abs(o.line-i.lineHint)-Math.abs(l.line-i.lineHint))[0],{status:"fuzzy",from:r.from,to:r.to,candidates:n.filter(o=>o!==r).map(o=>({from:o.from,to:o.to}))}}var bt=.5,gn=500,Ze=8;function Ce(s,i){if(!i.selectedText)return{status:"drifted"};if(i.selectedText.length>gn)return{status:"drifted"};if(s.length===0)return{status:"drifted"};let e=i.selectedText,t=e.length,n=0,r=s.length;if(i.lineHint>0){let p=1,m=0;for(let f=0;f=i.lineHint-50){m=f;break}s.charCodeAt(f)===10&&p++}let u=s.length;p=1;for(let f=0;f=i.lineHint+50){u=f;break}s.charCodeAt(f)===10&&p++}n=Math.max(0,m-200),r=Math.min(s.length,u+200)}let o=-1,l=0;for(let p=n;p<=r-t;p+=Ze){let m=s.slice(p,p+t),u=xt(e,m);u>l&&(l=u,o=p)}if(o>=0&&l>=bt*.8){let p=Math.max(n,o-Ze*2),m=Math.min(r-t,o+Ze*2);for(let u=p;u<=m;u++){let f=s.slice(u,u+t),h=xt(e,f);h>l&&(l=h,o=u)}}if(o<0||l0?n/r:0}function yt(s){let i=new Set;for(let e=0;e<=s.length-3;e++){let t=s.charCodeAt(e)<<16|s.charCodeAt(e+1)<<8|s.charCodeAt(e+2);i.add(t)}return i}function X(s,i,e){if(!i)return 0;let t=0,n=0;for(;n<=e;){let r=s.indexOf(i,n);if(r<0||r>e)break;if(r===e)return t;t++,n=r+Math.max(1,i.length)}return t}function Q(s,i){return At(s,i)}function Ct(s,i,e,t=50){let n=Math.max(0,i-t),r=Math.min(s.length,e+t);return{contextBefore:s.slice(n,i),contextAfter:s.slice(e,r)}}function vn(s,i){let e=[],t=s.split(` `),n=i.split(` -`),r=[],o=[],l=0;for(let u of t)r.push(l),l+=u.length+1;l=0;for(let u of n)o.push(l),l+=u.length+1;let c=mn(t,n),d=0,p=0,m=0;for(;d=c.length||t[d]!==c[m]);)h=r[d]+t[d].length,d=c.length||n[p]!==c[m]);)f=o[p]+n[p].length,pd.aIdx-p.aIdx);let l=hn(o.map(d=>d.bIdx)),c=[];for(let d of l)c.push(o[d].line);return c}function un(s,i){let e=s.length,t=i.length,n=new Uint16Array(t+1),r=new Uint16Array(t+1);for(let p=1;p<=e;p++){for(let m=1;m<=t;m++)s[p-1]===i[m-1]?r[m]=n[m-1]+1:r[m]=Math.max(n[m],r[m-1]);[n,r]=[r,n],r.fill(0)}let o=[],l=e,c=t,d=[];for(let p=0;p<=e;p++)d[p]=new Array(t+1).fill(0);for(let p=1;p<=e;p++)for(let m=1;m<=t;m++)s[p-1]===i[m-1]?d[p][m]=d[p-1][m-1]+1:d[p][m]=Math.max(d[p-1][m],d[p][m-1]);for(;l>0&&c>0;)s[l-1]===i[c-1]?(o.unshift(s[l-1]),l--,c--):d[l-1][c]>d[l][c-1]?l--:c--;return o}function hn(s){if(s.length===0)return[];let i=[],e=new Array(s.length).fill(-1),t=[];for(let o=0;o>1;s[i[p]]0&&(e[o]=i[c-1]),c===i.length?i.push(o):i[c]=o}let n=[],r=i[i.length-1];for(;r>=0;)n.unshift(r),r=e[r];return n}function gn(s,i,e){let t=[{oldPos:0,newPos:0}];for(let r of s){let o=t[t.length-1];if(r.oldStart>o.oldPos){let l=r.oldStart-o.oldPos;t.push({oldPos:r.oldStart,newPos:o.newPos+l})}t.push({oldPos:r.oldEnd,newPos:r.newEnd})}let n=t[t.length-1];if(n.oldPos>1;s[l].oldPos<=i?e=l:t=l-1}let n=s[e];if(n.oldPos===i)return n.newPos;let r=e+1;if(re)break;if(r===e)return t;t++,n=r+Math.max(1,i.length)}return t}function St(s,i,e,t=50){if(e.length===0)return[];if(s===i)return e.map(l=>({id:l.id,status:"healed",patch:{}}));let n=pn(s,i),r=gn(n,s.length,i.length),o=[];for(let l of e){if(!l.selectedText){o.push({id:l.id,status:"drifted",patch:{}});continue}let c=s.indexOf(l.selectedText,l.lineHint>0?Math.max(0,s.indexOf(` -`,0)):0),d=-1,p=-1;if(l.contextBefore&&l.contextAfter){let C=l.contextBefore+l.selectedText+l.contextAfter,P=s.indexOf(C);P>=0&&(d=P+l.contextBefore.length,p=d+l.selectedText.length)}if(d<0){let C=s.indexOf(l.selectedText);C>=0&&(d=C,p=C+l.selectedText.length)}if(d<0){o.push({id:l.id,status:"drifted",patch:{}});continue}let m=At(r,d),u=At(r,p);if(u<=m||u>i.length){o.push({id:l.id,status:"drifted",patch:{}});continue}let g=i.slice(m,u),h=wn(l.selectedText,g);if(h<.3){o.push({id:l.id,status:"drifted",similarity:h,patch:{}});continue}let f=Math.max(0,m-t),b=Math.min(i.length,u+t),y=i.slice(f,m),S=i.slice(u,b),A=fn(i,m),v=vn(i,g,m);o.push({id:l.id,status:"healed",similarity:h,patch:{selectedText:g,contextBefore:y,contextAfter:S,lineHint:A,occurrenceIndex:v}})}return o}function wn(s,i){if(s===i)return 1;if(!s||!i)return 0;if(s.includes(i)||i.includes(s))return Math.min(s.length,i.length)/Math.max(s.length,i.length);let e=Ct(s),t=Ct(i),n=0,r=0,o=new Set([...e.keys(),...t.keys()]);for(let l of o){let c=e.get(l)??0,d=t.get(l)??0;n+=Math.min(c,d),r+=Math.max(c,d)}return r>0?n/r:0}function Ct(s){let i=new Map;for(let e of s)i.set(e,(i.get(e)??0)+1);return i}var _=require("@codemirror/view"),K=require("@codemirror/state");var oe=K.StateEffect.define(),xe=K.StateField.define({create:()=>[],update(s,i){for(let e of i.effects)if(e.is(oe))return e.value;return s}}),bn=K.StateField.define({create(s){return Je(s.doc.toString(),s.field(xe))},update(s,i){let e=null;for(let t of i.effects)t.is(oe)&&(e=t.value);return e?Je(i.state.doc.toString(),e):i.docChanged?Je(i.state.doc.toString(),i.state.field(xe)):s},provide:s=>_.EditorView.decorations.from(s)});function Je(s,i){let e=[];for(let r of i){let o=$(s,r);if(o.status==="drifted"||o.from===void 0||o.to===void 0)continue;let l=Pt(r,o.status);l&&e.push({from:o.from,to:o.to,deco:_.Decoration.mark({class:l,attributes:{"data-prm-id":r.id}})})}let t=xn(e),n=new K.RangeSetBuilder;for(let r of t)n.add(r.from,r.to,r.deco);return n.finish()}function xn(s){if(s.length===0)return s;s.sort((n,r)=>n.from-r.from||n.to-r.to);let i=[],e=new Set;for(let n of s)e.add(n.from),e.add(n.to);let t=Array.from(e).sort((n,r)=>n-r);for(let n=0;nm.from<=r&&m.to>=o);if(l.length===0)continue;let c=new Set,d=[];for(let m of l){let u=m.deco.spec;u.class&&u.class.split(/\s+/).forEach(g=>c.add(g)),u.attributes?.["data-prm-id"]&&d.push(u.attributes["data-prm-id"])}let p=_.Decoration.mark({class:Array.from(c).join(" "),attributes:d.length>0?{"data-prm-id":d.join(",")}:void 0});i.push({from:r,to:o,deco:p})}return i}function Pt(s,i){let e=i==="fuzzy"?" cm-promptuary-fuzzy":"",t=i==="auto-healed"?" cm-promptuary-auto-healed":"";if(s.type==="highlight")return`cm-promptuary-highlight cm-promptuary-highlight-${s.highlightColor??"yellow"}${e}${t}`;if(s.type==="note")return`cm-promptuary-highlight cm-promptuary-highlight-${s.highlightColor??"yellow"}${e}${t}`;if(s.type==="review"){let n="cm-promptuary-review";return s.strike&&(n+=" cm-promptuary-strike"),n+e+t}return null}var ye="prm-table-hl",Ye=class{constructor(i){this.rafId=null;this.observer=null;this.view=i,this.startObserving()}startObserving(){this.observer=new MutationObserver(i=>{i.some(t=>{let n=t.target;if(typeof n.closest=="function"&&n.closest(".cm-table-widget"))return!0;for(let r of Array.from(t.addedNodes).concat(Array.from(t.removedNodes))){let o=r;if(typeof o.closest=="function"&&(o.classList?.contains("cm-editor")||o.querySelector?.(".cm-editor")))return!0}return!1})&&this.scheduleApply()}),this.observer.observe(this.view.dom,{childList:!0,subtree:!0})}scheduleApply(){this.rafId!==null&&window.cancelAnimationFrame(this.rafId),this.rafId=window.requestAnimationFrame(()=>{this.rafId=null,this.applyTableHighlights(this.view)})}update(i){let e=i.transactions.some(t=>t.effects.some(n=>n.is(oe)));!i.docChanged&&!i.viewportChanged&&!e||this.scheduleApply()}destroy(){this.rafId!==null&&(window.cancelAnimationFrame(this.rafId),this.rafId=null),this.observer?.disconnect(),this.observer=null}applyTableHighlights(i){Array.from(i.dom.querySelectorAll(`.${ye}`)).forEach(o=>{let l=o.parentNode;if(l){for(;o.firstChild;)l.insertBefore(o.firstChild,o);l.removeChild(o),l.normalize()}});let e=i.state.field(xe);if(e.length===0)return;let t=i.state.doc.toString(),n=[];for(let o of e){if(!o.selectedText)continue;let l=$(t,o);if(l.status==="drifted"||l.from===void 0)continue;let c=Pt(o,l.status);c&&n.push({selectedText:o.selectedText,cls:c})}if(n.length===0)return;for(let o of Array.from(i.dom.querySelectorAll(".cm-line"))){if(o.querySelector("[class*='cm-promptuary']"))continue;let l;try{let d=i.posAtDOM(o,0);l=i.state.doc.lineAt(d).text}catch{continue}let c=l.trim();if(!(!c.startsWith("|")&&!c.endsWith("|")))for(let{selectedText:d,cls:p}of n)l.includes(d)&&kt(o,d,p)}let r=i.dom.querySelectorAll(".cm-table-widget");for(let o of Array.from(r)){let l=o.querySelectorAll("td, th");for(let c of Array.from(l)){if(c.querySelector(".cm-editor")||c.querySelector(`.${ye}`))continue;let d=c.textContent??"";for(let{selectedText:p,cls:m}of n)d.includes(p)&&kt(c,p,m)}}}};function kt(s,i,e){let t=activeDocument.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode(r){return r.parentElement?.closest(`.${ye}`)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),n;for(;n=t.nextNode();){let r=n,o=r.textContent??"",l=o.indexOf(i);if(l===-1)continue;let c=o.slice(0,l),d=o.slice(l+i.length),p=r.parentNode,m=activeDocument.createElement("span");m.className=`${e} ${ye}`,m.textContent=i,c&&p.insertBefore(activeDocument.createTextNode(c),r),p.insertBefore(m,r),d&&p.insertBefore(activeDocument.createTextNode(d),r),p.removeChild(r);return}}function Et(){return[xe,bn,_.ViewPlugin.fromClass(Ye)]}function Ae(s){let i=!1,e=null;return s.addEventListener("compositionstart",()=>{e!==null&&(window.clearTimeout(e),e=null),i=!0}),s.addEventListener("compositionend",()=>{e!==null&&window.clearTimeout(e),e=window.setTimeout(()=>{i=!1,e=null},0)}),t=>i||t.isComposing||t.keyCode===229}var Ce=class{constructor(i,e){this.app=i;this.cb=e;this.mode="reading";this.current=null;this.renderedMode=null;this.noteExpanded=!1;this.selectedColor="yellow";this.strikePending=!1;this.pendingStrikeId=null;this.editingAnnotationId=null;this.isEditing=!1;this.el=activeDocument.createElement("div"),this.el.className="promptuary-popover",this.el.addClass("prm-hidden"),activeDocument.body.appendChild(this.el)}destroy(){this.el.remove(),this.current=null,this.renderedMode=null}setMode(i){if(i===this.mode)return;let e=this.noteExpanded?this.el.querySelector(".prm-popover-note-input")?.value??"":"";this.mode=i,this.renderedMode=null,this.noteExpanded=!1,this.cleanupPendingStrike(),this.current&&(this.render(),e&&this.expandNoteAreaWithText(e,this.selectedColor))}show(i,e,t){if(e===t)return this.hide(),!1;let n=this.current?this.current.from!==e||this.current.to!==t:!0;return this.current={view:i,from:e,to:t},(this.renderedMode!==this.mode||n)&&this.render(),this.position(i,e,t),!0}showForAnnotation(i,e,t,n){this.isEditing=!0,this.editingAnnotationId=n.id;let r=n.type==="review"?"reviewing":"reading";this.mode!==r&&(this.mode=r,this.cb.onModeSwitch(r)),this.renderedMode=null,this.noteExpanded=!1,this.current={view:i,from:e,to:t},this.render(),this.position(i,e,t),(n.noteText||n.reviewText)&&this.expandNoteAreaWithText(n.noteText||n.reviewText||"",n.highlightColor||"yellow")}hide(){this.el.addClass("prm-hidden"),this.current=null,this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.editingAnnotationId=null,this.isEditing=!1,this.renderedMode=null}cleanupPendingStrike(){this.strikePending=!1,this.pendingStrikeId=null}position(i,e,t){let n=window.getSelection();if(n&&n.rangeCount>0&&!n.isCollapsed)try{let h=n.getRangeAt(0).getBoundingClientRect();if(h.width>0&&h.height>0){let f=h.bottom+6,b=this.el.offsetWidth||200,y=Math.max(8,Math.min(h.left,window.innerWidth-b-8));this.el.style.setProperty("--prm-pos-top",`${f}px`),this.el.style.setProperty("--prm-pos-left",`${y}px`),this.el.addClass("prm-dynamic-position"),this.el.removeClass("prm-hidden");return}}catch{}let r=i.coordsAtPos(t),o=i.coordsAtPos(e);if(!r&&!o)return;let l=r??o,c=l.bottom+6,d=o?o.left:l.left,p=this.el.offsetWidth||200,m=window.innerWidth-p-8,u=Math.max(8,Math.min(d,m));this.el.style.setProperty("--prm-pos-top",`${c}px`),this.el.style.setProperty("--prm-pos-left",`${u}px`),this.el.addClass("prm-dynamic-position"),this.el.removeClass("prm-hidden")}render(){this.el.empty(),this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.renderTitleRow(),this.mode==="reviewing"?this.renderReviewingActions():this.renderReadingActions(),this.renderedMode=this.mode}renderTitleRow(){let i=this.el.createDiv({cls:"prm-popover-title-row"}),e=i.createSpan({cls:"prm-popover-title",text:this.editingAnnotationId?a("popover.title.edit"):a("popover.title.add")});this.buildModeCapsule(i)}buildModeCapsule(i){let e=i.createDiv({cls:"prm-popover-capsule"}),t=[["reading",a("popover.mode.reading")],["reviewing",a("popover.mode.review")]];for(let[n,r]of t){let o=e.createEl("button",{text:r});this.mode===n&&o.addClass("active"),o.onmousedown=l=>{l.preventDefault(),n!==this.mode&&this.cb.onModeSwitch(n)}}}renderReadingActions(){let i=this.el.createDiv({cls:"prm-popover-actions"}),e=["yellow","blue","green","purple"];for(let n of e){let r=i.createDiv({cls:`prm-color ${n}`});n===this.selectedColor&&r.addClass("active"),r.title=a("popover.color.highlight",{color:a(`color.${n}`)}),r.onmousedown=o=>{o.preventDefault(),i.querySelectorAll(".prm-color").forEach(l=>l.removeClass("active")),r.addClass("active"),this.selectedColor=n,this.noteExpanded?this.cb.onHighlight(n,this.editingAnnotationId??void 0):(this.cb.onHighlight(n,this.editingAnnotationId??void 0),this.hide())}}i.createDiv({cls:"prm-divider"});let t=i.createEl("button",{cls:"prm-note-btn",text:a("popover.btn.addNote")});t.title=a("popover.btn.addNoteTitle"),t.onmousedown=n=>{n.preventDefault(),this.toggleNoteArea()}}renderReviewingActions(){let i=this.el.createDiv({cls:"prm-popover-actions"}),e=i.createEl("button",{cls:"prm-delete-btn",text:a("popover.btn.delete")});e.title=a("popover.btn.deleteTitle"),e.onmousedown=r=>{r.preventDefault(),this.strikePending=!this.strikePending,e.toggleClass("active",this.strikePending),this.editingAnnotationId?this.cb.onReview("",this.strikePending,this.editingAnnotationId):this.strikePending?this.pendingStrikeId||this.cb.onStrikeCreate().then(o=>{this.pendingStrikeId=o}):this.pendingStrikeId&&(this.cb.onStrikeRemove(this.pendingStrikeId),this.pendingStrikeId=null),this.updateStrikeIndicator(),this.updateReviewConfirmState()};let t=i.createEl("button",{cls:"prm-note-btn",text:a("popover.btn.reviewNote")});t.title=a("popover.btn.reviewNoteTitle"),t.onmousedown=r=>{r.preventDefault(),this.toggleNoteArea()};let n=i.createEl("button",{cls:"prm-review-confirm-btn",text:"\u2713"});n.title=a("popover.btn.confirmDelete"),n.addClass("prm-hidden"),n.onmousedown=r=>{r.preventDefault(),this.editingAnnotationId?this.hide():(this.pendingStrikeId=null,this.hide())}}updateReviewConfirmState(){let i=this.el.querySelector(".prm-review-confirm-btn");i&&i.toggleClass("prm-hidden",!(this.strikePending&&!this.noteExpanded))}updateStrikeIndicator(){}updateNoteColorIndicator(){}expandNoteAreaWithText(i,e){this.selectedColor=e,this.toggleNoteArea();let t=this.el.querySelector(".prm-popover-note-input");t&&(t.value=i,window.requestAnimationFrame(()=>{t.focus(),t.select()}))}toggleNoteArea(){if(this.noteExpanded){let l=this.el.querySelector(".prm-popover-note-area");l&&l.remove(),this.noteExpanded=!1,this.updateReviewConfirmState(),this.current&&this.position(this.current.view,this.current.from,this.current.to);return}this.noteExpanded=!0,this.updateReviewConfirmState();let i=this.el.createDiv({cls:"prm-popover-note-area"}),t=i.createDiv({cls:"prm-popover-note-input-wrap"}).createEl("input",{type:"text",cls:"prm-popover-note-input"});t.placeholder=this.mode==="reviewing"?a("popover.placeholder.review"):a("popover.placeholder.note");let n=Ae(t),o=i.createDiv({cls:"prm-popover-note-footer"}).createEl("button",{cls:"prm-popover-note-save",text:a("popover.btn.save")});t.onkeydown=l=>{if(l.key==="Enter"){if(n(l))return;l.preventDefault();let c=t.value.trim();c&&this.saveNote(c)}else if(l.key==="Escape"){if(n(l))return;this.hide()}},o.onmousedown=l=>{l.preventDefault();let c=t.value.trim();c&&this.saveNote(c)},this.current&&this.position(this.current.view,this.current.from,this.current.to),window.requestAnimationFrame(()=>t.focus())}saveNote(i){let e=this.editingAnnotationId??void 0;this.mode==="reviewing"?this.pendingStrikeId?(this.cb.onReview(i,!0,this.pendingStrikeId),this.pendingStrikeId=null):this.cb.onReview(i,this.strikePending,e):this.cb.onNote(i,this.selectedColor,e),this.hide()}};var Se=class{constructor(i,e){this.app=i;this.cb=e;this.mode="reading";this.active=!1;this.noteExpanded=!1;this.selectedColor="yellow";this.strikePending=!1;this.pendingStrikeId=null;this.el=activeDocument.createElement("div"),this.el.className="promptuary-bottom-toolbar",this.el.addClass("prm-hidden"),activeDocument.body.appendChild(this.el)}destroy(){this.el.remove(),this.active=!1}setMode(i){this.mode=i,this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.active&&this.render()}show(){this.active=!0,this.render(),this.el.removeClass("prm-hidden")}hide(){this.active=!1,this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.el.addClass("prm-hidden")}render(){this.el.empty(),this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.renderModeCapsule(),this.mode==="reviewing"?this.renderReviewingActions():this.renderReadingActions()}renderModeCapsule(){let i=this.el.createDiv({cls:"prm-popover-capsule"}),e=[["reading",a("toolbar.mode.reading")],["reviewing",a("toolbar.mode.review")]];for(let[t,n]of e){let r=i.createEl("button",{text:n});this.mode===t&&r.addClass("active"),r.onclick=()=>{t!==this.mode&&this.cb.onModeSwitch(t)}}}renderReadingActions(){let i=this.el.createDiv({cls:"prm-popover-actions"}),e=["yellow","blue","green","purple"];for(let r of e){let o=i.createDiv({cls:`prm-color ${r}`});o.title=a("toolbar.color.highlight",{color:a(`color.${r}`)}),o.onclick=()=>{this.selectedColor=r,this.noteExpanded?this.updateNoteColorIndicator():(this.cb.onHighlight(r),this.hide())}}let t=i.createEl("button",{text:a("toolbar.btn.addNote")});t.onclick=()=>{this.toggleNoteArea()};let n=i.createEl("button",{text:"\xD7"});n.onclick=()=>this.hide()}renderReviewingActions(){let i=this.el.createDiv({cls:"prm-popover-actions"}),e=i.createEl("button",{cls:"prm-delete-btn",text:a("toolbar.btn.delete")});e.title=a("toolbar.btn.deleteTitle"),e.onclick=()=>{this.strikePending=!this.strikePending,e.toggleClass("active",this.strikePending),this.strikePending?this.pendingStrikeId||this.cb.onStrikeCreate().then(o=>{this.pendingStrikeId=o}):this.pendingStrikeId&&(this.cb.onStrikeRemove(this.pendingStrikeId),this.pendingStrikeId=null),this.updateStrikeIndicator(),this.updateReviewConfirmState()};let t=i.createEl("button",{cls:"prm-note-btn",text:a("toolbar.btn.reviewNote")});t.title=a("toolbar.btn.reviewNoteTitle"),t.onclick=()=>{this.toggleNoteArea()};let n=i.createEl("button",{cls:"prm-review-confirm-btn",text:"\u2713"});n.title=a("toolbar.btn.confirmDelete"),n.addClass("prm-hidden"),n.onclick=()=>{this.pendingStrikeId=null,this.hide()};let r=i.createEl("button",{text:"\xD7"});r.onclick=()=>this.hide()}updateReviewConfirmState(){let i=this.el.querySelector(".prm-review-confirm-btn");i&&i.toggleClass("prm-hidden",!(this.strikePending&&!this.noteExpanded))}updateStrikeIndicator(){let i=this.el.querySelector(".prm-popover-note-header");if(!i)return;let e=i.querySelector(".prm-strike-indicator");this.strikePending?e||(e=i.createSpan({cls:"prm-strike-indicator",text:a("toolbar.label.delete")})):e&&e.remove()}updateNoteColorIndicator(){let i=this.el.querySelector(".prm-popover-note-header .prm-note-dot"),e=this.el.querySelector(".prm-popover-note-header .prm-note-label");if(!i||!e)return;let t=["yellow","blue","green","purple","orange"];for(let n of t)i.removeClass(n),e.removeClass(n);i.addClass(this.selectedColor),e.addClass(this.selectedColor)}toggleNoteArea(){if(this.noteExpanded){let c=this.el.querySelector(".prm-popover-note-area");c&&c.remove(),this.noteExpanded=!1,this.updateReviewConfirmState();return}this.noteExpanded=!0,this.updateReviewConfirmState();let i=this.el.createDiv({cls:"prm-popover-note-area"}),e=i.createDiv({cls:"prm-popover-note-header"});this.mode==="reviewing"?(e.createDiv({cls:"prm-note-dot orange"}),e.createDiv({cls:"prm-divider"}),e.createSpan({cls:"prm-note-label orange",text:a("toolbar.label.review")}),this.strikePending&&e.createSpan({cls:"prm-strike-indicator",text:a("toolbar.label.delete")})):(e.createDiv({cls:`prm-note-dot ${this.selectedColor}`}),e.createDiv({cls:"prm-divider"}),e.createSpan({cls:`prm-note-label ${this.selectedColor}`,text:a("toolbar.label.note")}));let n=i.createDiv({cls:"prm-popover-note-input-wrap"}).createEl("input",{type:"text",cls:"prm-popover-note-input"});n.placeholder=this.mode==="reviewing"?a("toolbar.placeholder.review"):a("toolbar.placeholder.note");let r=Ae(n),l=i.createDiv({cls:"prm-popover-note-footer"}).createEl("button",{cls:"prm-popover-note-save",text:a("toolbar.btn.save")});n.onkeydown=c=>{if(c.key==="Enter"){if(r(c))return;c.preventDefault();let d=n.value.trim();d&&this.saveNote(d)}else if(c.key==="Escape"){if(r(c))return;this.hide()}},l.onclick=()=>{let c=n.value.trim();c&&this.saveNote(c)},window.requestAnimationFrame(()=>n.focus())}saveNote(i){this.mode==="reviewing"?this.pendingStrikeId?(this.cb.onReview(i,!0,this.pendingStrikeId),this.pendingStrikeId=null):this.cb.onReview(i,this.strikePending):this.cb.onNote(i,this.selectedColor),this.hide()}};var N=require("obsidian");var se=class extends N.Modal{constructor(i,e="",t){super(i),this.value=e,this.onSubmit=t}onOpen(){let{contentEl:i}=this;i.createEl("h3",{text:a("notemodal.note.title")}),new N.Setting(i).setName(a("notemodal.note.content")).addTextArea(e=>{e.setValue(this.value).onChange(t=>{this.value=t}),e.inputEl.addClass("prm-input-full-width"),e.inputEl.addClass("prm-input-min-height"),e.inputEl.addEventListener("keydown",t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.submit())}),window.setTimeout(()=>e.inputEl.focus(),50)}),new N.Setting(i).addButton(e=>e.setButtonText(a("common.cancel")).onClick(()=>this.close())).addButton(e=>e.setButtonText(a("common.save")).setCta().onClick(()=>this.submit()))}submit(){let i=this.value.trim();if(!i){this.close();return}this.onSubmit(i),this.close()}onClose(){this.contentEl.empty()}},ae=class extends N.Modal{constructor(i,e={},t){super(i),this.value=e.text??"",this.strike=e.strike??!1,this.isEdit=e.isEdit??!1,this.onSubmit=t}onOpen(){let{contentEl:i}=this;i.createEl("h3",{text:a("notemodal.review.title")}),new N.Setting(i).setName(a("notemodal.review.content")).addTextArea(e=>{e.setValue(this.value).onChange(t=>{this.value=t}),e.inputEl.addClass("prm-input-full-width"),e.inputEl.addClass("prm-input-min-height"),e.inputEl.addEventListener("keydown",t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.submit())}),window.setTimeout(()=>e.inputEl.focus(),50)}),new N.Setting(i).setName(a("notemodal.review.strikethrough")).setDesc(a("notemodal.review.strikethroughDesc")).addToggle(e=>e.setValue(this.strike).onChange(t=>this.strike=t)),new N.Setting(i).addButton(e=>e.setButtonText(a("common.cancel")).onClick(()=>this.close())).addButton(e=>e.setButtonText(a("common.save")).setCta().onClick(()=>this.submit()))}submit(){if(!this.isEdit&&!this.value.trim()&&!this.strike){this.close();return}this.onSubmit(this.value.trim(),this.strike),this.close()}};var x=require("obsidian");function Dt(s){return"'"+s.replace(/'/g,"'\\''")+"'"}var yn=/[|&;<>`$(){}]/;function ke(s){let e=s.replace(/\{\{[a-zA-Z]+\}\}/g,"").match(yn);if(e)throw new Error(a("shell.error.forbiddenChar",{chars:e[0]}))}var An=new Set(["vaultPath","instructionFile","filePath","fileName","prompt"]);function Pe(s){let i=/\{\{([a-zA-Z]+)\}\}/g,e=[],t;for(;(t=i.exec(s))!==null;){let n=t[1];if(!An.has(n))throw new Error(a("shell.error.unknownVariable",{var:n}));e.includes(n)||e.push(n)}return e}var G=[{id:"claude",label:"Claude Code",vendor:"Anthropic",detectCmd:"which claude",template:'cd {{vaultPath}} && claude "\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6"',installHint:"npm i -g @anthropic-ai/claude-code",isPreset:!0},{id:"codex",label:"Codex CLI",vendor:"OpenAI",detectCmd:"which codex",template:'cd {{vaultPath}} && codex "\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6"',installHint:"npm i -g @openai/codex",isPreset:!0},{id:"aider",label:"Aider",vendor:"Paul Gauthier",detectCmd:"which aider",template:'cd {{vaultPath}} && aider --msg "\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6"',installHint:"pip install aider-chat",isPreset:!0},{id:"gemini",label:"Gemini CLI",vendor:"Google",detectCmd:"which gemini",template:'cd {{vaultPath}} && gemini "\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6"',installHint:"npm i -g @google/gemini-cli",isPreset:!0}],V=class{constructor(){this.customRules=[]}loadFromJSON(i){Array.isArray(i)&&(this.customRules=i.filter(e=>{if(!e.id||!e.label||!e.template||!e.detectCmd)return!1;try{return ke(e.template),Pe(e.template),!0}catch{return!1}}))}toJSON(){return this.customRules}allRules(){return[...G,...this.customRules]}getCustomRules(){return[...this.customRules]}getById(i){return this.allRules().find(e=>e.id===i)}add(i){if(ke(i.template),Pe(i.template),this.allRules().some(e=>e.id===i.id))throw new Error(a("cmdrule.error.idExists",{id:i.id}));this.customRules.push({...i,isPreset:!1})}update(i,e){if(G.some(r=>r.id===i))throw new Error(a("cmdrule.error.presetNotEditable"));let t=this.customRules.findIndex(r=>r.id===i);if(t===-1)throw new Error(a("cmdrule.error.notFound",{id:i}));let n={...this.customRules[t],...e};e.template&&(ke(n.template),Pe(n.template)),this.customRules[t]=n}remove(i){if(G.some(e=>e.id===i))throw new Error(a("cmdrule.error.presetNotDeletable"));this.customRules=this.customRules.filter(e=>e.id!==i)}};var Tt=require("obsidian"),R=()=>Tt.Platform.isMobile;var Ee=window.require??require,{execSync:De,exec:Rt}=Ee("child_process"),le=Ee("fs"),It=Ee("os"),Ze=Ee("path");function Cn(){let s=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin",`${process.env.HOME??""}/.local/bin`,`${process.env.HOME??""}/.npm-global/bin`,`${process.env.HOME??""}/.cargo/bin`].filter(Boolean),i=process.env.PATH??"",e=[...new Set([...i.split(":"),...s])].join(":");return{...process.env,PATH:e}}function Te(s){if(R())return[];let i=Cn();return s.map(e=>{let t=!1;try{De(e.detectCmd,{encoding:"utf-8",timeout:5e3,stdio:"pipe",env:i}),t=!0}catch{t=!1}return{rule:e,installed:t}})}ce();var En={provider:"anthropic",apiKey:"",model:"",customEndpoint:"",maxTokens:4096},U={language:"auto",defaultMode:"reading",contextSpan:50,sidecarDir:".promptuary/annotations",exportDir:".promptuary/exports",includeReadingNotesInExport:!1,terminalApp:"Terminal",customCommandRules:[],apiSettings:{...En}},et=class extends x.Modal{constructor(e,t){super(e);this.existingIds=t}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{contentEl:e,modalEl:t}=this;e.empty(),e.addClass("prm-add-rule-modal"),t.addClass("prm-add-rule-modal");let r=e.createDiv({cls:"prm-arm-header"}).createDiv({cls:"prm-arm-header-left"}),o=r.createDiv({cls:"prm-arm-icon"});(0,x.setIcon)(o,"zap");let l=r.createDiv({});l.createDiv({cls:"prm-arm-title",text:a("addrule.title")}),l.createDiv({cls:"prm-arm-subtitle",text:a("addrule.subtitle")});let c=e.createDiv({cls:"prm-arm-form"}),d="",p="",m="",u="",g="";new x.Setting(c).setName(a("addrule.id.name")).setDesc(a("addrule.id.desc")).addText(v=>v.setPlaceholder(a("addrule.id.placeholder")).onChange(C=>d=C.trim())),new x.Setting(c).setName(a("addrule.label.name")).setDesc(a("addrule.label.desc")).addText(v=>v.setPlaceholder(a("addrule.label.placeholder")).onChange(C=>p=C.trim())),new x.Setting(c).setName(a("addrule.detectCmd.name")).setDesc(a("addrule.detectCmd.desc")).addText(v=>v.setPlaceholder(a("addrule.detectCmd.placeholder")).onChange(C=>m=C.trim())),new x.Setting(c).setName(a("addrule.command.name")).setDesc(a("addrule.command.desc")).addTextArea(v=>v.setPlaceholder(a("addrule.command.placeholder")).onChange(C=>u=C.trim())),new x.Setting(c).setName(a("addrule.installHint.name")).setDesc(a("addrule.installHint.desc")).addText(v=>v.setPlaceholder(a("addrule.installHint.placeholder")).onChange(C=>g=C.trim()));let h=c.createDiv({cls:"prm-arm-var-ref"});h.createDiv({cls:"prm-arm-var-title",text:a("addrule.varTitle")});let f=h.createDiv({cls:"prm-arm-var-grid"}),b=[["{{vaultPath}}",a("addrule.var.vaultPath")],["{{instructionFile}}",a("addrule.var.instructionFile")],["{{filePath}}",a("addrule.var.filePath")],["{{fileName}}",a("addrule.var.fileName")],["{{prompt}}",a("addrule.var.prompt")]];for(let[v,C]of b){let P=f.createDiv({cls:"prm-arm-var-item"});P.createDiv({cls:"prm-arm-var-code",text:v}),P.createDiv({cls:"prm-arm-var-desc",text:C})}let y=e.createDiv({cls:"prm-arm-footer"}),S=y.createEl("button",{cls:"prm-arm-btn-cancel",text:a("addrule.btn.cancel")});S.onclick=()=>this.close();let A=y.createEl("button",{cls:"prm-arm-btn-save",text:a("addrule.btn.add")});A.onclick=()=>{if(!d||!p||!u||!m){new x.Notice(a("addrule.notice.requiredFields"));return}if(this.existingIds.includes(d)){new x.Notice(a("addrule.notice.idExists",{id:d}));return}try{let v=new V;v.loadFromJSON([]),v.add({id:d,label:p,detectCmd:m,template:u,installHint:g||a("addrule.defaultInstallHint")})}catch(v){new x.Notice(a("addrule.notice.validationFailed",{error:v.message}));return}this.resolve?.({id:d,label:p,detectCmd:m,template:u,installHint:g||a("addrule.defaultInstallHint")}),this.close()}}onClose(){this.resolve?.(null),this.contentEl.empty()}},Me=class extends x.PluginSettingTab{constructor(e,t){super(e,t);this.plugin=t}display(){let{containerEl:e}=this;e.empty();let n=e.createDiv({cls:"prm-settings-header"}).createDiv({cls:"prm-settings-header-left"}),r=n.createDiv({cls:"prm-settings-page-icon"});if(this.plugin.logoUrl){let o=r.createEl("img",{cls:"prm-logo-img"});o.src=this.plugin.logoUrl,o.alt="Promptuary"}else(0,x.setIcon)(r,"prm-highlighter");n.createDiv({cls:"prm-settings-page-title",text:"Promptuary"}),this.renderSection(e,{icon:"file-text",title:a("settings.section.basic"),desc:a("settings.section.basicDesc"),open:!0,render:o=>this.renderBasicSettings(o)}),R()||(this.renderSection(e,{icon:"bot",title:a("settings.section.agent"),desc:a("settings.section.agentDesc"),open:!0,render:o=>this.renderAgentSettings(o)}),this.renderSection(e,{icon:"key-round",title:a("settings.section.api"),desc:a("settings.section.apiDesc"),open:!this.plugin.settings.apiSettings.apiKey,render:o=>this.renderAPISettings(o)}))}renderSection(e,t){let n=e.createDiv({cls:"prm-settings-section"}),r=n.createDiv({cls:"prm-settings-section-header"}),o=r.createDiv({cls:"prm-settings-section-left"}),l=o.createDiv({cls:"prm-settings-section-icon"});(0,x.setIcon)(l,t.icon);let c=o.createDiv({cls:"prm-settings-section-text"});c.createDiv({cls:"prm-settings-section-title",text:t.title}),c.createDiv({cls:"prm-settings-section-desc",text:t.desc});let d=r.createDiv({cls:"prm-settings-section-chevron"});(0,x.setIcon)(d,"chevron-down");let p=n.createDiv({cls:"prm-settings-section-body"});t.open&&(p.addClass("is-open"),d.addClass("is-open")),r.onclick=()=>{let m=p.hasClass("is-open");p.toggleClass("is-open",!m),d.toggleClass("is-open",!m)},t.render(p)}renderBasicSettings(e){new x.Setting(e).setName(a("settings.language.name")).setDesc(a("settings.language.desc")).addDropdown(t=>{t.addOption("auto",a("settings.language.auto")).addOption("zh-CN",a("settings.language.zhCN")).addOption("en",a("settings.language.en")).setValue(this.plugin.settings.language).onChange(async n=>{this.plugin.settings.language=n,await this.plugin.saveSettings(),ge(n);let r=this.app;r.plugins?.disablePlugin&&r.plugins?.enablePlugin&&(await r.plugins.disablePlugin("promptuary"),await r.plugins.enablePlugin("promptuary"))})}),new x.Setting(e).setName(a("settings.defaultMode.name")).setDesc(a("settings.defaultMode.desc")).addDropdown(t=>t.addOption("reading",a("settings.defaultMode.reading")).addOption("reviewing",a("settings.defaultMode.review")).addOption("all",a("sidebar.mode.all")).setValue(this.plugin.settings.defaultMode).onChange(async n=>{this.plugin.settings.defaultMode=n,await this.plugin.saveSettings()})),new x.Setting(e).setName(a("settings.contextSpan.name")).setDesc(a("settings.contextSpan.desc")).addText(t=>t.setValue(String(this.plugin.settings.contextSpan)).onChange(async n=>{let r=parseInt(n,10);!Number.isNaN(r)&&r>0&&(this.plugin.settings.contextSpan=r,await this.plugin.saveSettings())})),new x.Setting(e).setName(a("settings.sidecarDir.name")).setDesc(a("settings.sidecarDir.desc")).addText(t=>t.setValue(this.plugin.settings.sidecarDir).onChange(async n=>{this.plugin.settings.sidecarDir=n.trim()||U.sidecarDir,await this.plugin.saveSettings()})),new x.Setting(e).setName(a("settings.exportDir.name")).setDesc(a("settings.exportDir.desc")).addText(t=>t.setValue(this.plugin.settings.exportDir).onChange(async n=>{this.plugin.settings.exportDir=n.trim()||U.exportDir,await this.plugin.saveSettings()})),new x.Setting(e).setName(a("settings.includeReadingNotes.name")).setDesc(a("settings.includeReadingNotes.desc")).addToggle(t=>t.setValue(this.plugin.settings.includeReadingNotesInExport).onChange(async n=>{this.plugin.settings.includeReadingNotesInExport=n,await this.plugin.saveSettings()}))}renderAgentSettings(e){new x.Setting(e).setName(a("settings.terminalApp.name")).setDesc(a("settings.terminalApp.desc")).addDropdown(u=>{u.addOption("Terminal",a("settings.terminalApp.terminal")+a("settings.terminalApp.defaultSuffix")).addOption("iTerm2",a("settings.terminalApp.iterm")).setValue(this.plugin.settings.terminalApp).onChange(async g=>{this.plugin.settings.terminalApp=g,await this.plugin.saveSettings()})});let t=Te(G),n=e.createDiv({cls:"prm-agent-cards"});for(let u of t){let g=n.createDiv({cls:`prm-agent-card ${u.installed?"installed":"not-installed"}`});g.createDiv({cls:"prm-agent-card-avatar"}).setText(u.rule.label.charAt(0));let f=g.createDiv({cls:"prm-agent-card-info"}),b=f.createDiv({cls:"prm-agent-card-name-row"});b.createDiv({cls:"prm-agent-card-name",text:u.rule.label});let y=b.createDiv({cls:`prm-agent-card-badge ${u.installed?"installed":"missing"}`,text:u.installed?a("settings.detectedAgents.installed"):a("agent.select.missing")});u.rule.vendor&&f.createDiv({cls:"prm-agent-card-vendor",text:u.rule.vendor}),u.installed||f.createDiv({cls:"prm-agent-card-hint",text:`${a("settings.agentInstall")}${u.rule.installHint}`})}new x.Setting(e).setName(a("settings.redetectAgent.name")).setDesc(a("settings.redetectAgent.desc")).addButton(u=>u.setButtonText(a("settings.redetectAgent.btn")).onClick(()=>{this.plugin.invalidateAgentCache(),this.display(),new x.Notice(a("settings.redetectAgent.done"))}));let r=new V;r.loadFromJSON(this.plugin.settings.customCommandRules);let o=r.getCustomRules(),l=e.createDiv({cls:"prm-settings-sub-header"});l.createDiv({cls:"prm-settings-sub-title",text:a("settings.customRules.title")});let c=l.createEl("button",{cls:"prm-settings-sub-btn",text:`+ ${a("common.add")}`});if(c.onclick=async()=>{let u=r.allRules().map(h=>h.id),g=await new et(this.app,u).openForResult();if(g)try{let h=new V;h.loadFromJSON(this.plugin.settings.customCommandRules),h.add(g),this.plugin.settings.customCommandRules=h.toJSON(),await this.plugin.saveSettings(),this.plugin.invalidateAgentCache(),this.display(),new x.Notice(a("settings.customRules.added",{label:g.label}))}catch(h){new x.Notice(a("settings.customRules.addFailed",{error:h.message}))}},o.length===0)e.createDiv({cls:"prm-settings-empty",text:a("settings.customRules.empty")});else{let u=e.createDiv({cls:"prm-rule-cards"});for(let g of o)this.renderCustomRuleCard(u,g)}let d=e.createEl("details",{cls:"prm-settings-var-details"});d.createEl("summary",{text:a("settings.varRef.title")});let p=d.createEl("table",{cls:"prm-settings-var-table"}),m=[["{{vaultPath}}",a("settings.varRef.vaultPath")],["{{instructionFile}}",a("settings.varRef.instructionFile")],["{{filePath}}",a("settings.varRef.filePath")],["{{fileName}}",a("settings.varRef.fileName")],["{{prompt}}",a("settings.varRef.prompt")]];for(let[u,g]of m){let h=p.createEl("tr");h.createEl("td",{text:u}),h.createEl("td",{text:g})}}renderCustomRuleCard(e,t){let n=e.createDiv({cls:"prm-rule-card"}),r=n.createDiv({cls:"prm-rule-card-info"});r.createDiv({cls:"prm-rule-card-label",text:t.label});let o=r.createDiv({cls:"prm-rule-card-meta"});o.createSpan({text:`${a("settings.ruleCard.detect")}: ${t.detectCmd}`});let l=t.template.length>60?t.template.slice(0,57)+"\u2026":t.template;o.createSpan({cls:"prm-rule-card-template"}).setText(`${a("settings.ruleCard.template")}: ${l}`);let d=n.createEl("button",{cls:"prm-rule-card-del",text:a("common.delete")});d.onclick=async()=>{let p=new V;p.loadFromJSON(this.plugin.settings.customCommandRules),p.remove(t.id),this.plugin.settings.customCommandRules=p.toJSON(),await this.plugin.saveSettings(),this.plugin.invalidateAgentCache(),this.display()}}renderAPISettings(e){let t=this.plugin.settings.apiSettings;new x.Setting(e).setName(a("settings.api.provider.name")).addDropdown(o=>o.addOption("anthropic","Anthropic (Claude)").addOption("openai","OpenAI (GPT)").addOption("deepseek","DeepSeek").addOption("gemini","Google Gemini").addOption("custom",a("settings.api.provider.custom")).setValue(t.provider).onChange(async l=>{t.provider=l,t.model=E[t.provider].model,await this.plugin.saveSettings(),this.display()})),new x.Setting(e).setName(a("settings.api.key.name")).setDesc(a("settings.api.key.desc")).addText(o=>{o.setPlaceholder(a("settings.api.key.placeholder")).setValue(t.apiKey).onChange(async d=>{t.apiKey=d.trim(),await this.plugin.saveSettings()}),o.inputEl.type="password",o.inputEl.addClass("prm-api-key-input");let l=o.inputEl.parentElement;l&&l.addClass("prm-relative");let c=l?.createEl("button",{cls:"prm-api-key-toggle"});c&&((0,x.setIcon)(c,"eye"),c.onclick=()=>{let d=o.inputEl;d.type==="password"?(d.type="text",(0,x.setIcon)(c,"eye-off")):(d.type="password",(0,x.setIcon)(c,"eye"))})}),new x.Setting(e).setName(a("settings.api.model.name")).setDesc(a("settings.api.model.desc",{model:E[t.provider].model})).addText(o=>o.setPlaceholder(E[t.provider].model).setValue(t.model).onChange(async l=>{t.model=l.trim(),await this.plugin.saveSettings()})),t.provider==="custom"&&new x.Setting(e).setName(a("settings.api.customEndpoint.name")).setDesc(a("settings.api.customEndpoint.desc")).addText(o=>o.setPlaceholder(a("settings.api.customEndpoint.placeholder")).setValue(t.customEndpoint).onChange(async l=>{t.customEndpoint=l.trim(),await this.plugin.saveSettings()})),new x.Setting(e).setName(a("settings.api.maxTokens.name")).setDesc(a("settings.api.maxTokens.desc")).addText(o=>o.setValue(String(t.maxTokens)).onChange(async l=>{let c=parseInt(l,10);!Number.isNaN(c)&&c>0&&(t.maxTokens=c,await this.plugin.saveSettings())}));let n=new x.Setting(e).setName(a("settings.api.test.name")).setDesc(a("settings.api.test.desc")),r=null;n.addButton(o=>{o.setButtonText(a("settings.api.test.btn")).onClick(async()=>{if(!t.apiKey){new x.Notice(a("settings.api.test.noKey"));return}o.setButtonText(a("settings.api.test.running")).setDisabled(!0);let{callAPI:l,API_SYSTEM_PROMPT:c}=await Promise.resolve().then(()=>(ce(),Mt)),d=await l({...t,model:t.model||E[t.provider].model},{systemPrompt:c,userMessage:'\u8BF7\u56DE\u590D"\u8FDE\u63A5\u6210\u529F"\uFF0C\u4EC5\u6B64\u56DB\u5B57\u3002'});o.setButtonText(a("settings.api.test.btn")).setDisabled(!1),d.success?(r="success",new x.Notice(a("settings.api.test.success",{model:t.model||E[t.provider].model}))):(r="fail",new x.Notice(a("settings.api.test.failed",{error:d.error??""}))),this.display()})})}};var k=require("obsidian");var L="promptuary-sidebar",Fe=class extends k.ItemView{constructor(e,t){super(e);this.plugin=t;this.mode="reading";this.currentFilePath=null;this.currentHash=null;this.baselineMismatch=!1;this.refreshSeq=0;this.modifyDebounceTimer=null;this.lastReviewCount=0}getViewType(){return L}getDisplayText(){return"Promptuary"}getIcon(){return"highlighter"}async onOpen(){this.contentEl.empty(),this.container=this.contentEl.createDiv({cls:"promptuary-sidebar"}),this.mode=this.plugin.settings.defaultMode,this.headerEl=this.container.createDiv({cls:"prm-sidebar-header"}),this.contentEl2=this.container.createDiv({cls:"prm-sidebar-content"}),this.actionBarEl=this.container.createDiv({cls:"prm-sidebar-action-bar"}),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.onActiveLeafChange())),this.registerEvent(this.app.workspace.on("file-open",e=>this.onFileOpen(e))),this.registerEvent(this.app.vault.on("modify",async e=>{e.path===this.currentFilePath&&(this.modifyDebounceTimer!==null&&window.clearTimeout(this.modifyDebounceTimer),this.modifyDebounceTimer=window.setTimeout(()=>{this.modifyDebounceTimer=null,(async()=>(this.currentHash=await this.plugin.store.fileHash(e.path),await this.refresh()))()},300))})),this.registerEvent(this.plugin.store.on("change",e=>{e===this.currentFilePath&&this.refresh()})),this.plugin.onSettingsChanged=()=>this.reRenderActionBar(),await this.onActiveLeafChange()}setMode(e){this.mode=e,this.plugin.onModeChange(e),this.refresh()}setModeExternal(e){this.mode!==e&&(this.mode=e,this.refresh())}getMode(){return this.mode}getCurrentFilePath(){return this.currentFilePath}async onActiveLeafChange(){let e=this.app.workspace.getActiveViewOfType(k.MarkdownView);if(e?.file){e.file.path!==this.currentFilePath&&(this.currentFilePath=e.file.path,this.currentHash=await this.plugin.store.fileHash(e.file.path),await this.refresh());return}if(this.currentFilePath!==null)return;let t=this.app.workspace.getLeavesOfType("markdown");for(let n of t){let r=n.view;if(r?.file){this.currentFilePath=r.file.path,this.currentHash=await this.plugin.store.fileHash(r.file.path);break}}await this.refresh()}async onFileOpen(e){e&&e.extension==="md"&&e.path!==this.currentFilePath&&(this.currentFilePath=e.path,this.currentHash=await this.plugin.store.fileHash(e.path),await this.refresh())}async refresh(){let e=++this.refreshSeq;if(!this.currentFilePath){if(e!==this.refreshSeq)return;this.headerEl.empty(),this.contentEl2.empty(),this.actionBarEl.empty(),this.renderHeader(this.headerEl),this.renderEmptyState(this.contentEl2,a("sidebar.empty.openFile"));return}let t=await this.plugin.store.getFile(this.currentFilePath);if(e!==this.refreshSeq)return;let n={fuzzy:0,drifted:0,autoHealed:0,reviewRemoved:0,readingRemoved:0};if(!!t.baselineHash&&!!this.currentHash&&t.baselineHash!==this.currentHash){let o=Ft(this);if(o!==null){let l=[];for(let d of t.annotations){let p=$(o,d);if(p.status==="fuzzy")if((p.candidates?.length??0)===0&&p.from!==void 0&&p.to!==void 0){let m=this.plugin.settings.contextSpan,u=Math.max(0,p.from-m),g=Math.min(o.length,p.to+m),h=o.slice(p.from,p.to);await this.plugin.store.updateAnnotation(this.currentFilePath,d.id,{selectedText:h,contextBefore:o.slice(u,p.from),contextAfter:o.slice(p.to,g),lineHint:Q(o,p.from),occurrenceIndex:X(o,h,p.from)}),n.autoHealed++}else n.fuzzy++;else p.status==="drifted"&&l.push(d)}if(l.length>0)for(let d of l){if(d.type==="review"){await this.plugin.store.removeAnnotation(this.currentFilePath,d.id),n.reviewRemoved++;continue}let p=be(o,d);if(p.status==="auto-healed"&&p.from!==void 0&&p.to!==void 0){let m=this.plugin.settings.contextSpan,u=Math.max(0,p.from-m),g=Math.min(o.length,p.to+m),h=o.slice(p.from,p.to),f=o.slice(u,p.from),b=o.slice(p.to,g),y=Q(o,p.from),S=X(o,h,p.from);await this.plugin.store.updateAnnotation(this.currentFilePath,d.id,{selectedText:h,contextBefore:f,contextAfter:b,lineHint:y,occurrenceIndex:S}),n.autoHealed++}else await this.plugin.store.removeAnnotation(this.currentFilePath,d.id),n.readingRemoved++}let c=n.fuzzy+n.drifted;if(c===0&&this.currentHash){if(await this.plugin.store.confirmBaseline(this.currentFilePath,this.currentHash,!0),e!==this.refreshSeq)return;this.baselineMismatch=!1;let d=[];n.autoHealed>0&&d.push(a("sidebar.notice.autoHealed",{n:n.autoHealed})),n.reviewRemoved>0&&d.push(a("sidebar.notice.reviewAutoRemoved",{n:n.reviewRemoved})),n.readingRemoved>0&&d.push(a("sidebar.notice.invalidReadingRemoved",{n:n.readingRemoved})),d.length>0&&new k.Notice(d.join("\uFF0C"))}else{this.baselineMismatch=!0;let d=[];n.autoHealed>0&&d.push(a("sidebar.notice.autoHealed",{n:n.autoHealed})),n.reviewRemoved>0&&d.push(a("sidebar.notice.reviewAutoRemoved",{n:n.reviewRemoved})),n.readingRemoved>0&&d.push(a("sidebar.notice.invalidReadingRemoved",{n:n.readingRemoved})),c>0&&d.push(a("sidebar.notice.ambiguousCheck",{n:c})),d.length>0&&new k.Notice(d.join("\uFF0C"))}}else this.baselineMismatch=!1}else this.baselineMismatch=!1;e===this.refreshSeq&&this.paint(t.annotations,n)}paint(e,t){this.headerEl.empty(),this.renderHeader(this.headerEl),this.contentEl2.empty(),this.baselineMismatch&&this.renderBannerIn(this.contentEl2,t),this.currentFilePath&&this.renderReviewCleanupPrompt(this.contentEl2,this.currentFilePath),this.renderListIn(this.contentEl2,e),this.actionBarEl.empty();let n=e.filter(r=>r.type==="review").length;this.lastReviewCount=n,this.mode!=="reading"&&this.renderActionBar(this.actionBarEl,n)}renderEmptyState(e,t){let n=e.createDiv({cls:"prm-empty-state"});if(this.plugin.emptyStateUrl){let r=n.createEl("img",{cls:"prm-empty-state-img"});r.src=this.plugin.emptyStateUrl,r.alt=""}n.createDiv({cls:"prm-empty-state-text",text:t})}renderHeader(e){let t=e.createDiv({cls:"prm-header-row"}),n=t.createDiv({cls:"prm-header-left"}),r=n.createDiv({cls:"prm-header-icon"});if(this.plugin.logoUrl){let d=r.createEl("img",{cls:"prm-logo-img"});d.src=this.plugin.logoUrl,d.alt="Promptuary"}else(0,k.setIcon)(r,"prm-highlighter");n.createSpan({cls:"prm-header-title",text:"Promptuary"});let o=t.createEl("button",{cls:"prm-header-settings"});(0,k.setIcon)(o,"settings"),o.onclick=()=>{let d=this.app;d.setting?.open(),d.setting?.openTabById?.("promptuary")};let l=e.createDiv({cls:"prm-mode-capsule"}),c=[["reading",a("sidebar.mode.reading")],["reviewing",a("sidebar.mode.review")],["all",a("sidebar.mode.all")]];for(let[d,p]of c){let m=l.createEl("button",{text:p});this.mode===d&&m.addClass("active"),m.onclick=()=>this.setMode(d)}}renderActionBar(e,t){let n=t>0,r=this.plugin.executionState,o=r!==null;if(!R()){let h=e.createEl("button",{cls:"prm-action-execute"});(0,k.setIcon)(h,"sparkles"),h.title=a("sidebar.action.agentTitle");let f=o&&r.type==="agent";f?h.createSpan({text:a("sidebar.status.agentRunning")}):h.createSpan({text:a("sidebar.action.agentReview")}),h.disabled=!n||o,f&&h.addClass("prm-executing"),h.onclick=async()=>{if(!(!n||o)){if(!n){new k.Notice(a("main.notice.noReviewAnnotations"));return}this.plugin.executionState={type:"agent"},this.reRenderActionBar();try{await this.plugin.runAgentWithSelect()}finally{this.plugin.executionState=null,this.refresh()}}}}let l=e.createDiv({cls:"prm-action-row"}),c=!!this.plugin.settings.apiSettings?.apiKey,d=o&&r.type==="api",p=l.createEl("button",{cls:"prm-action-btn"});(0,k.setIcon)(p,"zap"),d?(p.createSpan({cls:"prm-action-short",text:"API"}),p.createSpan({cls:"prm-action-long",text:` ${a("sidebar.mode.review")}\u2026`})):(p.createSpan({cls:"prm-action-short",text:"API"}),p.createSpan({cls:"prm-action-long",text:` ${a("sidebar.mode.review")}`})),p.title=c?a("sidebar.action.apiTitle"):a("sidebar.action.noApiKey"),p.disabled=!c||o,d&&p.addClass("prm-executing"),p.onclick=async()=>{if(!(!c||o)){this.plugin.executionState={type:"api"},this.reRenderActionBar();try{await this.plugin.runAPIExecute()}finally{this.plugin.executionState=null,this.refresh()}}};let m=l.createEl("button",{cls:"prm-action-btn"});(0,k.setIcon)(m,"clipboard-copy"),m.createSpan({cls:"prm-action-short",text:"Prompt"}),m.createSpan({cls:"prm-action-long",text:` ${a("sidebar.action.copy")}`}),m.title=a("sidebar.action.copyTitle"),m.disabled=!n||o,m.onclick=()=>{this.currentFilePath?this.plugin.runCopyPrompt(this.currentFilePath):this.plugin.runCopyPrompt()};let u=l.createEl("button",{cls:"prm-action-btn prm-more-btn"});(0,k.setIcon)(u,"more-horizontal"),u.title=a("sidebar.action.exportTitle"),u.disabled=!n||o,u.onclick=()=>{if(!n||o)return;let h=new k.Menu;h.addItem(b=>{b.setTitle(a("sidebar.action.exportFile")).setIcon("file-text").onClick(async()=>{this.currentFilePath?await this.plugin.runExport(this.currentFilePath):await this.plugin.runExport()})});let f=u.getBoundingClientRect();h.showAtPosition({x:f.left,y:f.top-4})};let g=e.createDiv({cls:"prm-action-status"});o?(g.createSpan({cls:"prm-status-dot prm-status-dot-executing"}),g.createSpan({text:r.type==="agent"?a("sidebar.status.agentRunning"):a("sidebar.status.apiRunning")})):(g.createSpan({cls:"prm-status-dot"}),g.createSpan({text:a("sidebar.status.pendingReview",{n:t})}))}reRenderActionBar(){this.actionBarEl.empty(),this.mode!=="reading"&&this.renderActionBar(this.actionBarEl,this.lastReviewCount)}renderBannerIn(e,t){let n=e.createDiv({cls:"prm-banner"}),r=[];t.drifted>0&&r.push(a("sidebar.banner.drifted",{n:t.drifted})),t.fuzzy>0&&r.push(a("sidebar.banner.ambiguous",{n:t.fuzzy}));let o=r.length>0?`${a("sidebar.banner.changed")} ${r.join("\u3001")}\uFF0C${a("sidebar.banner.changedFull")}`:a("sidebar.banner.changedFull");n.createSpan({text:o});let l=n.createEl("button",{text:a("sidebar.banner.confirmAll")});l.onclick=async()=>{!this.currentFilePath||!this.currentHash||(await this.plugin.store.confirmBaseline(this.currentFilePath,this.currentHash),this.refresh(),new k.Notice(a("sidebar.banner.baselineUpdated")))}}renderReviewCleanupPrompt(e,t){let n=this.plugin.getPendingReviewCleanup(t);if(!n||n.count===0)return;let r=e.createDiv({cls:"prm-cleanup-prompt"}),o=r.createDiv({cls:"prm-cleanup-text"});o.createDiv({cls:"prm-cleanup-title",text:a("sidebar.cleanup.title")}),o.createDiv({cls:"prm-cleanup-desc",text:a("sidebar.cleanup.desc",{n:n.count})});let l=r.createDiv({cls:"prm-cleanup-actions"}),c=l.createEl("button",{cls:"prm-cleanup-keep",text:a("sidebar.cleanup.keep")});c.onclick=()=>this.plugin.dismissReviewCleanup(t);let d=l.createEl("button",{cls:"prm-cleanup-confirm",text:a("sidebar.cleanup.clean")});d.onclick=async()=>{await this.plugin.cleanupProcessedReviews(t)}}renderListIn(e,t){let n=t.filter(l=>this.mode==="reading"?l.type==="highlight"||l.type==="note":this.mode==="reviewing"?l.type==="review":!0);if(n.length===0){this.renderEmptyState(e,Dn(this.mode));return}let r=Ft(this),o=[...n].sort((l,c)=>{if(r){let d=$(r,l),p=$(r,c),m=d.from??Number.MAX_SAFE_INTEGER,u=p.from??Number.MAX_SAFE_INTEGER;if(m!==u)return m-u}return l.createdAt-c.createdAt});for(let l of o)this.renderCard(e,l,r)}renderCard(e,t,n){let r=n?$(n,t):null,o=e.createDiv({cls:"prm-card"}),l=Tn(t);l&&o.addClass(l),r&&(r.status==="fuzzy"&&o.addClass("fuzzy"),r.status==="auto-healed"&&o.addClass("auto-healed"),r.status==="drifted"&&o.addClass("drifted"));let c=o.createDiv({cls:"prm-card-meta"}),d=Rn(t);if(c.createSpan({cls:`prm-tag ${d}`,text:In(t)}),r?.status==="fuzzy"){let u=c.createSpan({cls:"prm-card-status-inline"});(0,k.setIcon)(u,"alert-triangle"),u.createSpan({text:` ${a("sidebar.card.ambiguous")}`})}if(r?.status==="auto-healed"){let u=c.createSpan({cls:"prm-card-status-inline"});(0,k.setIcon)(u,"wrench"),u.createSpan({text:` ${a("sidebar.card.autoHealed")}`})}if(r?.status==="drifted"){let u=c.createSpan({cls:"prm-card-status-inline"});(0,k.setIcon)(u,"alert-triangle"),u.createSpan({text:` ${a("sidebar.card.drifted")}`})}let p=c.createDiv({cls:"prm-card-meta-spacer"}),m=c.createEl("button",{cls:"prm-card-del-btn",text:a("sidebar.card.delete")});if(m.onclick=u=>{u.stopPropagation(),this.plugin.deleteAnnotation(t)},t.type==="review"){o.createDiv({cls:"prm-card-quote prm-quote-orange"+(t.strike?" strike":"")}).setText(t.selectedText),t.reviewText&&o.createDiv({cls:"prm-card-text prm-text-purple"}).setText(t.reviewText);let g=(this.currentFilePath??"").split("/").pop()??"",h=o.createDiv({cls:"prm-card-source"});h.createSpan({text:g}),h.createSpan({text:` \xB7 L.${t.lineHint}`})}else{o.createDiv({cls:"prm-card-quote"+(t.strike?" strike":"")}).setText(t.selectedText),t.type==="note"&&t.noteText&&o.createDiv({cls:"prm-card-text",text:t.noteText});let g=(this.currentFilePath??"").split("/").pop()??"",h=o.createDiv({cls:"prm-card-source"});h.createSpan({text:g}),h.createSpan({text:` \xB7 L.${t.lineHint}`})}o.onclick=()=>this.jumpTo(t)}async jumpTo(e){if(!this.currentFilePath)return;let t=this.app.vault.getAbstractFileByPath(this.currentFilePath);if(!(t instanceof k.TFile))return;await this.app.workspace.getLeaf(!1).openFile(t);let r=this.app.workspace.getActiveViewOfType(k.MarkdownView);if(!r)return;let o=r.editor.getValue(),l=$(o,e);if(l.status==="drifted"||l.from===void 0||l.to===void 0){new k.Notice(a("sidebar.notice.cannotLocate"));return}let c=r.editor.offsetToPos(l.from),d=r.editor.offsetToPos(l.to);r.editor.setSelection(c,d),r.editor.scrollIntoView({from:c,to:d},!0);let p=r.editor.cm;p&&this.plugin.popover&&window.requestAnimationFrame(()=>{this.plugin.popover.showForAnnotation(p,l.from,l.to,e)})}};function Dn(s){return s==="reading"?a("sidebar.empty.reading"):s==="reviewing"?a("sidebar.empty.review"):a("sidebar.empty.all")}function Tn(s){return s.type==="highlight"?`color-${s.highlightColor??"yellow"}`:s.type==="note"?`color-${s.highlightColor??"yellow"}`:s.type==="review"?"color-orange":null}function Rn(s){return s.type==="highlight"||s.type==="note"?s.highlightColor??"yellow":"orange"}function In(s){return s.type==="highlight"?a("sidebar.tag.highlight"):s.type==="note"?a("sidebar.tag.note"):s.type==="review"?s.strike?a("sidebar.tag.delete"):a("sidebar.tag.review"):""}function Ft(s){let i=s.getCurrentFilePath();if(!i)return null;let e=s.app.workspace.getLeavesOfType("markdown");for(let t of e){let n=t.view;if(n?.file?.path===i)return n.editor.getValue()}return null}var z=require("obsidian");function He(s){return Math.ceil(s.length/4)}var Mn=1e5;function tt(s,i,e,t){let n=e.annotations.filter(c=>c.type==="review"),r=e.annotations.filter(c=>c.type==="note"),o=new Date().toISOString().slice(0,10),l=`# ${a("export.reviewTitle")} \u2014 ${s} +`),r=[],o=[],l=0;for(let u of t)r.push(l),l+=u.length+1;l=0;for(let u of n)o.push(l),l+=u.length+1;let c=wn(t,n),d=0,p=0,m=0;for(;d=c.length||t[d]!==c[m]);)h=r[d]+t[d].length,d=c.length||n[p]!==c[m]);)g=o[p]+n[p].length,pd.aIdx-p.aIdx);let l=xn(o.map(d=>d.bIdx)),c=[];for(let d of l)c.push(o[d].line);return c}function bn(s,i){let e=s.length,t=i.length,n=new Uint16Array(t+1),r=new Uint16Array(t+1);for(let p=1;p<=e;p++){for(let m=1;m<=t;m++)s[p-1]===i[m-1]?r[m]=n[m-1]+1:r[m]=Math.max(n[m],r[m-1]);[n,r]=[r,n],r.fill(0)}let o=[],l=e,c=t,d=[];for(let p=0;p<=e;p++)d[p]=new Array(t+1).fill(0);for(let p=1;p<=e;p++)for(let m=1;m<=t;m++)s[p-1]===i[m-1]?d[p][m]=d[p-1][m-1]+1:d[p][m]=Math.max(d[p-1][m],d[p][m-1]);for(;l>0&&c>0;)s[l-1]===i[c-1]?(o.unshift(s[l-1]),l--,c--):d[l-1][c]>d[l][c-1]?l--:c--;return o}function xn(s){if(s.length===0)return[];let i=[],e=new Array(s.length).fill(-1),t=[];for(let o=0;o>1;s[i[p]]0&&(e[o]=i[c-1]),c===i.length?i.push(o):i[c]=o}let n=[],r=i[i.length-1];for(;r>=0;)n.unshift(r),r=e[r];return n}function yn(s,i,e){let t=[{oldPos:0,newPos:0}];for(let r of s){let o=t[t.length-1];if(r.oldStart>o.oldPos){let l=r.oldStart-o.oldPos;t.push({oldPos:r.oldStart,newPos:o.newPos+l})}t.push({oldPos:r.oldEnd,newPos:r.newEnd})}let n=t[t.length-1];if(n.oldPos>1;s[l].oldPos<=i?e=l:t=l-1}let n=s[e];if(n.oldPos===i)return n.newPos;let r=e+1;if(re)break;if(r===e)return t;t++,n=r+Math.max(1,i.length)}return t}function Tt(s,i,e,t=50){if(e.length===0)return[];if(s===i)return e.map(l=>({id:l.id,status:"healed",patch:{}}));let n=vn(s,i),r=yn(n,s.length,i.length),o=[];for(let l of e){if(!l.selectedText){o.push({id:l.id,status:"drifted",patch:{}});continue}let c=s.indexOf(l.selectedText,l.lineHint>0?Math.max(0,s.indexOf(` +`,0)):0),d=-1,p=-1;if(l.contextBefore&&l.contextAfter){let S=l.contextBefore+l.selectedText+l.contextAfter,T=s.indexOf(S);T>=0&&(d=T+l.contextBefore.length,p=d+l.selectedText.length)}if(d<0){let S=s.indexOf(l.selectedText);S>=0&&(d=S,p=S+l.selectedText.length)}if(d<0){o.push({id:l.id,status:"drifted",patch:{}});continue}let m=St(r,d),u=St(r,p);if(u<=m||u>i.length){o.push({id:l.id,status:"drifted",patch:{}});continue}let f=i.slice(m,u),h=Sn(l.selectedText,f);if(h<.3){o.push({id:l.id,status:"drifted",similarity:h,patch:{}});continue}let g=Math.max(0,m-t),b=Math.min(i.length,u+t),A=i.slice(g,m),y=i.slice(u,b),C=An(i,m),v=Cn(i,f,m);o.push({id:l.id,status:"healed",similarity:h,patch:{selectedText:f,contextBefore:A,contextAfter:y,lineHint:C,occurrenceIndex:v}})}return o}function Sn(s,i){if(s===i)return 1;if(!s||!i)return 0;if(s.includes(i)||i.includes(s))return Math.min(s.length,i.length)/Math.max(s.length,i.length);let e=kt(s),t=kt(i),n=0,r=0,o=new Set([...e.keys(),...t.keys()]);for(let l of o){let c=e.get(l)??0,d=t.get(l)??0;n+=Math.min(c,d),r+=Math.max(c,d)}return r>0?n/r:0}function kt(s){let i=new Map;for(let e of s)i.set(e,(i.get(e)??0)+1);return i}var _=require("@codemirror/view"),G=require("@codemirror/state");var le=G.StateEffect.define(),Se=G.StateField.define({create:()=>[],update(s,i){for(let e of i.effects)if(e.is(le))return e.value;return s}}),kn=G.StateField.define({create(s){return Xe(s.doc.toString(),s.field(Se))},update(s,i){let e=null;for(let t of i.effects)t.is(le)&&(e=t.value);return e?Xe(i.state.doc.toString(),e):i.docChanged?Xe(i.state.doc.toString(),i.state.field(Se)):s},provide:s=>_.EditorView.decorations.from(s)});function Xe(s,i){let e=[];for(let r of i){let o=V(s,r);if(o.status==="drifted"||o.from===void 0||o.to===void 0)continue;let l=Et(r,o.status);l&&e.push({from:o.from,to:o.to,deco:_.Decoration.mark({class:l,attributes:{"data-prm-id":r.id}})})}let t=Tn(e),n=new G.RangeSetBuilder;for(let r of t)n.add(r.from,r.to,r.deco);return n.finish()}function Tn(s){if(s.length===0)return s;s.sort((n,r)=>n.from-r.from||n.to-r.to);let i=[],e=new Set;for(let n of s)e.add(n.from),e.add(n.to);let t=Array.from(e).sort((n,r)=>n-r);for(let n=0;nm.from<=r&&m.to>=o);if(l.length===0)continue;let c=new Set,d=[];for(let m of l){let u=m.deco.spec;u.class&&u.class.split(/\s+/).forEach(f=>c.add(f)),u.attributes?.["data-prm-id"]&&d.push(u.attributes["data-prm-id"])}let p=_.Decoration.mark({class:Array.from(c).join(" "),attributes:d.length>0?{"data-prm-id":d.join(",")}:void 0});i.push({from:r,to:o,deco:p})}return i}function Et(s,i){let e=i==="fuzzy"?" cm-promptuary-fuzzy":"",t=i==="auto-healed"?" cm-promptuary-auto-healed":"";if(s.type==="highlight")return`cm-promptuary-highlight cm-promptuary-highlight-${s.highlightColor??"yellow"}${e}${t}`;if(s.type==="note")return`cm-promptuary-highlight cm-promptuary-highlight-${s.highlightColor??"yellow"}${e}${t}`;if(s.type==="review"){let n="cm-promptuary-review";return s.strike&&(n+=" cm-promptuary-strike"),n+e+t}return null}var ke="prm-table-hl",Qe=class{constructor(i){this.rafId=null;this.observer=null;this.view=i,this.startObserving()}startObserving(){this.observer=new MutationObserver(i=>{i.some(t=>{let n=t.target;if(typeof n.closest=="function"&&n.closest(".cm-table-widget"))return!0;for(let r of Array.from(t.addedNodes).concat(Array.from(t.removedNodes))){let o=r;if(typeof o.closest=="function"&&(o.classList?.contains("cm-editor")||o.querySelector?.(".cm-editor")))return!0}return!1})&&this.scheduleApply()}),this.observer.observe(this.view.dom,{childList:!0,subtree:!0})}scheduleApply(){this.rafId!==null&&window.cancelAnimationFrame(this.rafId),this.rafId=window.requestAnimationFrame(()=>{this.rafId=null,this.applyTableHighlights(this.view)})}update(i){let e=i.transactions.some(t=>t.effects.some(n=>n.is(le)));!i.docChanged&&!i.viewportChanged&&!e||this.scheduleApply()}destroy(){this.rafId!==null&&(window.cancelAnimationFrame(this.rafId),this.rafId=null),this.observer?.disconnect(),this.observer=null}applyTableHighlights(i){Array.from(i.dom.querySelectorAll(`.${ke}`)).forEach(o=>{let l=o.parentNode;if(l){for(;o.firstChild;)l.insertBefore(o.firstChild,o);l.removeChild(o),l.normalize()}});let e=i.state.field(Se);if(e.length===0)return;let t=i.state.doc.toString(),n=[];for(let o of e){if(!o.selectedText)continue;let l=V(t,o);if(l.status==="drifted"||l.from===void 0)continue;let c=Et(o,l.status);c&&n.push({selectedText:o.selectedText,cls:c})}if(n.length===0)return;for(let o of Array.from(i.dom.querySelectorAll(".cm-line"))){if(o.querySelector("[class*='cm-promptuary']"))continue;let l;try{let d=i.posAtDOM(o,0);l=i.state.doc.lineAt(d).text}catch{continue}let c=l.trim();if(!(!c.startsWith("|")&&!c.endsWith("|")))for(let{selectedText:d,cls:p}of n)l.includes(d)&&Pt(o,d,p)}let r=i.dom.querySelectorAll(".cm-table-widget");for(let o of Array.from(r)){let l=o.querySelectorAll("td, th");for(let c of Array.from(l)){if(c.querySelector(".cm-editor")||c.querySelector(`.${ke}`))continue;let d=c.textContent??"";for(let{selectedText:p,cls:m}of n)d.includes(p)&&Pt(c,p,m)}}}};function Pt(s,i,e){let t=activeDocument.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode(r){return r.parentElement?.closest(`.${ke}`)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),n;for(;n=t.nextNode();){let r=n,o=r.textContent??"",l=o.indexOf(i);if(l===-1)continue;let c=o.slice(0,l),d=o.slice(l+i.length),p=r.parentNode,m=activeDocument.createElement("span");m.className=`${e} ${ke}`,m.textContent=i,c&&p.insertBefore(activeDocument.createTextNode(c),r),p.insertBefore(m,r),d&&p.insertBefore(activeDocument.createTextNode(d),r),p.removeChild(r);return}}function Dt(){return[Se,kn,_.ViewPlugin.fromClass(Qe)]}function Te(s){let i=!1,e=null;return s.addEventListener("compositionstart",()=>{e!==null&&(window.clearTimeout(e),e=null),i=!0}),s.addEventListener("compositionend",()=>{e!==null&&window.clearTimeout(e),e=window.setTimeout(()=>{i=!1,e=null},0)}),t=>i||t.isComposing||t.keyCode===229}var Pe=class{constructor(i,e){this.app=i;this.cb=e;this.mode="reading";this.current=null;this.renderedMode=null;this.noteExpanded=!1;this.selectedColor="yellow";this.strikePending=!1;this.pendingStrikeId=null;this.editingAnnotationId=null;this.isEditing=!1;this.el=activeDocument.createElement("div"),this.el.className="promptuary-popover",this.el.addClass("prm-hidden"),activeDocument.body.appendChild(this.el)}destroy(){this.el.remove(),this.current=null,this.renderedMode=null}setMode(i){if(i===this.mode)return;let e=this.noteExpanded?this.el.querySelector(".prm-popover-note-input")?.value??"":"";this.mode=i,this.renderedMode=null,this.noteExpanded=!1,this.cleanupPendingStrike(),this.current&&(this.render(),e&&this.expandNoteAreaWithText(e,this.selectedColor))}show(i,e,t){if(e===t)return this.hide(),!1;let n=this.current?this.current.from!==e||this.current.to!==t:!0;return this.current={view:i,from:e,to:t},(this.renderedMode!==this.mode||n)&&this.render(),this.position(i,e,t),!0}showForAnnotation(i,e,t,n){this.isEditing=!0,this.editingAnnotationId=n.id;let r=n.type==="review"?"reviewing":"reading";this.mode!==r&&(this.mode=r,this.cb.onModeSwitch(r)),this.renderedMode=null,this.noteExpanded=!1,this.current={view:i,from:e,to:t},this.render(),this.position(i,e,t),(n.noteText||n.reviewText)&&this.expandNoteAreaWithText(n.noteText||n.reviewText||"",n.highlightColor||"yellow")}hide(){this.el.addClass("prm-hidden"),this.current=null,this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.editingAnnotationId=null,this.isEditing=!1,this.renderedMode=null}cleanupPendingStrike(){this.strikePending=!1,this.pendingStrikeId=null}position(i,e,t){let n=window.getSelection();if(n&&n.rangeCount>0&&!n.isCollapsed)try{let h=n.getRangeAt(0).getBoundingClientRect();if(h.width>0&&h.height>0){let g=h.bottom+6,b=this.el.offsetWidth||200,A=Math.max(8,Math.min(h.left,window.innerWidth-b-8));this.el.style.setProperty("--prm-pos-top",`${g}px`),this.el.style.setProperty("--prm-pos-left",`${A}px`),this.el.addClass("prm-dynamic-position"),this.el.removeClass("prm-hidden");return}}catch{}let r=i.coordsAtPos(t),o=i.coordsAtPos(e);if(!r&&!o)return;let l=r??o,c=l.bottom+6,d=o?o.left:l.left,p=this.el.offsetWidth||200,m=window.innerWidth-p-8,u=Math.max(8,Math.min(d,m));this.el.style.setProperty("--prm-pos-top",`${c}px`),this.el.style.setProperty("--prm-pos-left",`${u}px`),this.el.addClass("prm-dynamic-position"),this.el.removeClass("prm-hidden")}render(){this.el.empty(),this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.renderTitleRow(),this.mode==="reviewing"?this.renderReviewingActions():this.renderReadingActions(),this.renderedMode=this.mode}renderTitleRow(){let i=this.el.createDiv({cls:"prm-popover-title-row"}),e=i.createSpan({cls:"prm-popover-title",text:this.editingAnnotationId?a("popover.title.edit"):a("popover.title.add")});this.buildModeCapsule(i)}buildModeCapsule(i){let e=i.createDiv({cls:"prm-popover-capsule"}),t=[["reading",a("popover.mode.reading")],["reviewing",a("popover.mode.review")]];for(let[n,r]of t){let o=e.createEl("button",{text:r});this.mode===n&&o.addClass("active"),o.onmousedown=l=>{l.preventDefault(),n!==this.mode&&this.cb.onModeSwitch(n)}}}renderReadingActions(){let i=this.el.createDiv({cls:"prm-popover-actions"}),e=["yellow","blue","green","purple"];for(let n of e){let r=i.createDiv({cls:`prm-color ${n}`});n===this.selectedColor&&r.addClass("active"),r.title=a("popover.color.highlight",{color:a(`color.${n}`)}),r.onmousedown=o=>{o.preventDefault(),i.querySelectorAll(".prm-color").forEach(l=>l.removeClass("active")),r.addClass("active"),this.selectedColor=n,this.noteExpanded?this.cb.onHighlight(n,this.editingAnnotationId??void 0):(this.cb.onHighlight(n,this.editingAnnotationId??void 0),this.hide())}}i.createDiv({cls:"prm-divider"});let t=i.createEl("button",{cls:"prm-note-btn",text:a("popover.btn.addNote")});t.title=a("popover.btn.addNoteTitle"),t.onmousedown=n=>{n.preventDefault(),this.toggleNoteArea()}}renderReviewingActions(){let i=this.el.createDiv({cls:"prm-popover-actions"}),e=i.createEl("button",{cls:"prm-delete-btn",text:a("popover.btn.delete")});e.title=a("popover.btn.deleteTitle"),e.onmousedown=r=>{r.preventDefault(),this.strikePending=!this.strikePending,e.toggleClass("active",this.strikePending),this.editingAnnotationId?this.cb.onReview("",this.strikePending,this.editingAnnotationId):this.strikePending?this.pendingStrikeId||this.cb.onStrikeCreate().then(o=>{this.pendingStrikeId=o}):this.pendingStrikeId&&(this.cb.onStrikeRemove(this.pendingStrikeId),this.pendingStrikeId=null),this.updateStrikeIndicator(),this.updateReviewConfirmState()};let t=i.createEl("button",{cls:"prm-note-btn",text:a("popover.btn.reviewNote")});t.title=a("popover.btn.reviewNoteTitle"),t.onmousedown=r=>{r.preventDefault(),this.toggleNoteArea()};let n=i.createEl("button",{cls:"prm-review-confirm-btn",text:"\u2713"});n.title=a("popover.btn.confirmDelete"),n.addClass("prm-hidden"),n.onmousedown=r=>{r.preventDefault(),this.editingAnnotationId?this.hide():(this.pendingStrikeId=null,this.hide())}}updateReviewConfirmState(){let i=this.el.querySelector(".prm-review-confirm-btn");i&&i.toggleClass("prm-hidden",!(this.strikePending&&!this.noteExpanded))}updateStrikeIndicator(){}updateNoteColorIndicator(){}expandNoteAreaWithText(i,e){this.selectedColor=e,this.toggleNoteArea();let t=this.el.querySelector(".prm-popover-note-input");t&&(t.value=i,window.requestAnimationFrame(()=>{t.focus(),t.select()}))}toggleNoteArea(){if(this.noteExpanded){let l=this.el.querySelector(".prm-popover-note-area");l&&l.remove(),this.noteExpanded=!1,this.updateReviewConfirmState(),this.current&&this.position(this.current.view,this.current.from,this.current.to);return}this.noteExpanded=!0,this.updateReviewConfirmState();let i=this.el.createDiv({cls:"prm-popover-note-area"}),t=i.createDiv({cls:"prm-popover-note-input-wrap"}).createEl("input",{type:"text",cls:"prm-popover-note-input"});t.placeholder=this.mode==="reviewing"?a("popover.placeholder.review"):a("popover.placeholder.note");let n=Te(t),o=i.createDiv({cls:"prm-popover-note-footer"}).createEl("button",{cls:"prm-popover-note-save",text:a("popover.btn.save")});t.onkeydown=l=>{if(l.key==="Enter"){if(n(l))return;l.preventDefault();let c=t.value.trim();c&&this.saveNote(c)}else if(l.key==="Escape"){if(n(l))return;this.hide()}},o.onmousedown=l=>{l.preventDefault();let c=t.value.trim();c&&this.saveNote(c)},this.current&&this.position(this.current.view,this.current.from,this.current.to),window.requestAnimationFrame(()=>t.focus())}saveNote(i){let e=this.editingAnnotationId??void 0;this.mode==="reviewing"?this.pendingStrikeId?(this.cb.onReview(i,!0,this.pendingStrikeId),this.pendingStrikeId=null):this.cb.onReview(i,this.strikePending,e):this.cb.onNote(i,this.selectedColor,e),this.hide()}};var Ee=class{constructor(i,e){this.app=i;this.cb=e;this.mode="reading";this.active=!1;this.noteExpanded=!1;this.selectedColor="yellow";this.strikePending=!1;this.pendingStrikeId=null;this.el=activeDocument.createElement("div"),this.el.className="promptuary-bottom-toolbar",this.el.addClass("prm-hidden"),activeDocument.body.appendChild(this.el)}destroy(){this.el.remove(),this.active=!1}setMode(i){this.mode=i,this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.active&&this.render()}show(){this.active=!0,this.render(),this.el.removeClass("prm-hidden")}hide(){this.active=!1,this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.el.addClass("prm-hidden")}render(){this.el.empty(),this.noteExpanded=!1,this.strikePending=!1,this.pendingStrikeId=null,this.renderModeCapsule(),this.mode==="reviewing"?this.renderReviewingActions():this.renderReadingActions()}renderModeCapsule(){let i=this.el.createDiv({cls:"prm-popover-capsule"}),e=[["reading",a("toolbar.mode.reading")],["reviewing",a("toolbar.mode.review")]];for(let[t,n]of e){let r=i.createEl("button",{text:n});this.mode===t&&r.addClass("active"),r.onclick=()=>{t!==this.mode&&this.cb.onModeSwitch(t)}}}renderReadingActions(){let i=this.el.createDiv({cls:"prm-popover-actions"}),e=["yellow","blue","green","purple"];for(let r of e){let o=i.createDiv({cls:`prm-color ${r}`});o.title=a("toolbar.color.highlight",{color:a(`color.${r}`)}),o.onclick=()=>{this.selectedColor=r,this.noteExpanded?this.updateNoteColorIndicator():(this.cb.onHighlight(r),this.hide())}}let t=i.createEl("button",{text:a("toolbar.btn.addNote")});t.onclick=()=>{this.toggleNoteArea()};let n=i.createEl("button",{text:"\xD7"});n.onclick=()=>this.hide()}renderReviewingActions(){let i=this.el.createDiv({cls:"prm-popover-actions"}),e=i.createEl("button",{cls:"prm-delete-btn",text:a("toolbar.btn.delete")});e.title=a("toolbar.btn.deleteTitle"),e.onclick=()=>{this.strikePending=!this.strikePending,e.toggleClass("active",this.strikePending),this.strikePending?this.pendingStrikeId||this.cb.onStrikeCreate().then(o=>{this.pendingStrikeId=o}):this.pendingStrikeId&&(this.cb.onStrikeRemove(this.pendingStrikeId),this.pendingStrikeId=null),this.updateStrikeIndicator(),this.updateReviewConfirmState()};let t=i.createEl("button",{cls:"prm-note-btn",text:a("toolbar.btn.reviewNote")});t.title=a("toolbar.btn.reviewNoteTitle"),t.onclick=()=>{this.toggleNoteArea()};let n=i.createEl("button",{cls:"prm-review-confirm-btn",text:"\u2713"});n.title=a("toolbar.btn.confirmDelete"),n.addClass("prm-hidden"),n.onclick=()=>{this.pendingStrikeId=null,this.hide()};let r=i.createEl("button",{text:"\xD7"});r.onclick=()=>this.hide()}updateReviewConfirmState(){let i=this.el.querySelector(".prm-review-confirm-btn");i&&i.toggleClass("prm-hidden",!(this.strikePending&&!this.noteExpanded))}updateStrikeIndicator(){let i=this.el.querySelector(".prm-popover-note-header");if(!i)return;let e=i.querySelector(".prm-strike-indicator");this.strikePending?e||(e=i.createSpan({cls:"prm-strike-indicator",text:a("toolbar.label.delete")})):e&&e.remove()}updateNoteColorIndicator(){let i=this.el.querySelector(".prm-popover-note-header .prm-note-dot"),e=this.el.querySelector(".prm-popover-note-header .prm-note-label");if(!i||!e)return;let t=["yellow","blue","green","purple","orange"];for(let n of t)i.removeClass(n),e.removeClass(n);i.addClass(this.selectedColor),e.addClass(this.selectedColor)}toggleNoteArea(){if(this.noteExpanded){let c=this.el.querySelector(".prm-popover-note-area");c&&c.remove(),this.noteExpanded=!1,this.updateReviewConfirmState();return}this.noteExpanded=!0,this.updateReviewConfirmState();let i=this.el.createDiv({cls:"prm-popover-note-area"}),e=i.createDiv({cls:"prm-popover-note-header"});this.mode==="reviewing"?(e.createDiv({cls:"prm-note-dot orange"}),e.createDiv({cls:"prm-divider"}),e.createSpan({cls:"prm-note-label orange",text:a("toolbar.label.review")}),this.strikePending&&e.createSpan({cls:"prm-strike-indicator",text:a("toolbar.label.delete")})):(e.createDiv({cls:`prm-note-dot ${this.selectedColor}`}),e.createDiv({cls:"prm-divider"}),e.createSpan({cls:`prm-note-label ${this.selectedColor}`,text:a("toolbar.label.note")}));let n=i.createDiv({cls:"prm-popover-note-input-wrap"}).createEl("input",{type:"text",cls:"prm-popover-note-input"});n.placeholder=this.mode==="reviewing"?a("toolbar.placeholder.review"):a("toolbar.placeholder.note");let r=Te(n),l=i.createDiv({cls:"prm-popover-note-footer"}).createEl("button",{cls:"prm-popover-note-save",text:a("toolbar.btn.save")});n.onkeydown=c=>{if(c.key==="Enter"){if(r(c))return;c.preventDefault();let d=n.value.trim();d&&this.saveNote(d)}else if(c.key==="Escape"){if(r(c))return;this.hide()}},l.onclick=()=>{let c=n.value.trim();c&&this.saveNote(c)},window.requestAnimationFrame(()=>n.focus())}saveNote(i){this.mode==="reviewing"?this.pendingStrikeId?(this.cb.onReview(i,!0,this.pendingStrikeId),this.pendingStrikeId=null):this.cb.onReview(i,this.strikePending):this.cb.onNote(i,this.selectedColor),this.hide()}};var L=require("obsidian");var ce=class extends L.Modal{constructor(i,e="",t){super(i),this.value=e,this.onSubmit=t}onOpen(){let{contentEl:i}=this;i.createEl("h3",{text:a("notemodal.note.title")}),new L.Setting(i).setName(a("notemodal.note.content")).addTextArea(e=>{e.setValue(this.value).onChange(t=>{this.value=t}),e.inputEl.addClass("prm-input-full-width"),e.inputEl.addClass("prm-input-min-height"),e.inputEl.addEventListener("keydown",t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.submit())}),window.setTimeout(()=>e.inputEl.focus(),50)}),new L.Setting(i).addButton(e=>e.setButtonText(a("common.cancel")).onClick(()=>this.close())).addButton(e=>e.setButtonText(a("common.save")).setCta().onClick(()=>this.submit()))}submit(){let i=this.value.trim();if(!i){this.close();return}this.onSubmit(i),this.close()}onClose(){this.contentEl.empty()}},de=class extends L.Modal{constructor(i,e={},t){super(i),this.value=e.text??"",this.strike=e.strike??!1,this.isEdit=e.isEdit??!1,this.onSubmit=t}onOpen(){let{contentEl:i}=this;i.createEl("h3",{text:a("notemodal.review.title")}),new L.Setting(i).setName(a("notemodal.review.content")).addTextArea(e=>{e.setValue(this.value).onChange(t=>{this.value=t}),e.inputEl.addClass("prm-input-full-width"),e.inputEl.addClass("prm-input-min-height"),e.inputEl.addEventListener("keydown",t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),this.submit())}),window.setTimeout(()=>e.inputEl.focus(),50)}),new L.Setting(i).setName(a("notemodal.review.strikethrough")).setDesc(a("notemodal.review.strikethroughDesc")).addToggle(e=>e.setValue(this.strike).onChange(t=>this.strike=t)),new L.Setting(i).addButton(e=>e.setButtonText(a("common.cancel")).onClick(()=>this.close())).addButton(e=>e.setButtonText(a("common.save")).setCta().onClick(()=>this.submit()))}submit(){if(!this.isEdit&&!this.value.trim()&&!this.strike){this.close();return}this.onSubmit(this.value.trim(),this.strike),this.close()}};var x=require("obsidian");function pe(s){return"'"+s.replace(/'/g,"'\\''")+"'"}var Pn=/[|&;<>`$(){}]/;function De(s){let e=s.replace(/\{\{[a-zA-Z]+\}\}/g,"").match(Pn);if(e)throw new Error(a("shell.error.forbiddenChar",{chars:e[0]}))}var En=new Set(["vaultPath","instructionFile","filePath","fileName","prompt"]);function Re(s){let i=/\{\{([a-zA-Z]+)\}\}/g,e=[],t;for(;(t=i.exec(s))!==null;){let n=t[1];if(!En.has(n))throw new Error(a("shell.error.unknownVariable",{var:n}));e.includes(n)||e.push(n)}return e}var K=[{id:"claude",label:"Claude Code",vendor:"Anthropic",detectCmd:"which claude",template:'cd {{vaultPath}} && claude "\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6"',installHint:"npm i -g @anthropic-ai/claude-code",isPreset:!0},{id:"codex",label:"Codex CLI",vendor:"OpenAI",detectCmd:"which codex",template:'cd {{vaultPath}} && codex "\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6"',installHint:"npm i -g @openai/codex",isPreset:!0},{id:"aider",label:"Aider",vendor:"Paul Gauthier",detectCmd:"which aider",template:'cd {{vaultPath}} && aider --msg "\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6"',installHint:"pip install aider-chat",isPreset:!0},{id:"gemini",label:"Gemini CLI",vendor:"Google",detectCmd:"which gemini",template:'cd {{vaultPath}} && gemini "\u8BFB\u53D6 {{instructionFile}}\uFF0C\u6309\u6279\u6CE8\u6307\u4EE4\u4FEE\u6539\u5BF9\u5E94\u6587\u4EF6"',installHint:"npm i -g @google/gemini-cli",isPreset:!0}],z=class{constructor(){this.customRules=[]}loadFromJSON(i){Array.isArray(i)&&(this.customRules=i.filter(e=>{if(!e.id||!e.label||!e.template||!e.detectCmd)return!1;try{return De(e.template),Re(e.template),!0}catch{return!1}}))}toJSON(){return this.customRules}allRules(){return[...K,...this.customRules]}getCustomRules(){return[...this.customRules]}getById(i){return this.allRules().find(e=>e.id===i)}add(i){if(De(i.template),Re(i.template),this.allRules().some(e=>e.id===i.id))throw new Error(a("cmdrule.error.idExists",{id:i.id}));this.customRules.push({...i,isPreset:!1})}update(i,e){if(K.some(r=>r.id===i))throw new Error(a("cmdrule.error.presetNotEditable"));let t=this.customRules.findIndex(r=>r.id===i);if(t===-1)throw new Error(a("cmdrule.error.notFound",{id:i}));let n={...this.customRules[t],...e};e.template&&(De(n.template),Re(n.template)),this.customRules[t]=n}remove(i){if(K.some(e=>e.id===i))throw new Error(a("cmdrule.error.presetNotDeletable"));this.customRules=this.customRules.filter(e=>e.id!==i)}};var Rt=require("obsidian"),I=()=>Rt.Platform.isMobile;var me=window.require??require,{execSync:It,exec:Mt,execFileSync:Ft}=me("child_process"),ee=me("fs"),Nt=me("os"),te=me("path"),Lt=me("crypto");function Dn(){let s=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin",`${process.env.HOME??""}/.local/bin`,`${process.env.HOME??""}/.npm-global/bin`,`${process.env.HOME??""}/.cargo/bin`].filter(Boolean),i=process.env.PATH??"",e=[...new Set([...i.split(":"),...s])].join(":");return{...process.env,PATH:e}}function Ie(s){if(I())return[];let i=Dn();return s.map(e=>{let t=!1;try{It(e.detectCmd,{encoding:"utf-8",timeout:5e3,stdio:"pipe",env:i}),t=!0}catch{t=!1}return{rule:e,installed:t}})}ue();var Fn={provider:"anthropic",apiKey:"",model:"",customEndpoint:"",maxTokens:4096},U={language:"auto",defaultMode:"reading",contextSpan:50,sidecarDir:".promptuary/annotations",exportDir:".promptuary/exports",includeReadingNotesInExport:!1,terminalApp:"Terminal",customCommandRules:[],apiSettings:{...Fn}},nt=class extends x.Modal{constructor(e,t){super(e);this.existingIds=t}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{contentEl:e,modalEl:t}=this;e.empty(),e.addClass("prm-add-rule-modal"),t.addClass("prm-add-rule-modal");let r=e.createDiv({cls:"prm-arm-header"}).createDiv({cls:"prm-arm-header-left"}),o=r.createDiv({cls:"prm-arm-icon"});(0,x.setIcon)(o,"zap");let l=r.createDiv({});l.createDiv({cls:"prm-arm-title",text:a("addrule.title")}),l.createDiv({cls:"prm-arm-subtitle",text:a("addrule.subtitle")});let c=e.createDiv({cls:"prm-arm-form"}),d="",p="",m="",u="",f="";new x.Setting(c).setName(a("addrule.id.name")).setDesc(a("addrule.id.desc")).addText(v=>v.setPlaceholder(a("addrule.id.placeholder")).onChange(S=>d=S.trim())),new x.Setting(c).setName(a("addrule.label.name")).setDesc(a("addrule.label.desc")).addText(v=>v.setPlaceholder(a("addrule.label.placeholder")).onChange(S=>p=S.trim())),new x.Setting(c).setName(a("addrule.detectCmd.name")).setDesc(a("addrule.detectCmd.desc")).addText(v=>v.setPlaceholder(a("addrule.detectCmd.placeholder")).onChange(S=>m=S.trim())),new x.Setting(c).setName(a("addrule.command.name")).setDesc(a("addrule.command.desc")).addTextArea(v=>v.setPlaceholder(a("addrule.command.placeholder")).onChange(S=>u=S.trim())),new x.Setting(c).setName(a("addrule.installHint.name")).setDesc(a("addrule.installHint.desc")).addText(v=>v.setPlaceholder(a("addrule.installHint.placeholder")).onChange(S=>f=S.trim()));let h=c.createDiv({cls:"prm-arm-var-ref"});h.createDiv({cls:"prm-arm-var-title",text:a("addrule.varTitle")});let g=h.createDiv({cls:"prm-arm-var-grid"}),b=[["{{vaultPath}}",a("addrule.var.vaultPath")],["{{instructionFile}}",a("addrule.var.instructionFile")],["{{filePath}}",a("addrule.var.filePath")],["{{fileName}}",a("addrule.var.fileName")],["{{prompt}}",a("addrule.var.prompt")]];for(let[v,S]of b){let T=g.createDiv({cls:"prm-arm-var-item"});T.createDiv({cls:"prm-arm-var-code",text:v}),T.createDiv({cls:"prm-arm-var-desc",text:S})}let A=e.createDiv({cls:"prm-arm-footer"}),y=A.createEl("button",{cls:"prm-arm-btn-cancel",text:a("addrule.btn.cancel")});y.onclick=()=>this.close();let C=A.createEl("button",{cls:"prm-arm-btn-save",text:a("addrule.btn.add")});C.onclick=()=>{if(!d||!p||!u||!m){new x.Notice(a("addrule.notice.requiredFields"));return}if(this.existingIds.includes(d)){new x.Notice(a("addrule.notice.idExists",{id:d}));return}try{let v=new z;v.loadFromJSON([]),v.add({id:d,label:p,detectCmd:m,template:u,installHint:f||a("addrule.defaultInstallHint")})}catch(v){new x.Notice(a("addrule.notice.validationFailed",{error:v.message}));return}this.resolve?.({id:d,label:p,detectCmd:m,template:u,installHint:f||a("addrule.defaultInstallHint")}),this.close()}}onClose(){this.resolve?.(null),this.contentEl.empty()}},Ne=class extends x.PluginSettingTab{constructor(e,t){super(e,t);this.plugin=t}display(){let{containerEl:e}=this;e.empty();let n=e.createDiv({cls:"prm-settings-header"}).createDiv({cls:"prm-settings-header-left"}),r=n.createDiv({cls:"prm-settings-page-icon"});if(this.plugin.logoUrl){let o=r.createEl("img",{cls:"prm-logo-img"});o.src=this.plugin.logoUrl,o.alt="Promptuary"}else(0,x.setIcon)(r,"prm-highlighter");n.createDiv({cls:"prm-settings-page-title",text:"Promptuary"}),this.renderSection(e,{icon:"file-text",title:a("settings.section.basic"),desc:a("settings.section.basicDesc"),open:!0,render:o=>this.renderBasicSettings(o)}),I()||(this.renderSection(e,{icon:"bot",title:a("settings.section.agent"),desc:a("settings.section.agentDesc"),open:!0,render:o=>this.renderAgentSettings(o)}),this.renderSection(e,{icon:"key-round",title:a("settings.section.api"),desc:a("settings.section.apiDesc"),open:!this.plugin.settings.apiSettings.apiKey,render:o=>this.renderAPISettings(o)}))}renderSection(e,t){let n=e.createDiv({cls:"prm-settings-section"}),r=n.createDiv({cls:"prm-settings-section-header"}),o=r.createDiv({cls:"prm-settings-section-left"}),l=o.createDiv({cls:"prm-settings-section-icon"});(0,x.setIcon)(l,t.icon);let c=o.createDiv({cls:"prm-settings-section-text"});c.createDiv({cls:"prm-settings-section-title",text:t.title}),c.createDiv({cls:"prm-settings-section-desc",text:t.desc});let d=r.createDiv({cls:"prm-settings-section-chevron"});(0,x.setIcon)(d,"chevron-down");let p=n.createDiv({cls:"prm-settings-section-body"});t.open&&(p.addClass("is-open"),d.addClass("is-open")),r.onclick=()=>{let m=p.hasClass("is-open");p.toggleClass("is-open",!m),d.toggleClass("is-open",!m)},t.render(p)}renderBasicSettings(e){new x.Setting(e).setName(a("settings.language.name")).setDesc(a("settings.language.desc")).addDropdown(t=>{t.addOption("auto",a("settings.language.auto")).addOption("zh-CN",a("settings.language.zhCN")).addOption("en",a("settings.language.en")).setValue(this.plugin.settings.language).onChange(async n=>{this.plugin.settings.language=n,await this.plugin.saveSettings(),be(n);let r=this.app;r.plugins?.disablePlugin&&r.plugins?.enablePlugin&&(await r.plugins.disablePlugin("promptuary"),await r.plugins.enablePlugin("promptuary"))})}),new x.Setting(e).setName(a("settings.defaultMode.name")).setDesc(a("settings.defaultMode.desc")).addDropdown(t=>t.addOption("reading",a("settings.defaultMode.reading")).addOption("reviewing",a("settings.defaultMode.review")).addOption("all",a("sidebar.mode.all")).setValue(this.plugin.settings.defaultMode).onChange(async n=>{this.plugin.settings.defaultMode=n,await this.plugin.saveSettings()})),new x.Setting(e).setName(a("settings.contextSpan.name")).setDesc(a("settings.contextSpan.desc")).addText(t=>t.setValue(String(this.plugin.settings.contextSpan)).onChange(async n=>{let r=parseInt(n,10);!Number.isNaN(r)&&r>0&&(this.plugin.settings.contextSpan=r,await this.plugin.saveSettings())})),new x.Setting(e).setName(a("settings.sidecarDir.name")).setDesc(a("settings.sidecarDir.desc")).addText(t=>t.setValue(this.plugin.settings.sidecarDir).onChange(async n=>{this.plugin.settings.sidecarDir=n.trim()||U.sidecarDir,await this.plugin.saveSettings()})),new x.Setting(e).setName(a("settings.exportDir.name")).setDesc(a("settings.exportDir.desc")).addText(t=>t.setValue(this.plugin.settings.exportDir).onChange(async n=>{this.plugin.settings.exportDir=n.trim()||U.exportDir,await this.plugin.saveSettings()})),new x.Setting(e).setName(a("settings.includeReadingNotes.name")).setDesc(a("settings.includeReadingNotes.desc")).addToggle(t=>t.setValue(this.plugin.settings.includeReadingNotesInExport).onChange(async n=>{this.plugin.settings.includeReadingNotesInExport=n,await this.plugin.saveSettings()}))}renderAgentSettings(e){new x.Setting(e).setName(a("settings.terminalApp.name")).setDesc(a("settings.terminalApp.desc")).addDropdown(u=>{u.addOption("Terminal",a("settings.terminalApp.terminal")+a("settings.terminalApp.defaultSuffix")).addOption("iTerm2",a("settings.terminalApp.iterm")).setValue(this.plugin.settings.terminalApp).onChange(async f=>{this.plugin.settings.terminalApp=f,await this.plugin.saveSettings()})});let t=Ie(K),n=e.createDiv({cls:"prm-agent-cards"});for(let u of t){let f=n.createDiv({cls:`prm-agent-card ${u.installed?"installed":"not-installed"}`});f.createDiv({cls:"prm-agent-card-avatar"}).setText(u.rule.label.charAt(0));let g=f.createDiv({cls:"prm-agent-card-info"}),b=g.createDiv({cls:"prm-agent-card-name-row"});b.createDiv({cls:"prm-agent-card-name",text:u.rule.label});let A=b.createDiv({cls:`prm-agent-card-badge ${u.installed?"installed":"missing"}`,text:u.installed?a("settings.detectedAgents.installed"):a("agent.select.missing")});u.rule.vendor&&g.createDiv({cls:"prm-agent-card-vendor",text:u.rule.vendor}),u.installed||g.createDiv({cls:"prm-agent-card-hint",text:`${a("settings.agentInstall")}${u.rule.installHint}`})}new x.Setting(e).setName(a("settings.redetectAgent.name")).setDesc(a("settings.redetectAgent.desc")).addButton(u=>u.setButtonText(a("settings.redetectAgent.btn")).onClick(()=>{this.plugin.invalidateAgentCache(),this.display(),new x.Notice(a("settings.redetectAgent.done"))}));let r=new z;r.loadFromJSON(this.plugin.settings.customCommandRules);let o=r.getCustomRules(),l=e.createDiv({cls:"prm-settings-sub-header"});l.createDiv({cls:"prm-settings-sub-title",text:a("settings.customRules.title")});let c=l.createEl("button",{cls:"prm-settings-sub-btn",text:`+ ${a("common.add")}`});if(c.onclick=async()=>{let u=r.allRules().map(h=>h.id),f=await new nt(this.app,u).openForResult();if(f)try{let h=new z;h.loadFromJSON(this.plugin.settings.customCommandRules),h.add(f),this.plugin.settings.customCommandRules=h.toJSON(),await this.plugin.saveSettings(),this.plugin.invalidateAgentCache(),this.display(),new x.Notice(a("settings.customRules.added",{label:f.label}))}catch(h){new x.Notice(a("settings.customRules.addFailed",{error:h.message}))}},o.length===0)e.createDiv({cls:"prm-settings-empty",text:a("settings.customRules.empty")});else{let u=e.createDiv({cls:"prm-rule-cards"});for(let f of o)this.renderCustomRuleCard(u,f)}let d=e.createEl("details",{cls:"prm-settings-var-details"});d.createEl("summary",{text:a("settings.varRef.title")});let p=d.createEl("table",{cls:"prm-settings-var-table"}),m=[["{{vaultPath}}",a("settings.varRef.vaultPath")],["{{instructionFile}}",a("settings.varRef.instructionFile")],["{{filePath}}",a("settings.varRef.filePath")],["{{fileName}}",a("settings.varRef.fileName")],["{{prompt}}",a("settings.varRef.prompt")]];for(let[u,f]of m){let h=p.createEl("tr");h.createEl("td",{text:u}),h.createEl("td",{text:f})}}renderCustomRuleCard(e,t){let n=e.createDiv({cls:"prm-rule-card"}),r=n.createDiv({cls:"prm-rule-card-info"});r.createDiv({cls:"prm-rule-card-label",text:t.label});let o=r.createDiv({cls:"prm-rule-card-meta"});o.createSpan({text:`${a("settings.ruleCard.detect")}: ${t.detectCmd}`});let l=t.template.length>60?t.template.slice(0,57)+"\u2026":t.template;o.createSpan({cls:"prm-rule-card-template"}).setText(`${a("settings.ruleCard.template")}: ${l}`);let d=n.createEl("button",{cls:"prm-rule-card-del",text:a("common.delete")});d.onclick=async()=>{let p=new z;p.loadFromJSON(this.plugin.settings.customCommandRules),p.remove(t.id),this.plugin.settings.customCommandRules=p.toJSON(),await this.plugin.saveSettings(),this.plugin.invalidateAgentCache(),this.display()}}renderAPISettings(e){let t=this.plugin.settings.apiSettings;new x.Setting(e).setName(a("settings.api.provider.name")).addDropdown(o=>o.addOption("anthropic","Anthropic (Claude)").addOption("openai","OpenAI (GPT)").addOption("deepseek","DeepSeek").addOption("gemini","Google Gemini").addOption("custom",a("settings.api.provider.custom")).setValue(t.provider).onChange(async l=>{t.provider=l,t.model=P[t.provider].model,await this.plugin.saveSettings(),this.display()})),new x.Setting(e).setName(a("settings.api.key.name")).setDesc(a("settings.api.key.desc")).addText(o=>{o.setPlaceholder(a("settings.api.key.placeholder")).setValue(t.apiKey).onChange(async d=>{t.apiKey=d.trim(),await this.plugin.saveSettings()}),o.inputEl.type="password",o.inputEl.addClass("prm-api-key-input");let l=o.inputEl.parentElement;l&&l.addClass("prm-relative");let c=l?.createEl("button",{cls:"prm-api-key-toggle"});c&&((0,x.setIcon)(c,"eye"),c.onclick=()=>{let d=o.inputEl;d.type==="password"?(d.type="text",(0,x.setIcon)(c,"eye-off")):(d.type="password",(0,x.setIcon)(c,"eye"))})}),new x.Setting(e).setName(a("settings.api.model.name")).setDesc(a("settings.api.model.desc",{model:P[t.provider].model})).addText(o=>o.setPlaceholder(P[t.provider].model).setValue(t.model).onChange(async l=>{t.model=l.trim(),await this.plugin.saveSettings()})),t.provider==="custom"&&new x.Setting(e).setName(a("settings.api.customEndpoint.name")).setDesc(a("settings.api.customEndpoint.desc")).addText(o=>o.setPlaceholder(a("settings.api.customEndpoint.placeholder")).setValue(t.customEndpoint).onChange(async l=>{t.customEndpoint=l.trim(),await this.plugin.saveSettings()})),new x.Setting(e).setName(a("settings.api.maxTokens.name")).setDesc(a("settings.api.maxTokens.desc")).addText(o=>o.setValue(String(t.maxTokens)).onChange(async l=>{let c=parseInt(l,10);!Number.isNaN(c)&&c>0&&(t.maxTokens=c,await this.plugin.saveSettings())}));let n=new x.Setting(e).setName(a("settings.api.test.name")).setDesc(a("settings.api.test.desc")),r=null;n.addButton(o=>{o.setButtonText(a("settings.api.test.btn")).onClick(async()=>{if(!t.apiKey){new x.Notice(a("settings.api.test.noKey"));return}o.setButtonText(a("settings.api.test.running")).setDisabled(!0);let{callAPI:l,API_SYSTEM_PROMPT:c}=await Promise.resolve().then(()=>(ue(),Ht)),d=await l({...t,model:t.model||P[t.provider].model},{systemPrompt:c,userMessage:'\u8BF7\u56DE\u590D"\u8FDE\u63A5\u6210\u529F"\uFF0C\u4EC5\u6B64\u56DB\u5B57\u3002'});o.setButtonText(a("settings.api.test.btn")).setDisabled(!1),d.success?(r="success",new x.Notice(a("settings.api.test.success",{model:t.model||P[t.provider].model}))):(r="fail",new x.Notice(a("settings.api.test.failed",{error:d.error??""}))),this.display()})})}};var k=require("obsidian");var H="promptuary-sidebar",Le=class extends k.ItemView{constructor(e,t){super(e);this.plugin=t;this.mode="reading";this.currentFilePath=null;this.currentHash=null;this.baselineMismatch=!1;this.refreshSeq=0;this.modifyDebounceTimer=null;this.lastReviewCount=0}getViewType(){return H}getDisplayText(){return"Promptuary"}getIcon(){return"highlighter"}async onOpen(){this.contentEl.empty(),this.container=this.contentEl.createDiv({cls:"promptuary-sidebar"}),this.mode=this.plugin.settings.defaultMode,this.headerEl=this.container.createDiv({cls:"prm-sidebar-header"}),this.contentEl2=this.container.createDiv({cls:"prm-sidebar-content"}),this.actionBarEl=this.container.createDiv({cls:"prm-sidebar-action-bar"}),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.onActiveLeafChange())),this.registerEvent(this.app.workspace.on("file-open",e=>this.onFileOpen(e))),this.registerEvent(this.app.vault.on("modify",async e=>{e.path===this.currentFilePath&&(this.modifyDebounceTimer!==null&&window.clearTimeout(this.modifyDebounceTimer),this.modifyDebounceTimer=window.setTimeout(()=>{this.modifyDebounceTimer=null,(async()=>(this.currentHash=await this.plugin.store.fileHash(e.path),await this.refresh()))()},300))})),this.registerEvent(this.plugin.store.on("change",e=>{e===this.currentFilePath&&this.refresh()})),this.plugin.onSettingsChanged=()=>this.reRenderActionBar(),await this.onActiveLeafChange()}setMode(e){this.mode=e,this.plugin.onModeChange(e),this.refresh()}setModeExternal(e){this.mode!==e&&(this.mode=e,this.refresh())}getMode(){return this.mode}getCurrentFilePath(){return this.currentFilePath}async onActiveLeafChange(){let e=this.app.workspace.getActiveViewOfType(k.MarkdownView);if(e?.file){e.file.path!==this.currentFilePath&&(this.currentFilePath=e.file.path,this.currentHash=await this.plugin.store.fileHash(e.file.path),await this.refresh());return}if(this.currentFilePath!==null)return;let t=this.app.workspace.getLeavesOfType("markdown");for(let n of t){let r=n.view;if(r?.file){this.currentFilePath=r.file.path,this.currentHash=await this.plugin.store.fileHash(r.file.path);break}}await this.refresh()}async onFileOpen(e){e&&e.extension==="md"&&e.path!==this.currentFilePath&&(this.currentFilePath=e.path,this.currentHash=await this.plugin.store.fileHash(e.path),await this.refresh())}async refresh(){let e=++this.refreshSeq;if(!this.currentFilePath){if(e!==this.refreshSeq)return;this.headerEl.empty(),this.contentEl2.empty(),this.actionBarEl.empty(),this.renderHeader(this.headerEl),this.renderEmptyState(this.contentEl2,a("sidebar.empty.openFile"));return}let t=await this.plugin.store.getFile(this.currentFilePath);if(e!==this.refreshSeq)return;let n={fuzzy:0,drifted:0,autoHealed:0,reviewRemoved:0,readingRemoved:0};if(!!t.baselineHash&&!!this.currentHash&&t.baselineHash!==this.currentHash){let o=Ot(this);if(o!==null){let l=[];for(let d of t.annotations){let p=V(o,d);if(p.status==="fuzzy")if((p.candidates?.length??0)===0&&p.from!==void 0&&p.to!==void 0){let m=this.plugin.settings.contextSpan,u=Math.max(0,p.from-m),f=Math.min(o.length,p.to+m),h=o.slice(p.from,p.to);await this.plugin.store.updateAnnotation(this.currentFilePath,d.id,{selectedText:h,contextBefore:o.slice(u,p.from),contextAfter:o.slice(p.to,f),lineHint:Q(o,p.from),occurrenceIndex:X(o,h,p.from)}),n.autoHealed++}else n.fuzzy++;else p.status==="drifted"&&l.push(d)}if(l.length>0)for(let d of l){if(d.type==="review"){await this.plugin.store.removeAnnotation(this.currentFilePath,d.id),n.reviewRemoved++;continue}let p=Ce(o,d);if(p.status==="auto-healed"&&p.from!==void 0&&p.to!==void 0){let m=this.plugin.settings.contextSpan,u=Math.max(0,p.from-m),f=Math.min(o.length,p.to+m),h=o.slice(p.from,p.to),g=o.slice(u,p.from),b=o.slice(p.to,f),A=Q(o,p.from),y=X(o,h,p.from);await this.plugin.store.updateAnnotation(this.currentFilePath,d.id,{selectedText:h,contextBefore:g,contextAfter:b,lineHint:A,occurrenceIndex:y}),n.autoHealed++}else await this.plugin.store.removeAnnotation(this.currentFilePath,d.id),n.readingRemoved++}let c=n.fuzzy+n.drifted;if(c===0&&this.currentHash){if(await this.plugin.store.confirmBaseline(this.currentFilePath,this.currentHash,!0),e!==this.refreshSeq)return;this.baselineMismatch=!1;let d=[];n.autoHealed>0&&d.push(a("sidebar.notice.autoHealed",{n:n.autoHealed})),n.reviewRemoved>0&&d.push(a("sidebar.notice.reviewAutoRemoved",{n:n.reviewRemoved})),n.readingRemoved>0&&d.push(a("sidebar.notice.invalidReadingRemoved",{n:n.readingRemoved})),d.length>0&&new k.Notice(d.join("\uFF0C"))}else{this.baselineMismatch=!0;let d=[];n.autoHealed>0&&d.push(a("sidebar.notice.autoHealed",{n:n.autoHealed})),n.reviewRemoved>0&&d.push(a("sidebar.notice.reviewAutoRemoved",{n:n.reviewRemoved})),n.readingRemoved>0&&d.push(a("sidebar.notice.invalidReadingRemoved",{n:n.readingRemoved})),c>0&&d.push(a("sidebar.notice.ambiguousCheck",{n:c})),d.length>0&&new k.Notice(d.join("\uFF0C"))}}else this.baselineMismatch=!1}else this.baselineMismatch=!1;e===this.refreshSeq&&this.paint(t.annotations,n)}paint(e,t){this.headerEl.empty(),this.renderHeader(this.headerEl),this.contentEl2.empty(),this.baselineMismatch&&this.renderBannerIn(this.contentEl2,t),this.currentFilePath&&this.renderReviewCleanupPrompt(this.contentEl2,this.currentFilePath),this.renderListIn(this.contentEl2,e),this.actionBarEl.empty();let n=e.filter(r=>r.type==="review").length;this.lastReviewCount=n,this.mode!=="reading"&&this.renderActionBar(this.actionBarEl,n)}renderEmptyState(e,t){let n=e.createDiv({cls:"prm-empty-state"});if(this.plugin.emptyStateUrl){let r=n.createEl("img",{cls:"prm-empty-state-img"});r.src=this.plugin.emptyStateUrl,r.alt=""}n.createDiv({cls:"prm-empty-state-text",text:t})}renderHeader(e){let t=e.createDiv({cls:"prm-header-row"}),n=t.createDiv({cls:"prm-header-left"}),r=n.createDiv({cls:"prm-header-icon"});if(this.plugin.logoUrl){let d=r.createEl("img",{cls:"prm-logo-img"});d.src=this.plugin.logoUrl,d.alt="Promptuary"}else(0,k.setIcon)(r,"prm-highlighter");n.createSpan({cls:"prm-header-title",text:"Promptuary"});let o=t.createEl("button",{cls:"prm-header-settings"});(0,k.setIcon)(o,"settings"),o.onclick=()=>{let d=this.app;d.setting?.open(),d.setting?.openTabById?.("promptuary")};let l=e.createDiv({cls:"prm-mode-capsule"}),c=[["reading",a("sidebar.mode.reading")],["reviewing",a("sidebar.mode.review")],["all",a("sidebar.mode.all")]];for(let[d,p]of c){let m=l.createEl("button",{text:p});this.mode===d&&m.addClass("active"),m.onclick=()=>this.setMode(d)}}renderActionBar(e,t){let n=t>0,r=this.plugin.executionState,o=r!==null;if(!I()){let h=e.createEl("button",{cls:"prm-action-execute"});(0,k.setIcon)(h,"sparkles"),h.title=a("sidebar.action.agentTitle");let g=o&&r.type==="agent";g?h.createSpan({text:a("sidebar.status.agentRunning")}):h.createSpan({text:a("sidebar.action.agentReview")}),h.disabled=!n||o,g&&h.addClass("prm-executing"),h.onclick=async()=>{if(!(!n||o)){if(!n){new k.Notice(a("main.notice.noReviewAnnotations"));return}this.plugin.executionState={type:"agent"},this.reRenderActionBar();try{await this.plugin.runAgentWithSelect()}finally{this.plugin.executionState=null,this.refresh()}}}}let l=e.createDiv({cls:"prm-action-row"}),c=!!this.plugin.settings.apiSettings?.apiKey,d=o&&r.type==="api",p=l.createEl("button",{cls:"prm-action-btn"});(0,k.setIcon)(p,"zap"),d?(p.createSpan({cls:"prm-action-short",text:"API"}),p.createSpan({cls:"prm-action-long",text:` ${a("sidebar.mode.review")}\u2026`})):(p.createSpan({cls:"prm-action-short",text:"API"}),p.createSpan({cls:"prm-action-long",text:` ${a("sidebar.mode.review")}`})),p.title=c?a("sidebar.action.apiTitle"):a("sidebar.action.noApiKey"),p.disabled=!c||o,d&&p.addClass("prm-executing"),p.onclick=async()=>{if(!(!c||o)){this.plugin.executionState={type:"api"},this.reRenderActionBar();try{await this.plugin.runAPIExecute()}finally{this.plugin.executionState=null,this.refresh()}}};let m=l.createEl("button",{cls:"prm-action-btn"});(0,k.setIcon)(m,"clipboard-copy"),m.createSpan({cls:"prm-action-short",text:"Prompt"}),m.createSpan({cls:"prm-action-long",text:` ${a("sidebar.action.copy")}`}),m.title=a("sidebar.action.copyTitle"),m.disabled=!n||o,m.onclick=()=>{this.currentFilePath?this.plugin.runCopyPrompt(this.currentFilePath):this.plugin.runCopyPrompt()};let u=l.createEl("button",{cls:"prm-action-btn prm-more-btn"});(0,k.setIcon)(u,"more-horizontal"),u.title=a("sidebar.action.exportTitle"),u.disabled=!n||o,u.onclick=()=>{if(!n||o)return;let h=new k.Menu;h.addItem(b=>{b.setTitle(a("sidebar.action.exportFile")).setIcon("file-text").onClick(async()=>{this.currentFilePath?await this.plugin.runExport(this.currentFilePath):await this.plugin.runExport()})});let g=u.getBoundingClientRect();h.showAtPosition({x:g.left,y:g.top-4})};let f=e.createDiv({cls:"prm-action-status"});o?(f.createSpan({cls:"prm-status-dot prm-status-dot-executing"}),f.createSpan({text:r.type==="agent"?a("sidebar.status.agentRunning"):a("sidebar.status.apiRunning")})):(f.createSpan({cls:"prm-status-dot"}),f.createSpan({text:a("sidebar.status.pendingReview",{n:t})}))}reRenderActionBar(){this.actionBarEl.empty(),this.mode!=="reading"&&this.renderActionBar(this.actionBarEl,this.lastReviewCount)}renderBannerIn(e,t){let n=e.createDiv({cls:"prm-banner"}),r=[];t.drifted>0&&r.push(a("sidebar.banner.drifted",{n:t.drifted})),t.fuzzy>0&&r.push(a("sidebar.banner.ambiguous",{n:t.fuzzy}));let o=r.length>0?`${a("sidebar.banner.changed")} ${r.join("\u3001")}\uFF0C${a("sidebar.banner.changedFull")}`:a("sidebar.banner.changedFull");n.createSpan({text:o});let l=n.createEl("button",{text:a("sidebar.banner.confirmAll")});l.onclick=async()=>{!this.currentFilePath||!this.currentHash||(await this.plugin.store.confirmBaseline(this.currentFilePath,this.currentHash),this.refresh(),new k.Notice(a("sidebar.banner.baselineUpdated")))}}renderReviewCleanupPrompt(e,t){let n=this.plugin.getPendingReviewCleanup(t);if(!n||n.count===0)return;let r=e.createDiv({cls:"prm-cleanup-prompt"}),o=r.createDiv({cls:"prm-cleanup-text"});o.createDiv({cls:"prm-cleanup-title",text:a("sidebar.cleanup.title")}),o.createDiv({cls:"prm-cleanup-desc",text:a("sidebar.cleanup.desc",{n:n.count})});let l=r.createDiv({cls:"prm-cleanup-actions"}),c=l.createEl("button",{cls:"prm-cleanup-keep",text:a("sidebar.cleanup.keep")});c.onclick=()=>this.plugin.dismissReviewCleanup(t);let d=l.createEl("button",{cls:"prm-cleanup-confirm",text:a("sidebar.cleanup.clean")});d.onclick=async()=>{await this.plugin.cleanupProcessedReviews(t)}}renderListIn(e,t){let n=t.filter(l=>this.mode==="reading"?l.type==="highlight"||l.type==="note":this.mode==="reviewing"?l.type==="review":!0);if(n.length===0){this.renderEmptyState(e,Nn(this.mode));return}let r=Ot(this),o=[...n].sort((l,c)=>{if(r){let d=V(r,l),p=V(r,c),m=d.from??Number.MAX_SAFE_INTEGER,u=p.from??Number.MAX_SAFE_INTEGER;if(m!==u)return m-u}return l.createdAt-c.createdAt});for(let l of o)this.renderCard(e,l,r)}renderCard(e,t,n){let r=n?V(n,t):null,o=e.createDiv({cls:"prm-card"}),l=Ln(t);l&&o.addClass(l),r&&(r.status==="fuzzy"&&o.addClass("fuzzy"),r.status==="auto-healed"&&o.addClass("auto-healed"),r.status==="drifted"&&o.addClass("drifted"));let c=o.createDiv({cls:"prm-card-meta"}),d=Hn(t);if(c.createSpan({cls:`prm-tag ${d}`,text:On(t)}),r?.status==="fuzzy"){let u=c.createSpan({cls:"prm-card-status-inline"});(0,k.setIcon)(u,"alert-triangle"),u.createSpan({text:` ${a("sidebar.card.ambiguous")}`})}if(r?.status==="auto-healed"){let u=c.createSpan({cls:"prm-card-status-inline"});(0,k.setIcon)(u,"wrench"),u.createSpan({text:` ${a("sidebar.card.autoHealed")}`})}if(r?.status==="drifted"){let u=c.createSpan({cls:"prm-card-status-inline"});(0,k.setIcon)(u,"alert-triangle"),u.createSpan({text:` ${a("sidebar.card.drifted")}`})}let p=c.createDiv({cls:"prm-card-meta-spacer"}),m=c.createEl("button",{cls:"prm-card-del-btn",text:a("sidebar.card.delete")});if(m.onclick=u=>{u.stopPropagation(),this.plugin.deleteAnnotation(t)},t.type==="review"){o.createDiv({cls:"prm-card-quote prm-quote-orange"+(t.strike?" strike":"")}).setText(t.selectedText),t.reviewText&&o.createDiv({cls:"prm-card-text prm-text-purple"}).setText(t.reviewText);let f=(this.currentFilePath??"").split("/").pop()??"",h=o.createDiv({cls:"prm-card-source"});h.createSpan({text:f}),h.createSpan({text:` \xB7 L.${t.lineHint}`})}else{o.createDiv({cls:"prm-card-quote"+(t.strike?" strike":"")}).setText(t.selectedText),t.type==="note"&&t.noteText&&o.createDiv({cls:"prm-card-text",text:t.noteText});let f=(this.currentFilePath??"").split("/").pop()??"",h=o.createDiv({cls:"prm-card-source"});h.createSpan({text:f}),h.createSpan({text:` \xB7 L.${t.lineHint}`})}o.onclick=()=>this.jumpTo(t)}async jumpTo(e){if(!this.currentFilePath)return;let t=this.app.vault.getAbstractFileByPath(this.currentFilePath);if(!(t instanceof k.TFile))return;await this.app.workspace.getLeaf(!1).openFile(t);let r=this.app.workspace.getActiveViewOfType(k.MarkdownView);if(!r)return;let o=r.editor.getValue(),l=V(o,e);if(l.status==="drifted"||l.from===void 0||l.to===void 0){new k.Notice(a("sidebar.notice.cannotLocate"));return}let c=r.editor.offsetToPos(l.from),d=r.editor.offsetToPos(l.to);r.editor.setSelection(c,d),r.editor.scrollIntoView({from:c,to:d},!0);let p=r.editor.cm;p&&this.plugin.popover&&window.requestAnimationFrame(()=>{this.plugin.popover.showForAnnotation(p,l.from,l.to,e)})}};function Nn(s){return s==="reading"?a("sidebar.empty.reading"):s==="reviewing"?a("sidebar.empty.review"):a("sidebar.empty.all")}function Ln(s){return s.type==="highlight"?`color-${s.highlightColor??"yellow"}`:s.type==="note"?`color-${s.highlightColor??"yellow"}`:s.type==="review"?"color-orange":null}function Hn(s){return s.type==="highlight"||s.type==="note"?s.highlightColor??"yellow":"orange"}function On(s){return s.type==="highlight"?a("sidebar.tag.highlight"):s.type==="note"?a("sidebar.tag.note"):s.type==="review"?s.strike?a("sidebar.tag.delete"):a("sidebar.tag.review"):""}function Ot(s){let i=s.getCurrentFilePath();if(!i)return null;let e=s.app.workspace.getLeavesOfType("markdown");for(let t of e){let n=t.view;if(n?.file?.path===i)return n.editor.getValue()}return null}var W=require("obsidian");function Be(s){return Math.ceil(s.length/4)}var Bn=1e5;function it(s,i,e,t){let n=e.annotations.filter(c=>c.type==="review"),r=e.annotations.filter(c=>c.type==="note"),o=new Date().toISOString().slice(0,10),l=`# ${a("export.reviewTitle")} \u2014 ${s} -`;return l+=`- ${a("export.originalFile")}: [[${Fn(i)}]] +`;return l+=`- ${a("export.originalFile")}: [[${$n(i)}]] `,l+=`- ${a("export.exportTime")}: ${o} `,l+=`- ${a("export.reviewCount")}: ${n.length} `,l+=`- ${a("export.includeReading")}: ${t.includeReadingNotes?a("common.yes"):a("common.no")} @@ -299,29 +299,29 @@ ${a("export.none")} `,n.forEach((c,d)=>{let p=c.strike?a("export.strikethrough"):"\u6279\u9605";l+=`### ${d+1}. ${p} `,l+=`${a("export.original")}\uFF1A -`,l+=`> ${F(c.selectedText)} +`,l+=`> ${N(c.selectedText)} `,l+=`${a("export.context")}\uFF1A -`,l+=`> \u524D\uFF1A${F(c.contextBefore)} -`,l+=`> \u540E\uFF1A${F(c.contextAfter)} +`,l+=`> \u524D\uFF1A${N(c.contextBefore)} +`,l+=`> \u540E\uFF1A${N(c.contextAfter)} `,l+=`${a("export.opinion")}\uFF1A -`;let m=c.reviewText?c.reviewText:c.strike?"\u7528\u6237\u6807\u8BB0\u4E3A\u5220\u9664\u7EBF\u3002\u8BF7\u5224\u65AD\u662F\u5426\u5220\u9664\u6216\u5408\u5E76\u3002":"\uFF08\u65E0\u6587\u672C\uFF09";l+=`> ${F(m)} +`;let m=c.reviewText?c.reviewText:c.strike?"\u7528\u6237\u6807\u8BB0\u4E3A\u5220\u9664\u7EBF\u3002\u8BF7\u5224\u65AD\u662F\u5426\u5220\u9664\u6216\u5408\u5E76\u3002":"\uFF08\u65E0\u6587\u672C\uFF09";l+=`> ${N(m)} `})),t.includeReadingNotes&&r.length>0&&(l+=`--- ## \u9605\u8BFB\u7B14\u8BB0\uFF08\u53C2\u8003\u4E0A\u4E0B\u6587\uFF09 `,r.forEach((c,d)=>{l+=`### ${d+1}. \u7B14\u8BB0 -`,l+=`> ${F(c.selectedText)} +`,l+=`> ${N(c.selectedText)} -`,l+=`${F(c.noteText??"")} +`,l+=`${N(c.noteText??"")} `})),l+=`--- `,l+=`## ${a("export.execRequirement")} `,l+=a("export.execRequirementText")+` -`,l}function Be(s,i,e,t){let n=e.annotations.filter(l=>l.type==="review"),r=e.annotations.filter(l=>l.type==="note"),o=`${a("export.promptHeader")}\u300A${s}\u300B +`,l}function $e(s,i,e,t){let n=e.annotations.filter(l=>l.type==="review"),r=e.annotations.filter(l=>l.type==="note"),o=`${a("export.promptHeader")}\u300A${s}\u300B `;return o+=`${a("export.execRequirement")}\uFF1A `,o+=a("export.execRequirementText")+` @@ -334,27 +334,135 @@ ${a("export.none")} `,n.length===0?o+=`${a("export.none")} `:n.forEach((l,c)=>{o+=`### ${c+1}. ${l.strike?a("export.strikethrough"):"\u6279\u9605"} -`,o+=`${a("export.original")}\uFF1A"${F(l.selectedText)}" -`,o+=`${a("export.context")}\uFF08\u524D\uFF09\uFF1A${F(l.contextBefore)} -`,o+=`${a("export.context")}\uFF08\u540E\uFF09\uFF1A${F(l.contextAfter)} +`,o+=`${a("export.original")}\uFF1A"${N(l.selectedText)}" +`,o+=`${a("export.context")}\uFF08\u524D\uFF09\uFF1A${N(l.contextBefore)} +`,o+=`${a("export.context")}\uFF08\u540E\uFF09\uFF1A${N(l.contextAfter)} `;let d=l.reviewText?l.reviewText:l.strike?"\u8BF7\u5220\u9664\u6216\u4E0E\u76F8\u90BB\u6BB5\u843D\u5408\u5E76\u3002":"\uFF08\u65E0\u6587\u672C\uFF09";o+=`${a("export.opinion")}\uFF1A${d} `}),t.includeReadingNotes&&r.length>0&&(o+=`## \u9605\u8BFB\u7B14\u8BB0\uFF08\u53C2\u8003\uFF09 `,r.forEach((l,c)=>{o+=`### ${c+1}. -`,o+=`\u539F\u6587\uFF1A"${F(l.selectedText)}" -`,o+=`\u7B14\u8BB0\uFF1A${F(l.noteText??"")} +`,o+=`\u539F\u6587\uFF1A"${N(l.selectedText)}" +`,o+=`\u7B14\u8BB0\uFF1A${N(l.noteText??"")} -`})),o}function Fn(s){return s.replace(/\.md$/i,"")}function F(s){return s.replace(/\n/g," ").trim()}var Ne=class{constructor(i,e){this.app=i;this.getExportDir=e}get exportDir(){return this.getExportDir()}async exportToVault(i,e,t){let n=this.app.vault.getAbstractFileByPath(i);if(!(n instanceof z.TFile))return new z.Notice(a("export.notice.fileNotFound")),null;let r=n.basename,o=tt(r,i,e,t),l=this.app.vault.adapter;await l.exists(this.exportDir)||await l.mkdir(this.exportDir);let c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=`${this.exportDir}/${r}-${c}.md`;await l.write(d,o);let p=He(o);return p>Mn?new z.Notice(a("export.notice.exportedTokens",{n:p})):new z.Notice(a("export.notice.exportedTokens",{n:p})),d}},Le=class{constructor(i){this.app=i}async copyToClipboard(i,e,t){let n=this.app.vault.getAbstractFileByPath(i);if(!(n instanceof z.TFile)){new z.Notice(a("export.notice.fileNotFound"));return}let r=n.basename,l=`${this.app.vault.adapter.basePath??this.app.vault.getRoot().path}/${i}`,c=Be(r,l,e,t);await H(c);let d=He(c);new z.Notice(a("export.notice.promptCopied",{n:d}))}};async function H(s){try{await navigator.clipboard.writeText(s)}catch{await navigator.clipboard.writeText(s)}}var Oe=require("obsidian");function Nn(s,i){let e=s.vault.adapter;if(typeof e.getFullPath=="function")return e.getFullPath(i);let t=e.basePath;return t?`${t}/${i}`:null}async function Nt(s,i){if(R())return new Oe.Notice(a("folder.notice.mobileNotSupported")),{success:!1,path:"",error:"mobile"};let e=Nn(s,i);if(!e)return new Oe.Notice(a("folder.notice.cannotResolveFile")),{success:!1,path:i,error:"no-abs-path"};try{let t;return process.platform==="darwin"?t=`open -R "${e}"`:process.platform==="win32"?t=`explorer /select,"${e}"`:t=`xdg-open "${e.substring(0,e.lastIndexOf("/"))}"`,await new Promise((n,r)=>{Rt(t,o=>{o?r(o):n()})}),{success:!0,path:e}}catch(t){let n=t instanceof Error?t.message:String(t);return new Oe.Notice(a("folder.notice.openFailed",{error:n})),{success:!1,path:e,error:n}}}function nt(s,i){let e=s.template;for(let[t,n]of Object.entries(i)){let r=`{{${t}}}`;e.includes(r)&&(e=e.split(r).join(Dt(n)))}return e}var ee=require("obsidian");function Lt(s){if(R()){H(s.command),new ee.Notice(a("terminal.notice.copied")),s.onCopied?.();return}let i=process.platform==="darwin",e=process.platform==="win32";i?Ln(s):e?(H(s.command),new ee.Notice(a("terminal.notice.copiedWin")),s.onCopied?.()):(H(s.command),new ee.Notice(a("terminal.notice.copiedLinux")),s.onCopied?.())}function Ln(s){let i=Ze.join(It.tmpdir(),`prm-agent-${Date.now()}.sh`);le.writeFileSync(i,`#!/bin/bash +`})),o}function $n(s){return s.replace(/\.md$/i,"")}function N(s){return s.replace(/\n/g," ").trim()}var He=class{constructor(i,e){this.app=i;this.getExportDir=e}get exportDir(){return this.getExportDir()}async exportToVault(i,e,t){let n=this.app.vault.getAbstractFileByPath(i);if(!(n instanceof W.TFile))return new W.Notice(a("export.notice.fileNotFound")),null;let r=n.basename,o=it(r,i,e,t),l=this.app.vault.adapter;await l.exists(this.exportDir)||await l.mkdir(this.exportDir);let c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=`${this.exportDir}/${r}-${c}.md`;await l.write(d,o);let p=Be(o);return p>Bn?new W.Notice(a("export.notice.exportedTokens",{n:p})):new W.Notice(a("export.notice.exportedTokens",{n:p})),d}},Oe=class{constructor(i){this.app=i}async copyToClipboard(i,e,t){let n=this.app.vault.getAbstractFileByPath(i);if(!(n instanceof W.TFile)){new W.Notice(a("export.notice.fileNotFound"));return}let r=n.basename,l=`${this.app.vault.adapter.basePath??this.app.vault.getRoot().path}/${i}`,c=$e(r,l,e,t);await O(c);let d=Be(c);new W.Notice(a("export.notice.promptCopied",{n:d}))}};async function O(s){try{await navigator.clipboard.writeText(s)}catch{await navigator.clipboard.writeText(s)}}var Ve=require("obsidian");function Vn(s,i){let e=s.vault.adapter;if(typeof e.getFullPath=="function")return e.getFullPath(i);let t=e.basePath;return t?`${t}/${i}`:null}async function Bt(s,i){if(I())return new Ve.Notice(a("folder.notice.mobileNotSupported")),{success:!1,path:"",error:"mobile"};let e=Vn(s,i);if(!e)return new Ve.Notice(a("folder.notice.cannotResolveFile")),{success:!1,path:i,error:"no-abs-path"};try{let t;return process.platform==="darwin"?t=`open -R "${e}"`:process.platform==="win32"?t=`explorer /select,"${e}"`:t=`xdg-open "${e.substring(0,e.lastIndexOf("/"))}"`,await new Promise((n,r)=>{Mt(t,o=>{o?r(o):n()})}),{success:!0,path:e}}catch(t){let n=t instanceof Error?t.message:String(t);return new Ve.Notice(a("folder.notice.openFailed",{error:n})),{success:!1,path:e,error:n}}}function rt(s,i){let e=s.template;for(let[t,n]of Object.entries(i)){let r=`{{${t}}}`;e.includes(r)&&(e=e.split(r).join(pe(n)))}return e}var ne=require("obsidian");var zn="Promptuary Agent";function $t(s){if(I()){O(s.command),new ne.Notice(a("terminal.notice.copied")),s.onCopied?.();return}let i=process.platform==="darwin",e=process.platform==="win32";i?Wn(s):e?(O(s.command),new ne.Notice(a("terminal.notice.copiedWin")),s.onCopied?.()):(O(s.command),new ne.Notice(a("terminal.notice.copiedLinux")),s.onCopied?.())}function Wn(s){let i=te.join(Nt.tmpdir(),`prm-agent-${Date.now()}.sh`);ee.writeFileSync(i,`#!/bin/bash ${s.command} -`,{mode:493}),window.setTimeout(()=>{try{le.unlinkSync(i)}catch{}},6e4);let e;s.terminalApp==="iTerm2"?e=`tell application "iTerm" -activate -create window with default profile command "${i}" -end tell`:e=`tell application "Terminal" -do script "${i}" -activate -end tell`;try{De(`osascript -e '${e}'`,{encoding:"utf-8",timeout:1e4,stdio:"pipe"}),new ee.Notice(a("terminal.notice.launched",{app:s.terminalApp})),s.onLaunched?.()}catch{H(s.command),new ee.Notice(a("terminal.notice.launchFailed")),s.onCopied?.()}}var de=class{constructor(){this.status="idle";this.timer=null;this.resolve=null;this.watchedAbsPath=null;this.cleanup=()=>{this.timer&&(window.clearTimeout(this.timer),this.timer=null)}}startMonitor(i,e,t=5*60*1e3){this.status="running";let n=i.vault.adapter.basePath??"",r=Ze.join(n,e);return this.watchedAbsPath=r,new Promise(o=>{this.resolve=o,this.timer=window.setTimeout(()=>{this.cleanup(),this.status="timeout",o(!1)},t);let l=(d,p)=>{d.mtimeMs!==p.mtimeMs&&this.status==="running"&&(this.cleanup(),this.status="detected",o(!0))};le.watchFile(r,{persistent:!1,interval:1e3},l);let c=this.cleanup;this.cleanup=()=>{c();try{le.unwatchFile(r,l)}catch{}}})}cancel(){this.status==="running"&&(this.cleanup(),this.status="idle",this.resolve?.(!1))}getStatus(){return this.status}};var I=require("obsidian");var Ht={C:{bg:"rgba(167,139,250,0.10)",border:"rgba(167,139,250,0.20)",text:"rgba(167,139,250,0.90)"},O:{bg:"rgba(74,222,128,0.08)",border:"rgba(74,222,128,0.15)",text:"rgba(74,222,128,0.80)"},A:{bg:"rgba(96,165,250,0.08)",border:"rgba(96,165,250,0.15)",text:"rgba(96,165,250,0.80)"},G:{bg:"rgba(251,191,36,0.08)",border:"rgba(251,191,36,0.15)",text:"rgba(251,191,36,0.80)"}};function Hn(s){let i=s[0]?.toUpperCase()??"C";return Ht[i]??Ht.C}var $e=class extends I.Modal{constructor(e,t,n,r){super(e);this.command=t;this.rule=n;this.instructionFile=r;this.resolve=null}openForConfirmation(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-confirm-modal");let t=Hn(this.rule.label),n=e.createDiv({cls:"prm-ccm-header"}),r=n.createDiv({cls:"prm-ccm-header-left"}),o=r.createDiv({cls:"prm-ccm-icon"});(0,I.setIcon)(o,"terminal");let l=r.createDiv();l.createDiv({cls:"prm-ccm-title",text:a("agent.confirm.title")}),l.createDiv({cls:"prm-ccm-subtitle",text:a("agent.confirm.subtitle",{label:this.rule.label})});let c=n.createEl("button",{cls:"prm-ccm-close"});(0,I.setIcon)(c,"x"),c.onclick=()=>{this.resolve?.(!1),this.close()};let d=e.createDiv({cls:"prm-ccm-agent-row"}),p=d.createDiv({cls:"prm-ccm-agent-avatar"});p.style.setProperty("--prm-color-bg",t.bg),p.style.setProperty("--prm-color-border",t.border),p.addClass("prm-dynamic-bg"),p.addClass("prm-dynamic-border-color");let m=p.createSpan({cls:"prm-ccm-agent-char",text:this.rule.label[0]});m.style.setProperty("--prm-color-text",t.text),m.addClass("prm-dynamic-text-color"),d.createSpan({cls:"prm-ccm-agent-name",text:this.rule.label});let u=d.createSpan({cls:"prm-ccm-agent-badge installed",text:a("agent.confirm.installed")});this.rule.vendor&&d.createSpan({cls:"prm-ccm-agent-vendor",text:`${this.rule.vendor}`});let h=e.createDiv({cls:"prm-ccm-cmd-wrap"}).createDiv({cls:"prm-ccm-cmd-box"});h.createDiv({cls:"prm-ccm-cmd-header"}).createSpan({cls:"prm-ccm-cmd-label",text:a("agent.confirm.commandLabel")}),h.createEl("code",{cls:"prm-ccm-code",text:this.command});let b=e.createDiv({cls:"prm-ccm-warning"}),y=b.createDiv({cls:"prm-ccm-warning-icon"});if((0,I.setIcon)(y,"alert-triangle"),b.createEl("p",{cls:"prm-ccm-warning-text",text:a("agent.confirm.warning")}),this.instructionFile){let te=e.createDiv({cls:"prm-ccm-hint"}),at=te.createDiv({cls:"prm-ccm-hint-icon"});(0,I.setIcon)(at,"file-text"),te.createSpan({cls:"prm-ccm-hint-text",text:a("agent.confirm.instructionFile",{path:this.instructionFile})})}let S=e.createDiv({cls:"prm-ccm-footer"}),v=S.createDiv({cls:"prm-ccm-footer-left"}).createEl("button",{cls:"prm-ccm-btn prm-ccm-btn-cancel"}),C=v.createSpan({cls:"prm-ccm-btn-inner"}),P=C.createSpan({cls:"prm-ccm-btn-icon"});(0,I.setIcon)(P,"x"),C.createSpan({text:a("agent.confirm.btn.cancel")}),v.onclick=()=>{this.resolve?.(!1),this.close()};let M=S.createDiv({cls:"prm-ccm-footer-right"}),T=M.createEl("button",{cls:"prm-ccm-btn prm-ccm-btn-copy"}),B=T.createSpan({cls:"prm-ccm-btn-inner"}),O=B.createSpan({cls:"prm-ccm-btn-icon"});(0,I.setIcon)(O,"copy"),B.createSpan({text:a("agent.confirm.btn.copyCommand")}),T.onclick=()=>{H(this.command),new I.Notice(a("agent.confirm.notice.copied")),this.resolve?.(!1),this.close()};let j=M.createEl("button",{cls:"prm-ccm-btn prm-ccm-btn-exec"}),he=j.createSpan({cls:"prm-ccm-btn-inner"}),_e=he.createSpan({cls:"prm-ccm-btn-icon"});(0,I.setIcon)(_e,"play"),he.createSpan({text:a("agent.confirm.btn.execute")}),j.onclick=()=>{this.resolve?.(!0),this.close()}}onClose(){this.resolve?.(!1),this.resolve=null}};var pe=require("obsidian");var Bt={C:{bg:"rgba(167,139,250,0.10)",border:"rgba(167,139,250,0.20)",text:"rgba(167,139,250,0.90)"},O:{bg:"rgba(74,222,128,0.08)",border:"rgba(74,222,128,0.15)",text:"rgba(74,222,128,0.80)"},A:{bg:"rgba(96,165,250,0.08)",border:"rgba(96,165,250,0.15)",text:"rgba(96,165,250,0.80)"},G:{bg:"rgba(251,191,36,0.08)",border:"rgba(251,191,36,0.15)",text:"rgba(251,191,36,0.80)"}};function Bn(s){let i=s[0]?.toUpperCase()??"C";return Bt[i]??Bt.C}var Ve=class extends pe.Modal{constructor(e,t){super(e);this.agents=t;this.selected=null;this.resolve=null}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-agent-select-modal");let t=e.createDiv({cls:"prm-asm-header"}),n=t.createDiv({cls:"prm-asm-header-left"}),r=n.createDiv({cls:"prm-asm-icon"});(0,pe.setIcon)(r,"bot");let o=n.createDiv();o.createDiv({cls:"prm-asm-title",text:a("agent.select.title")}),o.createDiv({cls:"prm-asm-subtitle",text:a("agent.select.subtitle")});let l=t.createEl("button",{cls:"prm-asm-close"});(0,pe.setIcon)(l,"x"),l.onclick=()=>{this.resolve?.({rule:null}),this.close()};let c=e.createDiv({cls:"prm-asm-list"}),d=this.agents.find(h=>h.installed);d&&(this.selected=d.rule);let p=new Map;for(let h of this.agents){let{rule:f,installed:b}=h,y=Bn(f.label),S=this.selected?.id===f.id,A=c.createDiv({cls:"prm-asm-row"+(S?" active":"")+(b?"":" disabled")});p.set(f.id,A);let v=A.createDiv({cls:"prm-asm-avatar"});v.style.setProperty("--prm-color-bg",y.bg),v.style.setProperty("--prm-color-border",y.border),v.addClass("prm-dynamic-bg"),v.addClass("prm-dynamic-border-color"),v.createSpan({cls:"prm-asm-avatar-char",text:f.label[0]}),v.querySelector(".prm-asm-avatar-char").style.setProperty("--prm-color-text",y.text),v.querySelector(".prm-asm-avatar-char").addClass("prm-dynamic-text-color");let C=A.createDiv({cls:"prm-asm-info"}),P=C.createDiv({cls:"prm-asm-name-row"});P.createSpan({cls:"prm-asm-name",text:f.label});let M=P.createSpan({cls:"prm-asm-badge "+(b?"installed":"missing"),text:b?a("agent.select.installed"):a("agent.select.missing")});C.createDiv({cls:"prm-asm-meta",text:f.vendor?`${f.vendor} \xB7 ${f.installHint}`:f.installHint});let T=A.createDiv({cls:"prm-asm-radio"+(S?" selected":"")});S&&T.createDiv({cls:"prm-asm-radio-dot"}),b&&(A.onclick=()=>{this.selected=f;for(let[B,O]of p){O.removeClass("active");let j=O.querySelector(".prm-asm-radio");j?.removeClass("selected"),j?.querySelector(".prm-asm-radio-dot")?.remove()}A.addClass("active"),T.addClass("selected"),T.querySelector(".prm-asm-radio-dot")||T.createDiv({cls:"prm-asm-radio-dot"})})}let m=e.createDiv({cls:"prm-asm-footer"}),u=m.createEl("button",{cls:"prm-asm-config-btn",text:a("agent.select.addCustom")});u.onclick=()=>{let h=this.app;h.setting?.open(),h.setting?.openTabById?.("promptuary"),this.resolve?.({rule:null}),this.close()};let g=m.createEl("button",{cls:"prm-asm-confirm-btn",text:a("agent.select.btn.confirm")});g.onclick=()=>{this.resolve?.({rule:this.selected}),this.close()}}onClose(){this.resolve?.({rule:null}),this.resolve=null}};var W=require("obsidian");function q(){}q.prototype={diff:function(i,e){var t,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n=="function"&&(r=n,n={}),this.options=n;var o=this;function l(v){return r?(setTimeout(function(){r(void 0,v)},0),!0):v}i=this.castInput(i),e=this.castInput(e),i=this.removeEmpty(this.tokenize(i)),e=this.removeEmpty(this.tokenize(e));var c=e.length,d=i.length,p=1,m=c+d;n.maxEditLength&&(m=Math.min(m,n.maxEditLength));var u=(t=n.timeout)!==null&&t!==void 0?t:1/0,g=Date.now()+u,h=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(h[0],e,i,0);if(h[0].oldPos+1>=d&&f+1>=c)return l([{value:this.join(e),count:e.length}]);var b=-1/0,y=1/0;function S(){for(var v=Math.max(b,-p);v<=Math.min(y,p);v+=2){var C=void 0,P=h[v-1],M=h[v+1];P&&(h[v-1]=void 0);var T=!1;if(M){var B=M.oldPos-v;T=M&&0<=B&&B=d&&f+1>=c)return l(On(o,C.lastComponent,e,i,o.useLongestToken));h[v]=C,C.oldPos+1>=d&&(y=Math.min(y,v-1)),f+1>=c&&(b=Math.max(b,v+1))}p++}if(r)(function v(){setTimeout(function(){if(p>m||Date.now()>g)return r();S()||v()},0)})();else for(;p<=m&&Date.now()<=g;){var A=S();if(A)return A}},addToPath:function(i,e,t,n){var r=i.lastComponent;return r&&r.added===e&&r.removed===t?{oldPos:i.oldPos+n,lastComponent:{count:r.count+1,added:e,removed:t,previousComponent:r.previousComponent}}:{oldPos:i.oldPos+n,lastComponent:{count:1,added:e,removed:t,previousComponent:r}}},extractCommon:function(i,e,t,n){for(var r=e.length,o=t.length,l=i.oldPos,c=l-n,d=0;c+1f.length?y:f}),m.value=s.join(u)}else m.value=s.join(e.slice(d,d+m.count));d+=m.count,m.added||(p+=m.count)}}var h=r[c-1];return c>1&&typeof h.value=="string"&&(h.added||h.removed)&&s.equals("",h.value)&&(r[c-2].value+=h.value,r.pop()),r}var Dr=new q;var Ot=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,$t=/\S/,Vt=new q;Vt.equals=function(s,i){return this.options.ignoreCase&&(s=s.toLowerCase(),i=i.toLowerCase()),s===i||this.options.ignoreWhitespace&&!$t.test(s)&&!$t.test(i)};Vt.tokenize=function(s){for(var i=s.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),e=0;e"u"?e:o}:t;return typeof s=="string"?s:JSON.stringify(it(s,null,null,n),n," ")};me.equals=function(s,i){return q.prototype.equals.call(me,s.replace(/,([\r\n])/g,"$1"),i.replace(/,([\r\n])/g,"$1"))};function it(s,i,e,t,n){i=i||[],e=e||[],t&&(s=t(n,s));var r;for(r=0;r0&&c[c.length-1]===""&&c.pop(),l.added)for(let d of c)t.push({index:o,type:"added",content:d,newLineNumber:r++}),o++;else if(l.removed)for(let d of c)t.push({index:o,type:"removed",content:d,oldLineNumber:n++}),o++;else for(let d of c)t.push({index:o,type:"unchanged",content:d,oldLineNumber:n++,newLineNumber:r++}),o++}return t}function qt(s){let i=0,e=0;for(let t of s)t.type==="added"&&i++,t.type==="removed"&&e++;return{added:i,removed:e}}function Wt(s,i,e){let t=st(s,""),n=[];for(let r of i){let o=e.get(r.index);switch(r.type){case"unchanged":n.push(r.content);break;case"removed":o===!0||n.push(r.content);break;case"added":o!==!1&&n.push(r.content);break}}return n.join(` +`,{mode:493}),window.setTimeout(()=>{try{ee.unlinkSync(i)}catch{}},6e4);let e=_n(i,s.vaultPath),t=s.terminalApp==="iTerm2"?jn(e,s.vaultPath):qn(e,s.vaultPath);try{Ft("osascript",[],{input:t,encoding:"utf-8",timeout:1e4,stdio:"pipe"}),new ne.Notice(a("terminal.notice.launched",{app:s.terminalApp})),s.onLaunched?.()}catch{O(s.command),new ne.Notice(a("terminal.notice.launchFailed")),s.onCopied?.()}}function qn(s,i){let e=ie(s),t=ie(zt(i)),n=ie(ze(i));return` +${Vt()} + +tell application "Terminal" + activate + set targetTab to missing value + set targetCwd to "${n}" + + repeat with terminalWindow in windows + repeat with terminalTab in tabs of terminalWindow + if (custom title of terminalTab is "${t}") and (busy of terminalTab is false) then + set targetTab to terminalTab + set index of terminalWindow to 1 + set selected of terminalTab to true + exit repeat + end if + end repeat + if targetTab is not missing value then exit repeat + end repeat + + if targetTab is missing value then + repeat with terminalWindow in windows + repeat with terminalTab in tabs of terminalWindow + if busy of terminalTab is false then + set tabCwd to my promptuaryCwdForTty(tty of terminalTab) + if tabCwd is targetCwd then + set targetTab to terminalTab + set index of terminalWindow to 1 + set selected of terminalTab to true + exit repeat + end if + end if + end repeat + if targetTab is not missing value then exit repeat + end repeat + end if + + if targetTab is missing value then + set targetTab to do script "${e}" + set custom title of targetTab to "${t}" + else + do script "${e}" in targetTab + set custom title of targetTab to "${t}" + end if +end tell +`.trim()}function jn(s,i){let e=ie(s),t=ie(zt(i)),n=ie(ze(i));return` +${Vt()} + +tell application "iTerm" + activate + set targetSession to missing value + set targetCwd to "${n}" + + repeat with terminalWindow in windows + repeat with terminalTab in tabs of terminalWindow + repeat with terminalSession in sessions of terminalTab + if (name of terminalSession is "${t}") and (is processing of terminalSession is false) then + set targetSession to terminalSession + exit repeat + end if + end repeat + if targetSession is not missing value then exit repeat + end repeat + if targetSession is not missing value then exit repeat + end repeat + + if targetSession is missing value then + repeat with terminalWindow in windows + repeat with terminalTab in tabs of terminalWindow + repeat with terminalSession in sessions of terminalTab + if (is processing of terminalSession is false) then + set sessionCwd to my promptuaryCwdForTty(tty of terminalSession) + if sessionCwd is targetCwd then + set targetSession to terminalSession + exit repeat + end if + end if + end repeat + if targetSession is not missing value then exit repeat + end repeat + if targetSession is not missing value then exit repeat + end repeat + end if + + if targetSession is missing value then + if (count of windows) is 0 then + set targetWindow to (create window with default profile) + else + set targetWindow to current window + tell targetWindow + create tab with default profile + end tell + end if + set targetSession to current session of targetWindow + end if + + tell targetSession + set name to "${t}" + write text "${e}" + end tell +end tell +`.trim()}function _n(s,i){return`cd ${pe(ze(i))} && ${pe(s)}`}function ie(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Vt(){return` +on promptuaryCwdForTty(tabTty) + if tabTty is missing value then return "" + set ttyText to tabTty as text + if ttyText is "" then return "" + if ttyText starts with "/dev/" then set ttyText to text 6 thru -1 of ttyText + set lookupCmd to "tty=" & quoted form of ttyText & "; pid=$(/bin/ps -t \\"$tty\\" -o pid= 2>/dev/null | /usr/bin/head -n 1 | /usr/bin/tr -d ' '); if [ -n \\"$pid\\" ]; then /usr/sbin/lsof -a -p \\"$pid\\" -d cwd -Fn 2>/dev/null | /usr/bin/sed -n 's/^n//p' | /usr/bin/head -n 1; fi" + try + return do shell script lookupCmd + on error + return "" + end try +end promptuaryCwdForTty +`.trim()}function zt(s){let i=ze(s),e=Gn(te.basename(i)||"Vault"),t=Lt.createHash("sha256").update(i).digest("hex").slice(0,12);return`${zn} - ${e} - ${t}`}function ze(s){let i=te.resolve(s);try{i=ee.realpathSync.native(i)}catch{}let e=te.parse(i);return i===e.root?i:i.replace(/[\\/]+$/,"")}function Gn(s){return s.replace(/\s+/g," ").trim()||"Vault"}var he=class{constructor(){this.status="idle";this.timeoutTimer=null;this.settleTimer=null;this.resolve=null;this.watchedAbsPath=null;this.unwatch=null;this.cleanup=()=>{this.timeoutTimer&&(window.clearTimeout(this.timeoutTimer),this.timeoutTimer=null),this.settleTimer&&(window.clearTimeout(this.settleTimer),this.settleTimer=null),this.unwatch&&(this.unwatch(),this.unwatch=null)}}startMonitor(i,e,t=5*60*1e3,n=1500){this.status="running";let r=i.vault.adapter.basePath??"",o=te.join(r,e);return this.watchedAbsPath=o,new Promise(l=>{this.resolve=l;let c=(p,m)=>{this.status==="running"&&(this.cleanup(),this.status=m,this.resolve=null,l(p))};this.timeoutTimer=window.setTimeout(()=>{c(!1,"timeout")},t);let d=(p,m)=>{this.status==="running"&&(p.mtimeMs===m.mtimeMs&&p.size===m.size||(this.settleTimer&&window.clearTimeout(this.settleTimer),this.settleTimer=window.setTimeout(()=>{c(!0,"detected")},n)))};ee.watchFile(o,{persistent:!1,interval:1e3},d),this.unwatch=()=>{try{ee.unwatchFile(o,d)}catch{}}})}cancel(){if(this.status==="running"){let i=this.resolve;this.cleanup(),this.status="idle",this.resolve=null,i?.(!1)}}getStatus(){return this.status}};var M=require("obsidian");var Wt={C:{bg:"rgba(167,139,250,0.10)",border:"rgba(167,139,250,0.20)",text:"rgba(167,139,250,0.90)"},O:{bg:"rgba(74,222,128,0.08)",border:"rgba(74,222,128,0.15)",text:"rgba(74,222,128,0.80)"},A:{bg:"rgba(96,165,250,0.08)",border:"rgba(96,165,250,0.15)",text:"rgba(96,165,250,0.80)"},G:{bg:"rgba(251,191,36,0.08)",border:"rgba(251,191,36,0.15)",text:"rgba(251,191,36,0.80)"}};function Kn(s){let i=s[0]?.toUpperCase()??"C";return Wt[i]??Wt.C}var We=class extends M.Modal{constructor(e,t,n,r){super(e);this.command=t;this.rule=n;this.instructionFile=r;this.resolve=null}openForConfirmation(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-confirm-modal");let t=Kn(this.rule.label),n=e.createDiv({cls:"prm-ccm-header"}),r=n.createDiv({cls:"prm-ccm-header-left"}),o=r.createDiv({cls:"prm-ccm-icon"});(0,M.setIcon)(o,"terminal");let l=r.createDiv();l.createDiv({cls:"prm-ccm-title",text:a("agent.confirm.title")}),l.createDiv({cls:"prm-ccm-subtitle",text:a("agent.confirm.subtitle",{label:this.rule.label})});let c=n.createEl("button",{cls:"prm-ccm-close"});(0,M.setIcon)(c,"x"),c.onclick=()=>{this.resolve?.(!1),this.close()};let d=e.createDiv({cls:"prm-ccm-agent-row"}),p=d.createDiv({cls:"prm-ccm-agent-avatar"});p.style.setProperty("--prm-color-bg",t.bg),p.style.setProperty("--prm-color-border",t.border),p.addClass("prm-dynamic-bg"),p.addClass("prm-dynamic-border-color");let m=p.createSpan({cls:"prm-ccm-agent-char",text:this.rule.label[0]});m.style.setProperty("--prm-color-text",t.text),m.addClass("prm-dynamic-text-color"),d.createSpan({cls:"prm-ccm-agent-name",text:this.rule.label});let u=d.createSpan({cls:"prm-ccm-agent-badge installed",text:a("agent.confirm.installed")});this.rule.vendor&&d.createSpan({cls:"prm-ccm-agent-vendor",text:`${this.rule.vendor}`});let h=e.createDiv({cls:"prm-ccm-cmd-wrap"}).createDiv({cls:"prm-ccm-cmd-box"});h.createDiv({cls:"prm-ccm-cmd-header"}).createSpan({cls:"prm-ccm-cmd-label",text:a("agent.confirm.commandLabel")}),h.createEl("code",{cls:"prm-ccm-code",text:this.command});let b=e.createDiv({cls:"prm-ccm-warning"}),A=b.createDiv({cls:"prm-ccm-warning-icon"});if((0,M.setIcon)(A,"alert-triangle"),b.createEl("p",{cls:"prm-ccm-warning-text",text:a("agent.confirm.warning")}),this.instructionFile){let re=e.createDiv({cls:"prm-ccm-hint"}),ct=re.createDiv({cls:"prm-ccm-hint-icon"});(0,M.setIcon)(ct,"file-text"),re.createSpan({cls:"prm-ccm-hint-text",text:a("agent.confirm.instructionFile",{path:this.instructionFile})})}let y=e.createDiv({cls:"prm-ccm-footer"}),v=y.createDiv({cls:"prm-ccm-footer-left"}).createEl("button",{cls:"prm-ccm-btn prm-ccm-btn-cancel"}),S=v.createSpan({cls:"prm-ccm-btn-inner"}),T=S.createSpan({cls:"prm-ccm-btn-icon"});(0,M.setIcon)(T,"x"),S.createSpan({text:a("agent.confirm.btn.cancel")}),v.onclick=()=>{this.resolve?.(!1),this.close()};let F=y.createDiv({cls:"prm-ccm-footer-right"}),R=F.createEl("button",{cls:"prm-ccm-btn prm-ccm-btn-copy"}),B=R.createSpan({cls:"prm-ccm-btn-inner"}),$=B.createSpan({cls:"prm-ccm-btn-icon"});(0,M.setIcon)($,"copy"),B.createSpan({text:a("agent.confirm.btn.copyCommand")}),R.onclick=()=>{O(this.command),new M.Notice(a("agent.confirm.notice.copied")),this.resolve?.(!1),this.close()};let j=F.createEl("button",{cls:"prm-ccm-btn prm-ccm-btn-exec"}),we=j.createSpan({cls:"prm-ccm-btn-inner"}),Ue=we.createSpan({cls:"prm-ccm-btn-icon"});(0,M.setIcon)(Ue,"play"),we.createSpan({text:a("agent.confirm.btn.execute")}),j.onclick=()=>{this.resolve?.(!0),this.close()}}onClose(){this.resolve?.(!1),this.resolve=null}};var fe=require("obsidian");var qt={C:{bg:"rgba(167,139,250,0.10)",border:"rgba(167,139,250,0.20)",text:"rgba(167,139,250,0.90)"},O:{bg:"rgba(74,222,128,0.08)",border:"rgba(74,222,128,0.15)",text:"rgba(74,222,128,0.80)"},A:{bg:"rgba(96,165,250,0.08)",border:"rgba(96,165,250,0.15)",text:"rgba(96,165,250,0.80)"},G:{bg:"rgba(251,191,36,0.08)",border:"rgba(251,191,36,0.15)",text:"rgba(251,191,36,0.80)"}};function Un(s){let i=s[0]?.toUpperCase()??"C";return qt[i]??qt.C}var qe=class extends fe.Modal{constructor(e,t){super(e);this.agents=t;this.selected=null;this.resolve=null}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-agent-select-modal");let t=e.createDiv({cls:"prm-asm-header"}),n=t.createDiv({cls:"prm-asm-header-left"}),r=n.createDiv({cls:"prm-asm-icon"});(0,fe.setIcon)(r,"bot");let o=n.createDiv();o.createDiv({cls:"prm-asm-title",text:a("agent.select.title")}),o.createDiv({cls:"prm-asm-subtitle",text:a("agent.select.subtitle")});let l=t.createEl("button",{cls:"prm-asm-close"});(0,fe.setIcon)(l,"x"),l.onclick=()=>{this.resolve?.({rule:null}),this.close()};let c=e.createDiv({cls:"prm-asm-list"}),d=this.agents.find(h=>h.installed);d&&(this.selected=d.rule);let p=new Map;for(let h of this.agents){let{rule:g,installed:b}=h,A=Un(g.label),y=this.selected?.id===g.id,C=c.createDiv({cls:"prm-asm-row"+(y?" active":"")+(b?"":" disabled")});p.set(g.id,C);let v=C.createDiv({cls:"prm-asm-avatar"});v.style.setProperty("--prm-color-bg",A.bg),v.style.setProperty("--prm-color-border",A.border),v.addClass("prm-dynamic-bg"),v.addClass("prm-dynamic-border-color"),v.createSpan({cls:"prm-asm-avatar-char",text:g.label[0]}),v.querySelector(".prm-asm-avatar-char").style.setProperty("--prm-color-text",A.text),v.querySelector(".prm-asm-avatar-char").addClass("prm-dynamic-text-color");let S=C.createDiv({cls:"prm-asm-info"}),T=S.createDiv({cls:"prm-asm-name-row"});T.createSpan({cls:"prm-asm-name",text:g.label});let F=T.createSpan({cls:"prm-asm-badge "+(b?"installed":"missing"),text:b?a("agent.select.installed"):a("agent.select.missing")});S.createDiv({cls:"prm-asm-meta",text:g.vendor?`${g.vendor} \xB7 ${g.installHint}`:g.installHint});let R=C.createDiv({cls:"prm-asm-radio"+(y?" selected":"")});y&&R.createDiv({cls:"prm-asm-radio-dot"}),b&&(C.onclick=()=>{this.selected=g;for(let[B,$]of p){$.removeClass("active");let j=$.querySelector(".prm-asm-radio");j?.removeClass("selected"),j?.querySelector(".prm-asm-radio-dot")?.remove()}C.addClass("active"),R.addClass("selected"),R.querySelector(".prm-asm-radio-dot")||R.createDiv({cls:"prm-asm-radio-dot"})})}let m=e.createDiv({cls:"prm-asm-footer"}),u=m.createEl("button",{cls:"prm-asm-config-btn",text:a("agent.select.addCustom")});u.onclick=()=>{let h=this.app;h.setting?.open(),h.setting?.openTabById?.("promptuary"),this.resolve?.({rule:null}),this.close()};let f=m.createEl("button",{cls:"prm-asm-confirm-btn",text:a("agent.select.btn.confirm")});f.onclick=()=>{this.resolve?.({rule:this.selected}),this.close()}}onClose(){this.resolve?.({rule:null}),this.resolve=null}};var E=require("obsidian");function q(){}q.prototype={diff:function(i,e){var t,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n=="function"&&(r=n,n={}),this.options=n;var o=this;function l(v){return r?(setTimeout(function(){r(void 0,v)},0),!0):v}i=this.castInput(i),e=this.castInput(e),i=this.removeEmpty(this.tokenize(i)),e=this.removeEmpty(this.tokenize(e));var c=e.length,d=i.length,p=1,m=c+d;n.maxEditLength&&(m=Math.min(m,n.maxEditLength));var u=(t=n.timeout)!==null&&t!==void 0?t:1/0,f=Date.now()+u,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],e,i,0);if(h[0].oldPos+1>=d&&g+1>=c)return l([{value:this.join(e),count:e.length}]);var b=-1/0,A=1/0;function y(){for(var v=Math.max(b,-p);v<=Math.min(A,p);v+=2){var S=void 0,T=h[v-1],F=h[v+1];T&&(h[v-1]=void 0);var R=!1;if(F){var B=F.oldPos-v;R=F&&0<=B&&B=d&&g+1>=c)return l(Jn(o,S.lastComponent,e,i,o.useLongestToken));h[v]=S,S.oldPos+1>=d&&(A=Math.min(A,v-1)),g+1>=c&&(b=Math.max(b,v+1))}p++}if(r)(function v(){setTimeout(function(){if(p>m||Date.now()>f)return r();y()||v()},0)})();else for(;p<=m&&Date.now()<=f;){var C=y();if(C)return C}},addToPath:function(i,e,t,n){var r=i.lastComponent;return r&&r.added===e&&r.removed===t?{oldPos:i.oldPos+n,lastComponent:{count:r.count+1,added:e,removed:t,previousComponent:r.previousComponent}}:{oldPos:i.oldPos+n,lastComponent:{count:1,added:e,removed:t,previousComponent:r}}},extractCommon:function(i,e,t,n){for(var r=e.length,o=t.length,l=i.oldPos,c=l-n,d=0;c+1g.length?A:g}),m.value=s.join(u)}else m.value=s.join(e.slice(d,d+m.count));d+=m.count,m.added||(p+=m.count)}}var h=r[c-1];return c>1&&typeof h.value=="string"&&(h.added||h.removed)&&s.equals("",h.value)&&(r[c-2].value+=h.value,r.pop()),r}var Vr=new q;var jt=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,_t=/\S/,Gt=new q;Gt.equals=function(s,i){return this.options.ignoreCase&&(s=s.toLowerCase(),i=i.toLowerCase()),s===i||this.options.ignoreWhitespace&&!_t.test(s)&&!_t.test(i)};Gt.tokenize=function(s){for(var i=s.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),e=0;e"u"?e:o}:t;return typeof s=="string"?s:JSON.stringify(ot(s,null,null,n),n," ")};ge.equals=function(s,i){return q.prototype.equals.call(ge,s.replace(/,([\r\n])/g,"$1"),i.replace(/,([\r\n])/g,"$1"))};function ot(s,i,e,t,n){i=i||[],e=e||[],t&&(s=t(n,s));var r;for(r=0;r0&&c[c.length-1]===""&&c.pop(),l.added)for(let d of c)t.push({index:o,type:"added",content:d,newLineNumber:r++}),o++;else if(l.removed)for(let d of c)t.push({index:o,type:"removed",content:d,oldLineNumber:n++}),o++;else for(let d of c)t.push({index:o,type:"unchanged",content:d,oldLineNumber:n++,newLineNumber:r++}),o++}return t}function Ut(s){let i=0,e=0;for(let t of s)t.type==="added"&&i++,t.type==="removed"&&e++;return{added:i,removed:e}}function Jt(s,i,e){let t=lt(s,""),n=[];for(let r of i){let o=e.get(r.index);switch(r.type){case"unchanged":n.push(r.content);break;case"removed":o===!0||n.push(r.content);break;case"added":o!==!1&&n.push(r.content);break}}return n.join(` `)+` -`}function Wn(s,i=2){let e=s.length,t=new Set;if(s.forEach((c,d)=>{c.type!=="unchanged"&&t.add(d)}),t.size===0)return[];let n=[],r=-1,o=-1,l=[...t].sort((c,d)=>c-d);for(let c of l){let d=Math.max(0,c-i),p=Math.min(e-1,c+i);r===-1?(r=d,o=p):d<=o+1?o=Math.max(o,p):(n.push({start:r,end:o}),r=d,o=p)}return r!==-1&&n.push({start:r,end:o}),n.map(({start:c,end:d})=>{let p=s.slice(c,d+1),m=p.filter(A=>A.type!=="unchanged").map(A=>A.index),u=p.find(A=>A.type==="removed"||A.type==="unchanged"),g=p.find(A=>A.type==="added"||A.type==="unchanged"),h=u?.oldLineNumber??p[0]?.oldLineNumber??1,f=g?.newLineNumber??p[0]?.newLineNumber??1,b=p.filter(A=>A.type!=="added").length,y=p.filter(A=>A.type!=="removed").length;return{header:`@@ -${h},${b} +${f},${y} @@`,blocks:p,changeIndices:m}})}var ue=class extends W.Modal{constructor(e,t,n,r){super(e);this.originalText=t;this.modifiedText=n;this.fileName=r;this.hunkDecisions=new Map;this.acceptMap=new Map;this.result=null;this.resolve=null;this.blocks=zt(t,n),this.hunks=Wn(this.blocks);for(let o of this.blocks)o.type!=="unchanged"&&this.acceptMap.set(o.index,!0)}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-diff-modal");let{added:t,removed:n}=qt(this.blocks),r=e.createDiv({cls:"prm-dm-header"}),o=r.createDiv({cls:"prm-dm-header-left"}),l=o.createDiv({cls:"prm-dm-icon"});(0,W.setIcon)(l,"git-compare-arrows");let c=o.createDiv();c.createDiv({cls:"prm-dm-title",text:a("diff.title")}),c.createDiv({cls:"prm-dm-subtitle",text:a("diff.subtitle",{file:this.fileName,n:this.hunks.length})});let d=r.createDiv({cls:"prm-dm-header-right"});d.createSpan({cls:"prm-dm-hunk-badge"}).setText(`${this.hunks.length} ${a("diff.hunks")}`);let m=d.createEl("button",{cls:"prm-dm-close"});(0,W.setIcon)(m,"x"),m.onclick=()=>{this.result={action:"reject"},this.close()};let u=e.createDiv({cls:"prm-dm-content"});this.hunks.length===0?u.createDiv({cls:"prm-dm-empty",text:a("diff.noChanges")}):this.hunks.forEach((S,A)=>{this.renderHunk(u,S,A)});let g=e.createDiv({cls:"prm-dm-footer"}),h=g.createDiv({cls:"prm-dm-stats"});h.createSpan({cls:"prm-dm-stat-label",text:a("diff.changesLabel")}),h.createSpan({cls:"prm-dm-stat-add",text:`+${t} lines`}),h.createSpan({cls:"prm-dm-stat-del",text:`-${n} lines`});let f=g.createDiv({cls:"prm-dm-btns"}),b=f.createEl("button",{cls:"prm-dm-btn-rollback"});(0,W.setIcon)(b,"rotate-ccw"),b.createSpan({text:a("diff.btn.rollbackAll")}),b.onclick=()=>{this.result={action:"reject"},this.close()};let y=f.createEl("button",{cls:"prm-dm-btn-accept"});(0,W.setIcon)(y,"check"),y.createSpan({text:a("diff.btn.applySelected")}),y.onclick=()=>{this.result=this.buildResultFromAcceptMap(),this.close()}}onClose(){this.resolve&&(this.result||(this.result=this.buildResultFromAcceptMap()),this.resolve(this.result),this.resolve=null)}buildResultFromAcceptMap(){let e=[...this.acceptMap.values()],t=e.every(o=>o);return e.every(o=>!o)?{action:"reject"}:t?{action:"accept-all"}:{action:"accept-partial",mergedText:Wt(this.originalText,this.blocks,this.acceptMap)}}renderHunk(e,t,n){let r=e.createDiv({cls:"prm-dm-hunk"}),o=r.createDiv({cls:"prm-dm-hunk-header"});o.createDiv({cls:"prm-dm-hunk-header-left"}).createSpan({cls:"prm-dm-hunk-pos",text:t.header});let c=o.createDiv({cls:"prm-dm-hunk-actions"}),d=c.createEl("button",{cls:"prm-dm-hunk-btn reject"});(0,W.setIcon)(d,"x"),d.createSpan({text:a("diff.btn.reject")});let p=c.createEl("button",{cls:"prm-dm-hunk-btn accept"});(0,W.setIcon)(p,"check"),p.createSpan({text:a("diff.btn.accept")}),p.onclick=()=>{t.changeIndices.forEach(u=>this.acceptMap.set(u,!0)),this.hunkDecisions.set(n,!0),r.addClass("prm-dm-hunk-decided"),window.setTimeout(()=>r.remove(),220)},d.onclick=()=>{t.changeIndices.forEach(u=>this.acceptMap.set(u,!1)),this.hunkDecisions.set(n,!1),r.addClass("prm-dm-hunk-decided"),window.setTimeout(()=>r.remove(),220)};let m=r.createDiv({cls:"prm-dm-lines"});for(let u of t.blocks){let g=m.createDiv({cls:"prm-dm-line prm-dm-line-"+u.type}),h=g.createSpan({cls:"prm-dm-linenum"}),f=u.type==="removed"?u.oldLineNumber:u.type==="added"?u.newLineNumber:u.oldLineNumber??"";h.setText(String(f??"")),g.createSpan({cls:"prm-dm-prefix"}).setText(u.type==="added"?"+":u.type==="removed"?"-":" "),g.createSpan({cls:"prm-dm-text",text:u.content})}}};ce();var D=require("obsidian");ce();var jt={A:{bg:"rgba(96,165,250,0.10)",border:"rgba(96,165,250,0.20)",text:"rgba(96,165,250,0.90)"},O:{bg:"rgba(74,222,128,0.08)",border:"rgba(74,222,128,0.15)",text:"rgba(74,222,128,0.80)"},D:{bg:"rgba(96,165,250,0.10)",border:"rgba(96,165,250,0.20)",text:"rgba(96,165,250,0.90)"},G:{bg:"rgba(251,191,36,0.08)",border:"rgba(251,191,36,0.15)",text:"rgba(251,191,36,0.80)"},C:{bg:"rgba(167,139,250,0.10)",border:"rgba(167,139,250,0.20)",text:"rgba(167,139,250,0.90)"}},jn={anthropic:"Anthropic (Claude)",openai:"OpenAI (GPT)",deepseek:"DeepSeek",gemini:"Google Gemini",custom:a("settings.api.provider.custom")};function _n(s){let i=s[0]?.toUpperCase()??"C";return jt[i]??jt.C}var qe=class extends D.Modal{constructor(e,t,n,r){super(e);this.config=t;this.estimatedTokens=n;this.reviewCount=r;this.resolve=null}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-api-confirm-modal");let t=_n(this.config.provider),n=jn[this.config.provider],r=this.config.model||E[this.config.provider].model,o=e.createDiv({cls:"prm-apm-header"}),l=o.createDiv({cls:"prm-apm-header-left"}),c=l.createDiv({cls:"prm-apm-icon"});(0,D.setIcon)(c,"zap");let d=l.createDiv();d.createDiv({cls:"prm-apm-title",text:a("api.execute.title")}),d.createDiv({cls:"prm-apm-subtitle",text:`${n} \xB7 ${a("api.execute.subtitle")}`});let p=o.createEl("button",{cls:"prm-apm-close"});(0,D.setIcon)(p,"x"),p.onclick=()=>{this.resolve?.({action:"cancel"}),this.close()};let m=e.createDiv({cls:"prm-apm-provider-row"}),u=m.createDiv({cls:"prm-apm-provider-avatar"});u.style.setProperty("--prm-color-bg",t.bg),u.style.setProperty("--prm-color-border",t.border),u.addClass("prm-dynamic-bg"),u.addClass("prm-dynamic-border-color");let g=u.createSpan({cls:"prm-apm-provider-char",text:n[0]});g.style.setProperty("--prm-color-text",t.text),g.addClass("prm-dynamic-text-color"),m.createSpan({cls:"prm-apm-provider-name",text:n});let h=m.createSpan({cls:"prm-apm-provider-badge",text:a("api.execute.provider")});h.style.setProperty("--prm-color-bg",t.bg),h.style.setProperty("--prm-color-border",t.border),h.style.setProperty("--prm-color-text",t.text),h.addClass("prm-dynamic-bg"),h.addClass("prm-dynamic-border-color"),h.addClass("prm-dynamic-text-color");let b=e.createDiv({cls:"prm-apm-info-wrap"}).createDiv({cls:"prm-apm-info-box"}),y=(j,he,_e=!1)=>{let te=b.createDiv({cls:"prm-apm-info-row"});return te.createSpan({cls:"prm-apm-info-label",text:j}),te.createSpan({cls:_e?"prm-apm-info-value prm-apm-info-warn":"prm-apm-info-value",text:he})};y(a("api.execute.model"),r),y(a("api.execute.reviews"),a("api.execute.reviewCount",{n:this.reviewCount})),y(a("api.execute.tokens"),`~${this.estimatedTokens.toLocaleString()}`,this.estimatedTokens>5e4);let S=e.createDiv({cls:"prm-apm-warning"}),A=S.createDiv({cls:"prm-apm-warning-icon"});(0,D.setIcon)(A,"alert-triangle"),S.createEl("p",{cls:"prm-apm-warning-text",text:a("api.execute.warning")});let v=e.createDiv({cls:"prm-apm-footer"}),C=v.createEl("button",{cls:"prm-apm-btn prm-apm-btn-cancel"}),P=C.createSpan({cls:"prm-apm-btn-inner"}),M=P.createSpan({cls:"prm-apm-btn-icon"});(0,D.setIcon)(M,"x"),P.createSpan({text:a("api.execute.btn.cancel")}),C.onclick=()=>{this.resolve?.({action:"cancel"}),this.close()};let T=v.createEl("button",{cls:"prm-apm-btn prm-apm-btn-exec"}),B=T.createSpan({cls:"prm-apm-btn-inner"}),O=B.createSpan({cls:"prm-apm-btn-icon"});(0,D.setIcon)(O,"send"),B.createSpan({text:a("api.execute.btn.confirm")}),T.onclick=()=>{this.resolve?.({action:"execute"}),this.close()}}onClose(){this.resolve?.({action:"cancel"}),this.resolve=null}},We=class extends D.Modal{constructor(e){super(e);this.state={phase:"calling"};this.resolve=null;this.modalEl.addEventListener("keydown",t=>{this.state.phase==="calling"&&t.key==="Escape"&&t.stopPropagation()},!0)}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-api-progress-modal");let n=e.createDiv({cls:"prm-ppm-header"}).createDiv({cls:"prm-ppm-header-left"}),r=n.createDiv({cls:"prm-ppm-icon"});(0,D.setIcon)(r,"zap");let o=n.createDiv();o.createDiv({cls:"prm-ppm-title",text:a("api.progress.title")}),o.createDiv({cls:"prm-ppm-subtitle",text:a("api.progress.subtitle")}),this.contentArea=e.createDiv({cls:"prm-ppm-content"});let c=e.createDiv({cls:"prm-ppm-footer"}).createDiv({cls:"prm-ppm-footer-right"}),d=c.createEl("button",{cls:"prm-ppm-btn prm-ppm-btn-close"});d.createSpan({cls:"prm-ppm-btn-inner"}).createSpan({text:a("api.progress.btn.close")}),d.onclick=()=>{this.resolve?.(null),this.close()},d.addClass("prm-hidden");let m=c.createEl("button",{cls:"prm-ppm-btn prm-ppm-btn-diff"}),u=m.createSpan({cls:"prm-ppm-btn-inner"}),g=u.createSpan({cls:"prm-ppm-btn-icon"});(0,D.setIcon)(g,"git-compare"),u.createSpan({text:a("api.progress.btn.viewDiff")}),m.onclick=()=>{this.resolve?.(this.state.phase==="done"?this.state.text:null),this.close()},m.addClass("prm-hidden"),this.render()}setState(e){this.state=e,this.render()}render(){let e=this.contentArea;e.empty();let t=this.modalEl.querySelector(".prm-ppm-footer-right"),n=t?.querySelector(".prm-ppm-btn-close"),r=t?.querySelector(".prm-ppm-btn-diff");if(n&&n.addClass("prm-hidden"),r&&r.addClass("prm-hidden"),this.state.phase==="calling"){e.createDiv({cls:"prm-ppm-spinner"}),e.createEl("p",{cls:"prm-ppm-calling-text",text:a("api.progress.calling")});return}if(this.state.phase==="error"){let c=e.createDiv({cls:"prm-ppm-error"}),d=c.createDiv({cls:"prm-ppm-error-icon"});(0,D.setIcon)(d,"x-circle"),c.createEl("p",{cls:"prm-ppm-error-text",text:a("api.progress.failed",{error:this.state.message})}),n&&n.removeClass("prm-hidden");return}let o=e.createDiv({cls:"prm-ppm-success"}),l=o.createDiv({cls:"prm-ppm-success-icon"});(0,D.setIcon)(l,"check-circle"),o.createEl("p",{cls:"prm-ppm-success-text",text:a("api.progress.success")}),r&&r.removeClass("prm-hidden")}onClose(){this.state.phase==="calling"&&new D.Notice(a("api.progress.cancelled")),this.resolve?.(null),this.resolve=null}};function _t(s){return btoa(Array.from(new TextEncoder().encode(s),i=>String.fromCodePoint(i)).join(""))}var je=class extends w.Plugin{constructor(){super(...arguments);this.settings=U;this.popover=null;this.toolbar=null;this.onSettingsChanged=null;this.agentCache=null;this.fileChangeMonitor=null;this.originalTextBeforeAgent=null;this.reviewIdsBeforeAgent=null;this.pendingReviewCleanup=new Map;this.logoUrl=`data:image/svg+xml;base64,${_t(ut)}`;this.emptyStateUrl=`data:image/svg+xml;base64,${_t(ht)}`;this.executionState=null;this.lastSelection=null;this.isDraggingSelection=!1}async onload(){await this.loadSettings(),ge(this.settings.language),ct(),this.store=new ve(this.app,()=>this.settings.sidecarDir),this.store.registerVaultEvents(),this.reviewExporter=new Ne(this.app,()=>this.settings.exportDir),this.promptExporter=new Le(this.app),this.commandRuleStore=new V,this.commandRuleStore.loadFromJSON(this.settings.customCommandRules),this.registerEditorExtension(Et()),this.registerView(L,e=>new Fe(e,this)),this.addRibbonIcon("highlighter",a("main.ribbonTooltip"),()=>{this.openSidebar()}),this.addCommand({id:"open-sidebar",name:a("main.cmd.openSidebar"),callback:()=>{this.openSidebar()}}),this.addSettingTab(new Me(this.app,this)),R()?this.toolbar=new Se(this.app,this.popoverCallbacks()):this.popover=new Ce(this.app,this.popoverCallbacks()),this.registerDomEvent(activeDocument,"selectionchange",()=>this.onSelectionChange()),this.registerDomEvent(activeDocument,"mousedown",e=>{let t=e.target;t&&(t.closest(".promptuary-popover")||t.closest(".cm-editor")&&(this.isDraggingSelection=!0,this.popover?.hide()))}),this.registerDomEvent(activeDocument,"mouseup",()=>{this.isDraggingSelection&&(this.isDraggingSelection=!1,window.setTimeout(()=>this.onSelectionChange(),0))}),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>{this.refreshDecorations()})),this.registerEvent(this.app.workspace.on("file-open",()=>{this.refreshDecorations()})),this.store.on("change",e=>{this.app.workspace.getActiveViewOfType(w.MarkdownView)?.file?.path===e&&this.refreshDecorations()}),this.addCommand({id:"highlight-yellow",name:a("main.cmd.highlightYellow"),editorCheckCallback:(e,t,n)=>n.file?(e||this.createHighlightFromSelection("yellow"),!0):!1}),this.addCommand({id:"create-note",name:a("main.cmd.addNote"),editorCheckCallback:(e,t,n)=>n.file?(e||this.openNoteModalForSelection(),!0):!1}),this.addCommand({id:"create-review",name:a("main.cmd.addReview"),editorCheckCallback:(e,t,n)=>n.file?(e||this.openReviewModalForSelection(),!0):!1}),this.addCommand({id:"export-review",name:a("main.cmd.exportReview"),callback:()=>{this.runExport()}}),this.addCommand({id:"copy-prompt",name:a("main.cmd.copyPrompt"),callback:()=>{this.runCopyPrompt()}}),this.registerAgentCommands(),this.addCommand({id:"api-execute",name:a("main.cmd.apiExecute"),callback:()=>{this.runAPIExecute()}}),this.app.workspace.onLayoutReady(()=>{this.app.workspace.getLeavesOfType(L).length===0?this.openSidebar():this.refreshDecorations()})}onunload(){this.store.flushAll(),this.store.destroy(),this.popover?.destroy(),this.toolbar?.destroy(),this.fileChangeMonitor?.cancel()}async loadSettings(){this.settings=Object.assign({},U,await this.loadData()),["Promptuary/exports","MultiAIEdit/exports",".multiaiedit/exports"].includes(this.settings.exportDir)&&(this.settings.exportDir=U.exportDir,await this.saveSettings()),this.settings.sidecarDir===".multiaiedit/annotations"&&(this.settings.sidecarDir=U.sidecarDir,await this.saveSettings())}async saveSettings(){await this.saveData(this.settings),this.onSettingsChanged?.()}registerAgentCommands(){for(let e of G)this.addCommand({id:`agent-${e.id}`,name:a("main.cmd.runAgent",{label:e.label}),callback:()=>{this.runAgent(e.id)}});this.addCommand({id:"copy-agent",name:a("main.cmd.copyAgentCommand"),callback:()=>{this.runCopyAgentCommand()}})}getAgentInfo(){return this.agentCache||(this.agentCache=Te(this.commandRuleStore.allRules())),this.agentCache}invalidateAgentCache(){this.agentCache=null}async runAPIExecute(){let e=this.resolveTargetMarkdownPath();if(!e){new w.Notice(a("main.notice.openMdFile"));return}let t=this.settings.apiSettings;if(!t.apiKey){new w.Notice(a("main.notice.configureAPIKey"));return}await this.store.flushAll();let n=await this.store.getFile(e),r=n.annotations.filter(A=>A.type==="review");if(r.length===0){new w.Notice(a("main.notice.noReviewAnnotations"));return}let o=this.app.vault.getAbstractFileByPath(e);if(!(o instanceof w.TFile)){new w.Notice(a("export.notice.fileNotFound"));return}let l=await this.app.vault.read(o),c=o.basename,d=tt(c,e,n,{includeReadingNotes:this.settings.includeReadingNotesInExport}),p=Qe(l,d),m=He(Ie+p),u={provider:t.provider,apiKey:t.apiKey,model:t.model,customEndpoint:t.customEndpoint,maxTokens:t.maxTokens};if((await new qe(this.app,u,m,r.length).openForResult()).action!=="execute")return;let h=new We(this.app),f=h.openForResult();h.setState({phase:"calling"});let b=await Xe(u,{systemPrompt:Ie,userMessage:p});if(!b.success||!b.text){h.setState({phase:"error",message:b.error??a("common.error")}),await f;return}h.setState({phase:"done",text:b.text});let y=await f;if(!y)return;if(l===y){new w.Notice(a("main.notice.noChangesNeeded"));return}let S=await new ue(this.app,l,y,c).openForResult();switch(S.action){case"accept-all":{await this.app.vault.modify(o,y),await this.reanchorAndConfirm(e,l,y),new w.Notice(a("main.notice.allAccepted"));break}case"accept-partial":{S.mergedText!==void 0&&(await this.app.vault.modify(o,S.mergedText),await this.reanchorAndConfirm(e,l,S.mergedText),new w.Notice(a("main.notice.selectedApplied")));break}case"reject":{new w.Notice(a("main.notice.cancelledNoChange"));break}}}async runAgent(e){if(R()){new w.Notice(a("main.notice.mobileNoAgent"));return}let t=this.commandRuleStore.getById(e);if(!t){new w.Notice(a("main.notice.ruleNotFound",{id:e}));return}let n=this.resolveTargetMarkdownPath();if(!n){new w.Notice(a("main.notice.openMdFile"));return}await this.store.flushAll();let r=await this.store.getFile(n),o=r.annotations.filter(S=>S.type==="review");if(o.length===0){new w.Notice(a("main.notice.noReviewAnnotations"));return}let l=this.app.vault.getAbstractFileByPath(n);if(!(l instanceof w.TFile)){new w.Notice(a("export.notice.fileNotFound"));return}let c=await this.app.vault.read(l),d=l.basename,p=`${this.settings.exportDir}/${d}-agent-instruction.md`,m=this.app.vault.adapter.basePath??this.app.vault.getRoot().path,u=`${m}/${n}`,g=Be(d,u,r,{includeReadingNotes:this.settings.includeReadingNotesInExport}),h=this.app.vault.adapter;await h.exists(this.settings.exportDir)||await h.mkdir(this.settings.exportDir),await h.write(p,g);let f={vaultPath:m,instructionFile:p,filePath:n,fileName:l.name,prompt:g},b=nt(t,f);await new $e(this.app,b,t,p).openForConfirmation()&&(this.originalTextBeforeAgent=c,this.reviewIdsBeforeAgent={filePath:n,ids:o.map(S=>S.id)},Lt({command:b,vaultPath:m,terminalApp:this.settings.terminalApp,onLaunched:()=>{this.startFileMonitoring(n)},onCopied:()=>{this.startFileMonitoring(n)}}))}async runAgentWithSelect(){if(R()){new w.Notice(a("main.notice.mobileNoAgent"));return}let e=this.getAgentInfo(),{rule:t}=await new Ve(this.app,e).openForResult();t&&await this.runAgent(t.id)}async runCopyAgentCommand(){if(!this.resolveTargetMarkdownPath()){new w.Notice(a("main.notice.openMdFile"));return}let n=this.getAgentInfo().filter(r=>r.installed);if(n.length===0){new w.Notice(a("main.notice.noAgentCLI"));return}if(n.length===1){await this.buildAndCopyCommand(n[0].rule);return}await this.buildAndCopyCommand(n[0].rule)}async buildAndCopyCommand(e){let t=this.resolveTargetMarkdownPath();if(!t)return;await this.store.flushAll();let n=await this.store.getFile(t),r=this.app.vault.getAbstractFileByPath(t);if(!(r instanceof w.TFile))return;let o=r.basename,l=this.app.vault.adapter.basePath??this.app.vault.getRoot().path,c=`${l}/${t}`,d=`${this.settings.exportDir}/${o}-agent-instruction.md`,p=Be(o,c,n,{includeReadingNotes:this.settings.includeReadingNotesInExport}),m=this.app.vault.adapter;await m.exists(this.settings.exportDir)||await m.mkdir(this.settings.exportDir),await m.write(d,p);let u={vaultPath:l,instructionFile:d,filePath:t,fileName:r.name,prompt:p},g=nt(e,u);H(g),new w.Notice(a("main.notice.commandCopied",{label:e.label}))}startFileMonitoring(e){this.fileChangeMonitor?.cancel(),this.fileChangeMonitor=new de,new w.Notice(a("main.notice.monitoringChanges")),(async()=>{let n=new de;if(this.fileChangeMonitor=n,!await n.startMonitor(this.app,e)){new w.Notice(a("main.notice.monitorTimeout")),this.fileChangeMonitor=null;return}new w.Notice(a("main.notice.changeDetected")),await this.showDiffForFile(e),this.fileChangeMonitor=null})()}async showDiffForFile(e){let t=this.app.vault.getAbstractFileByPath(e);if(!(t instanceof w.TFile))return;let n=this.originalTextBeforeAgent;if(!n){new w.Notice(a("main.notice.noOriginalSnapshot"));return}let r=await this.app.vault.read(t);if(n===r){new w.Notice(a("main.notice.noChangesDetected"));return}let o=t.basename,l=await new ue(this.app,n,r,o).openForResult();switch(l.action){case"accept-all":{let c=r;await this.reanchorAndConfirm(e,n,c),this.originalTextBeforeAgent=null,new w.Notice(a("main.notice.allAccepted"));break}case"accept-partial":{if(l.mergedText!==void 0){await this.app.vault.modify(t,l.mergedText);let c=l.mergedText;await this.reanchorAndConfirm(e,n,c),this.originalTextBeforeAgent=null,new w.Notice(a("main.notice.selectedApplied"))}break}case"reject":{await this.app.vault.modify(t,n),this.originalTextBeforeAgent=null,this.reviewIdsBeforeAgent=null,this.refreshDecorations(),new w.Notice(a("main.notice.allRolledBack"));break}}}onModeChange(e){let t=this.app.workspace.getLeavesOfType(L);if(t.length>0&&t[0].view.setModeExternal(e),this.popover?.setMode(e),this.toolbar?.setMode(e),this.lastSelection){let{cm:n,from:r,to:o}=this.lastSelection;try{n.dispatch({selection:{anchor:r,head:o}}),n.focus()}catch{this.lastSelection=null,this.popover?.hide();return}this.popover&&this.popover.show(n,r,o),this.toolbar&&this.toolbar.show()}}currentMode(){let e=this.app.workspace.getLeavesOfType(L);return e.length===0?this.settings.defaultMode:e[0].view.getMode()}async reanchorAndConfirm(e,t,n){let r=await this.store.getFile(e),o=St(t,n,r.annotations,this.settings.contextSpan),l=0,c=0,d=0;for(let u of o){let g=r.annotations.find(h=>h.id===u.id);if(g){if(u.status==="healed"&&Object.keys(u.patch).length>0)await this.store.updateAnnotation(e,u.id,u.patch),l++;else if(u.status==="drifted"){if(g.type==="review"){await this.store.removeAnnotation(e,u.id),c++;continue}let h=be(n,g);if(h.status==="auto-healed"&&h.from!==void 0&&h.to!==void 0){let f=this.settings.contextSpan,b=Math.max(0,h.from-f),y=Math.min(n.length,h.to+f),S=n.slice(h.from,h.to),A=n.slice(b,h.from),v=n.slice(h.to,y),C=Q(n,h.from),P=X(n,S,h.from);await this.store.updateAnnotation(e,u.id,{selectedText:S,contextBefore:A,contextAfter:v,lineHint:C,occurrenceIndex:P}),l++}else await this.store.removeAnnotation(e,u.id),d++}}}let p=await re(n);await this.store.confirmBaseline(e,p),this.refreshDecorations();let m=[];l>0&&m.push(a("main.notice.autoHealed",{n:l})),c>0&&m.push(a("main.notice.reviewExecuted",{n:c})),d>0&&m.push(a("main.notice.invalidReadingRemoved",{n:d})),m.length>0&&new w.Notice(m.join("\uFF0C")),await this.promptReviewCleanupForAgent(e)}async promptReviewCleanupForAgent(e){if(!this.reviewIdsBeforeAgent||this.reviewIdsBeforeAgent.filePath!==e)return;let t=new Set(this.reviewIdsBeforeAgent.ids);this.reviewIdsBeforeAgent=null;let r=(await this.store.getFile(e)).annotations.filter(o=>o.type==="review"&&t.has(o.id)).map(o=>o.id);r.length!==0&&(this.pendingReviewCleanup.set(e,{ids:r,count:r.length}),this.refreshSidebarViews(e))}getPendingReviewCleanup(e){return this.pendingReviewCleanup.get(e)??null}async cleanupProcessedReviews(e){let t=this.pendingReviewCleanup.get(e);if(!t)return;let n=await this.store.getFile(e),r=new Set(n.annotations.map(l=>l.id)),o=0;for(let l of t.ids)r.has(l)&&(await this.store.removeAnnotation(e,l),o++);this.pendingReviewCleanup.delete(e),this.refreshDecorations(),this.refreshSidebarViews(e),o>0&&new w.Notice(a("main.notice.reviewCleanupDone",{n:o}))}dismissReviewCleanup(e){this.pendingReviewCleanup.delete(e),this.refreshSidebarViews(e)}refreshSidebarViews(e){let t=this.app.workspace.getLeavesOfType(L);for(let n of t){let r=n.view;r.getCurrentFilePath()===e&&r.refresh()}}onSelectionChange(){if(this.isDraggingSelection||this.popover?.isEditing)return;let e=this.app.workspace.getActiveViewOfType(w.MarkdownView);if(!e)return;let t=e.editor,n=t.getSelection();if(!n||n.length===0){this.lastSelection=null,this.popover?.hide();return}let r=t.cm;if(!r)return;let o=r.state.selection.main;if(o.from===o.to)return;this.lastSelection={cm:r,from:o.from,to:o.to};let l=this.currentMode();this.popover&&(this.popover.setMode(l),this.popover.show(r,o.from,o.to)),this.toolbar&&(this.toolbar.setMode(l),this.toolbar.show())}popoverCallbacks(){let e=()=>{let t=this.app.workspace.getActiveViewOfType(w.MarkdownView);if(!t)return;let n=t.editor.cm;if(!n)return;let r=n.state.selection.main.head;n.dispatch({selection:{anchor:r}})};return{onHighlight:(t,n)=>{if(n){let r=this.findAnnotationFilePath(n);r&&this.store.updateAnnotation(r,n,{type:"highlight",highlightColor:t,reviewText:void 0,strike:void 0}),this.refreshDecorations(),this.lastSelection=null,e()}else this.createHighlightFromSelection(t).then(()=>{this.lastSelection=null,e()})},onNote:(t,n,r)=>{if(r){let o=this.findAnnotationFilePath(r);o&&this.store.updateAnnotation(o,r,{type:"note",noteText:t,highlightColor:n,reviewText:void 0,strike:void 0}),this.refreshDecorations(),this.lastSelection=null,e()}else this.createNoteFromSelection(t,n).then(()=>{this.lastSelection=null,e()})},onReview:(t,n,r)=>{if(r){let o=this.findAnnotationFilePath(r);if(o){let l={type:"review",strike:n,noteText:void 0,highlightColor:void 0};t&&(l.reviewText=t),this.store.updateAnnotation(o,r,l)}this.refreshDecorations(),this.lastSelection=null,e()}else this.createReviewFromSelection(t,n).then(()=>{this.lastSelection=null,e()})},onStrikeCreate:async()=>{this.lastSelection=null;let t=this.getActiveSelectionContext();if(!t)return"";let r={...await this.buildAnchor(t.file,t.doc,t.from,t.to,t.selectedText),type:"review",reviewText:void 0,strike:!0};return await this.store.addAnnotation(t.file.path,r),this.refreshDecorations(),r.id},onStrikeRemove:t=>{this.lastSelection=null;let n=this.findAnnotationFilePath(t);n&&(this.store.removeAnnotation(n,t),this.refreshDecorations())},onModeSwitch:t=>{this.onModeChange(t)}}}findAnnotationFilePath(e){let t=this.resolveTargetMarkdownPath();return t||null}getActiveSelectionContext(){let e=this.app.workspace.getActiveViewOfType(w.MarkdownView);if(!e||!e.file)return null;let t=e.editor.cm;if(!t)return null;let n=t.state.selection.main;if(n.from===n.to)return null;let r=t.state.doc.toString(),o=r.slice(n.from,n.to);return{view:e,file:e.file,editor:e.editor,cm:t,from:n.from,to:n.to,selectedText:o,doc:r}}async buildAnchor(e,t,n,r,o){let l=this.settings.contextSpan,{contextBefore:c,contextAfter:d}=yt(t,n,r,l),p=Q(t,n),m=X(t,o,n),u=await re(t),g=Date.now();return{id:gt(),filePath:e.path,selectedText:o,contextBefore:c,contextAfter:d,lineHint:p,occurrenceIndex:m,baselineHash:u,createdAt:g,updatedAt:g}}async createHighlightFromSelection(e){let t=this.getActiveSelectionContext();if(!t)return;let r={...await this.buildAnchor(t.file,t.doc,t.from,t.to,t.selectedText),type:"highlight",highlightColor:e};await this.store.addAnnotation(t.file.path,r),this.refreshDecorations()}async openNoteModalForSelection(){let e=this.getActiveSelectionContext();if(!e){new w.Notice(a("main.notice.selectTextFirst"));return}let t=await this.buildAnchor(e.file,e.doc,e.from,e.to,e.selectedText);new se(this.app,"",n=>{let r={...t,type:"note",noteText:n};this.store.addAnnotation(e.file.path,r).then(()=>this.refreshDecorations())}).open()}async createNoteFromSelection(e,t){let n=this.getActiveSelectionContext();if(!n){new w.Notice(a("main.notice.selectTextFirst"));return}let o={...await this.buildAnchor(n.file,n.doc,n.from,n.to,n.selectedText),type:"note",noteText:e,highlightColor:t};await this.store.addAnnotation(n.file.path,o),this.refreshDecorations()}async openReviewModalForSelection(){let e=this.getActiveSelectionContext();if(!e){new w.Notice(a("main.notice.selectReviewTextFirst"));return}let t=await this.buildAnchor(e.file,e.doc,e.from,e.to,e.selectedText);new ae(this.app,{},(n,r)=>{let o={...t,type:"review",reviewText:n||void 0,strike:r};this.store.addAnnotation(e.file.path,o).then(()=>this.refreshDecorations())}).open()}async createReviewFromSelection(e,t){let n=this.getActiveSelectionContext();if(!n){new w.Notice(a("main.notice.selectReviewTextFirst"));return}let o={...await this.buildAnchor(n.file,n.doc,n.from,n.to,n.selectedText),type:"review",reviewText:e||void 0,strike:t};await this.store.addAnnotation(n.file.path,o),this.refreshDecorations()}async editAnnotation(e){if(e.type==="note")new se(this.app,e.noteText??"",t=>{this.store.updateAnnotation(e.filePath,e.id,{noteText:t})}).open();else if(e.type==="review")new ae(this.app,{text:e.reviewText??"",strike:e.strike,isEdit:!0},(t,n)=>{this.store.updateAnnotation(e.filePath,e.id,{reviewText:t||void 0,strike:n})}).open();else if(e.type==="highlight"){let t=["yellow","blue","green","purple"],n=t[(t.indexOf(e.highlightColor??"yellow")+1)%t.length];await this.store.updateAnnotation(e.filePath,e.id,{highlightColor:n})}}async deleteAnnotation(e){await this.store.removeAnnotation(e.filePath,e.id),this.refreshDecorations()}async refreshDecorations(){let e=this.app.workspace.getLeavesOfType("markdown");for(let t of e){let n=t.view;if(!n?.file)continue;let r=n.editor.cm;if(!r)continue;let o=await this.store.getFile(n.file.path);r.dispatch({effects:oe.of(o.annotations)})}}async runExport(e){let t=e??this.resolveTargetMarkdownPath();if(!t){new w.Notice(a("main.notice.openMdFile"));return}await this.store.flushAll();let n=await this.store.getFile(t);if(n.annotations.filter(l=>l.type==="review").length===0){new w.Notice(a("main.notice.noReviewAnnotations"));return}let o=await this.reviewExporter.exportToVault(t,n,{includeReadingNotes:this.settings.includeReadingNotesInExport});if(o){new w.Notice(a("main.notice.exportSuccess",{target:o}));let l=await Nt(this.app,o);l.success||new w.Notice(a("folder.notice.openFailed",{error:l.error??""}))}else new w.Notice(a("main.notice.exportFailed"))}async runCopyPrompt(e){let t=e??this.resolveTargetMarkdownPath();if(!t){new w.Notice(a("main.notice.openMdFile"));return}await this.store.flushAll();let n=await this.store.getFile(t);await this.promptExporter.copyToClipboard(t,n,{includeReadingNotes:this.settings.includeReadingNotesInExport})}resolveTargetMarkdownPath(){let e=this.app.workspace.getActiveViewOfType(w.MarkdownView);if(e?.file)return e.file.path;let t=this.app.workspace.getLeavesOfType(L);if(t.length>0){let o=t[0].view.getCurrentFilePath();if(o)return o}let n=this.app.workspace.getLeavesOfType("markdown");for(let r of n){let o=r.view;if(o?.file)return o.file.path}return null}async openSidebar(){let e=this.app.workspace.getLeavesOfType(L)[0];if(!e){let t=this.app.workspace.getRightLeaf(!1);t&&(await t.setViewState({type:L,active:!0}),e=t)}if(e){let t=this.app.workspace;typeof t.revealLeaf=="function"?await t.revealLeaf(e):this.app.workspace.setActiveLeaf(e,{focus:!0})}}}; +`}function ei(s,i=2){let e=s.length,t=new Set;if(s.forEach((c,d)=>{c.type!=="unchanged"&&t.add(d)}),t.size===0)return[];let n=[],r=-1,o=-1,l=[...t].sort((c,d)=>c-d);for(let c of l){let d=Math.max(0,c-i),p=Math.min(e-1,c+i);r===-1?(r=d,o=p):d<=o+1?o=Math.max(o,p):(n.push({start:r,end:o}),r=d,o=p)}return r!==-1&&n.push({start:r,end:o}),n.map(({start:c,end:d})=>{let p=s.slice(c,d+1),m=p.filter(C=>C.type!=="unchanged").map(C=>C.index),u=p.find(C=>C.type==="removed"||C.type==="unchanged"),f=p.find(C=>C.type==="added"||C.type==="unchanged"),h=u?.oldLineNumber??p[0]?.oldLineNumber??1,g=f?.newLineNumber??p[0]?.newLineNumber??1,b=p.filter(C=>C.type!=="added").length,A=p.filter(C=>C.type!=="removed").length;return{header:`@@ -${h},${b} +${g},${A} @@`,blocks:p,changeIndices:m}})}var ve=class extends E.Modal{constructor(e,t,n,r,o={}){super(e);this.originalText=t;this.modifiedText=n;this.fileName=r;this.options=o;this.blocks=[];this.hunks=[];this.hunkDecisions=new Map;this.acceptMap=new Map;this.result=null;this.resolve=null;this.resetDiff(n)}resetDiff(e){this.modifiedText=e,this.blocks=Kt(this.originalText,e),this.hunks=ei(this.blocks).filter(t=>t.changeIndices.length>0),this.acceptMap.clear(),this.hunkDecisions.clear();for(let t of this.blocks)t.type!=="unchanged"&&this.acceptMap.set(t.index,!0)}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-diff-modal");let{added:t,removed:n}=Ut(this.blocks),r=e.createDiv({cls:"prm-dm-header"}),o=r.createDiv({cls:"prm-dm-header-left"}),l=o.createDiv({cls:"prm-dm-icon"});(0,E.setIcon)(l,"git-compare-arrows");let c=o.createDiv();c.createDiv({cls:"prm-dm-title",text:a("diff.title")}),c.createDiv({cls:"prm-dm-subtitle",text:a("diff.subtitle",{file:this.fileName,n:this.hunks.length})});let d=r.createDiv({cls:"prm-dm-header-right"});if(d.createSpan({cls:"prm-dm-hunk-badge"}).setText(`${this.hunks.length} ${a("diff.hunks")}`),this.options.reloadModifiedText){let y=d.createEl("button",{cls:"prm-dm-refresh"});y.title=a("diff.btn.refresh"),y.setAttribute("aria-label",a("diff.btn.refresh")),(0,E.setIcon)(y,"refresh-cw"),y.createSpan({text:a("diff.btn.refresh")}),y.onclick=()=>{this.refreshDiff(y)}}let m=d.createEl("button",{cls:"prm-dm-close"});m.title=a("common.close"),(0,E.setIcon)(m,"x"),m.onclick=()=>{this.result={action:"reject"},this.close()};let u=e.createDiv({cls:"prm-dm-content"});this.hunks.length===0?u.createDiv({cls:"prm-dm-empty",text:a("diff.noChanges")}):this.hunks.forEach((y,C)=>{this.renderHunk(u,y,C)});let f=e.createDiv({cls:"prm-dm-footer"}),h=f.createDiv({cls:"prm-dm-stats"});h.createSpan({cls:"prm-dm-stat-label",text:a("diff.changesLabel")}),h.createSpan({cls:"prm-dm-stat-add",text:`+${t} lines`}),h.createSpan({cls:"prm-dm-stat-del",text:`-${n} lines`});let g=f.createDiv({cls:"prm-dm-btns"}),b=g.createEl("button",{cls:"prm-dm-btn-rollback"});(0,E.setIcon)(b,"rotate-ccw"),b.createSpan({text:a("diff.btn.rollbackAll")}),b.onclick=()=>{this.result={action:"reject"},this.close()};let A=g.createEl("button",{cls:"prm-dm-btn-accept"});(0,E.setIcon)(A,"check"),A.createSpan({text:a("diff.btn.applySelected")}),A.onclick=()=>{this.applySelected()}}onClose(){this.resolve&&(this.result||(this.result={action:"reject"}),this.resolve(this.result),this.resolve=null)}buildResultFromAcceptMap(){if(this.acceptMap.size===0)return{action:"reject"};let e=[...this.acceptMap.values()],t=e.every(o=>o);return e.every(o=>!o)?{action:"reject"}:t?{action:"accept-all",mergedText:this.modifiedText}:{action:"accept-partial",mergedText:Jt(this.originalText,this.blocks,this.acceptMap)}}async refreshDiff(e){if(this.options.reloadModifiedText){e.disabled=!0,e.addClass("is-loading");try{let t=await this.options.reloadModifiedText();this.result=null,this.resetDiff(t),this.onOpen(),new E.Notice(a("diff.notice.refreshed"))}catch{e.disabled=!1,e.removeClass("is-loading"),new E.Notice(a("diff.notice.refreshFailed"))}}}async applySelected(){if(this.options.reloadModifiedText)try{let e=await this.options.reloadModifiedText();if(e!==this.modifiedText){this.result=null,this.resetDiff(e),this.onOpen(),new E.Notice(a("diff.notice.changedBeforeApply"));return}}catch{new E.Notice(a("diff.notice.refreshFailed"));return}this.result=this.buildResultFromAcceptMap(),this.close()}renderHunk(e,t,n){let r=e.createDiv({cls:"prm-dm-hunk"}),o=r.createDiv({cls:"prm-dm-hunk-header"});o.createDiv({cls:"prm-dm-hunk-header-left"}).createSpan({cls:"prm-dm-hunk-pos",text:t.header});let c=o.createDiv({cls:"prm-dm-hunk-actions"}),d=c.createEl("button",{cls:"prm-dm-hunk-btn reject"});(0,E.setIcon)(d,"x"),d.createSpan({text:a("diff.btn.reject")});let p=c.createEl("button",{cls:"prm-dm-hunk-btn accept"});(0,E.setIcon)(p,"check"),p.createSpan({text:a("diff.btn.accept")}),p.onclick=()=>{t.changeIndices.forEach(u=>this.acceptMap.set(u,!0)),this.hunkDecisions.set(n,!0),r.addClass("prm-dm-hunk-decided"),window.setTimeout(()=>r.remove(),220)},d.onclick=()=>{t.changeIndices.forEach(u=>this.acceptMap.set(u,!1)),this.hunkDecisions.set(n,!1),r.addClass("prm-dm-hunk-decided"),window.setTimeout(()=>r.remove(),220)};let m=r.createDiv({cls:"prm-dm-lines"});for(let u of t.blocks){let f=m.createDiv({cls:"prm-dm-line prm-dm-line-"+u.type}),h=f.createSpan({cls:"prm-dm-linenum"}),g=u.type==="removed"?u.oldLineNumber:u.type==="added"?u.newLineNumber:u.oldLineNumber??"";h.setText(String(g??"")),f.createSpan({cls:"prm-dm-prefix"}).setText(u.type==="added"?"+":u.type==="removed"?"-":" "),f.createSpan({cls:"prm-dm-text",text:u.content})}}};ue();var D=require("obsidian");ue();var Yt={A:{bg:"rgba(96,165,250,0.10)",border:"rgba(96,165,250,0.20)",text:"rgba(96,165,250,0.90)"},O:{bg:"rgba(74,222,128,0.08)",border:"rgba(74,222,128,0.15)",text:"rgba(74,222,128,0.80)"},D:{bg:"rgba(96,165,250,0.10)",border:"rgba(96,165,250,0.20)",text:"rgba(96,165,250,0.90)"},G:{bg:"rgba(251,191,36,0.08)",border:"rgba(251,191,36,0.15)",text:"rgba(251,191,36,0.80)"},C:{bg:"rgba(167,139,250,0.10)",border:"rgba(167,139,250,0.20)",text:"rgba(167,139,250,0.90)"}},ti={anthropic:"Anthropic (Claude)",openai:"OpenAI (GPT)",deepseek:"DeepSeek",gemini:"Google Gemini",custom:a("settings.api.provider.custom")};function ni(s){let i=s[0]?.toUpperCase()??"C";return Yt[i]??Yt.C}var _e=class extends D.Modal{constructor(e,t,n,r){super(e);this.config=t;this.estimatedTokens=n;this.reviewCount=r;this.resolve=null}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-api-confirm-modal");let t=ni(this.config.provider),n=ti[this.config.provider],r=this.config.model||P[this.config.provider].model,o=e.createDiv({cls:"prm-apm-header"}),l=o.createDiv({cls:"prm-apm-header-left"}),c=l.createDiv({cls:"prm-apm-icon"});(0,D.setIcon)(c,"zap");let d=l.createDiv();d.createDiv({cls:"prm-apm-title",text:a("api.execute.title")}),d.createDiv({cls:"prm-apm-subtitle",text:`${n} \xB7 ${a("api.execute.subtitle")}`});let p=o.createEl("button",{cls:"prm-apm-close"});(0,D.setIcon)(p,"x"),p.onclick=()=>{this.resolve?.({action:"cancel"}),this.close()};let m=e.createDiv({cls:"prm-apm-provider-row"}),u=m.createDiv({cls:"prm-apm-provider-avatar"});u.style.setProperty("--prm-color-bg",t.bg),u.style.setProperty("--prm-color-border",t.border),u.addClass("prm-dynamic-bg"),u.addClass("prm-dynamic-border-color");let f=u.createSpan({cls:"prm-apm-provider-char",text:n[0]});f.style.setProperty("--prm-color-text",t.text),f.addClass("prm-dynamic-text-color"),m.createSpan({cls:"prm-apm-provider-name",text:n});let h=m.createSpan({cls:"prm-apm-provider-badge",text:a("api.execute.provider")});h.style.setProperty("--prm-color-bg",t.bg),h.style.setProperty("--prm-color-border",t.border),h.style.setProperty("--prm-color-text",t.text),h.addClass("prm-dynamic-bg"),h.addClass("prm-dynamic-border-color"),h.addClass("prm-dynamic-text-color");let b=e.createDiv({cls:"prm-apm-info-wrap"}).createDiv({cls:"prm-apm-info-box"}),A=(j,we,Ue=!1)=>{let re=b.createDiv({cls:"prm-apm-info-row"});return re.createSpan({cls:"prm-apm-info-label",text:j}),re.createSpan({cls:Ue?"prm-apm-info-value prm-apm-info-warn":"prm-apm-info-value",text:we})};A(a("api.execute.model"),r),A(a("api.execute.reviews"),a("api.execute.reviewCount",{n:this.reviewCount})),A(a("api.execute.tokens"),`~${this.estimatedTokens.toLocaleString()}`,this.estimatedTokens>5e4);let y=e.createDiv({cls:"prm-apm-warning"}),C=y.createDiv({cls:"prm-apm-warning-icon"});(0,D.setIcon)(C,"alert-triangle"),y.createEl("p",{cls:"prm-apm-warning-text",text:a("api.execute.warning")});let v=e.createDiv({cls:"prm-apm-footer"}),S=v.createEl("button",{cls:"prm-apm-btn prm-apm-btn-cancel"}),T=S.createSpan({cls:"prm-apm-btn-inner"}),F=T.createSpan({cls:"prm-apm-btn-icon"});(0,D.setIcon)(F,"x"),T.createSpan({text:a("api.execute.btn.cancel")}),S.onclick=()=>{this.resolve?.({action:"cancel"}),this.close()};let R=v.createEl("button",{cls:"prm-apm-btn prm-apm-btn-exec"}),B=R.createSpan({cls:"prm-apm-btn-inner"}),$=B.createSpan({cls:"prm-apm-btn-icon"});(0,D.setIcon)($,"send"),B.createSpan({text:a("api.execute.btn.confirm")}),R.onclick=()=>{this.resolve?.({action:"execute"}),this.close()}}onClose(){this.resolve?.({action:"cancel"}),this.resolve=null}},Ge=class extends D.Modal{constructor(e){super(e);this.state={phase:"calling"};this.resolve=null;this.modalEl.addEventListener("keydown",t=>{this.state.phase==="calling"&&t.key==="Escape"&&t.stopPropagation()},!0)}openForResult(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{modalEl:e}=this;e.empty(),e.addClass("prm-api-progress-modal");let n=e.createDiv({cls:"prm-ppm-header"}).createDiv({cls:"prm-ppm-header-left"}),r=n.createDiv({cls:"prm-ppm-icon"});(0,D.setIcon)(r,"zap");let o=n.createDiv();o.createDiv({cls:"prm-ppm-title",text:a("api.progress.title")}),o.createDiv({cls:"prm-ppm-subtitle",text:a("api.progress.subtitle")}),this.contentArea=e.createDiv({cls:"prm-ppm-content"});let c=e.createDiv({cls:"prm-ppm-footer"}).createDiv({cls:"prm-ppm-footer-right"}),d=c.createEl("button",{cls:"prm-ppm-btn prm-ppm-btn-close"});d.createSpan({cls:"prm-ppm-btn-inner"}).createSpan({text:a("api.progress.btn.close")}),d.onclick=()=>{this.resolve?.(null),this.close()},d.addClass("prm-hidden");let m=c.createEl("button",{cls:"prm-ppm-btn prm-ppm-btn-diff"}),u=m.createSpan({cls:"prm-ppm-btn-inner"}),f=u.createSpan({cls:"prm-ppm-btn-icon"});(0,D.setIcon)(f,"git-compare"),u.createSpan({text:a("api.progress.btn.viewDiff")}),m.onclick=()=>{this.resolve?.(this.state.phase==="done"?this.state.text:null),this.close()},m.addClass("prm-hidden"),this.render()}setState(e){this.state=e,this.render()}render(){let e=this.contentArea;e.empty();let t=this.modalEl.querySelector(".prm-ppm-footer-right"),n=t?.querySelector(".prm-ppm-btn-close"),r=t?.querySelector(".prm-ppm-btn-diff");if(n&&n.addClass("prm-hidden"),r&&r.addClass("prm-hidden"),this.state.phase==="calling"){e.createDiv({cls:"prm-ppm-spinner"}),e.createEl("p",{cls:"prm-ppm-calling-text",text:a("api.progress.calling")});return}if(this.state.phase==="error"){let c=e.createDiv({cls:"prm-ppm-error"}),d=c.createDiv({cls:"prm-ppm-error-icon"});(0,D.setIcon)(d,"x-circle"),c.createEl("p",{cls:"prm-ppm-error-text",text:a("api.progress.failed",{error:this.state.message})}),n&&n.removeClass("prm-hidden");return}let o=e.createDiv({cls:"prm-ppm-success"}),l=o.createDiv({cls:"prm-ppm-success-icon"});(0,D.setIcon)(l,"check-circle"),o.createEl("p",{cls:"prm-ppm-success-text",text:a("api.progress.success")}),r&&r.removeClass("prm-hidden")}onClose(){this.state.phase==="calling"&&new D.Notice(a("api.progress.cancelled")),this.resolve?.(null),this.resolve=null}};function Zt(s){return btoa(Array.from(new TextEncoder().encode(s),i=>String.fromCodePoint(i)).join(""))}var Ke=class extends w.Plugin{constructor(){super(...arguments);this.settings=U;this.popover=null;this.toolbar=null;this.onSettingsChanged=null;this.agentCache=null;this.fileChangeMonitor=null;this.originalTextBeforeAgent=null;this.reviewIdsBeforeAgent=null;this.pendingReviewCleanup=new Map;this.logoUrl=`data:image/svg+xml;base64,${Zt(ft)}`;this.emptyStateUrl=`data:image/svg+xml;base64,${Zt(gt)}`;this.executionState=null;this.lastSelection=null;this.isDraggingSelection=!1}async onload(){await this.loadSettings(),be(this.settings.language),pt(),this.store=new ye(this.app,()=>this.settings.sidecarDir),this.store.registerVaultEvents(),this.reviewExporter=new He(this.app,()=>this.settings.exportDir),this.promptExporter=new Oe(this.app),this.commandRuleStore=new z,this.commandRuleStore.loadFromJSON(this.settings.customCommandRules),this.registerEditorExtension(Dt()),this.registerView(H,e=>new Le(e,this)),this.addRibbonIcon("highlighter",a("main.ribbonTooltip"),()=>{this.openSidebar()}),this.addCommand({id:"open-sidebar",name:a("main.cmd.openSidebar"),callback:()=>{this.openSidebar()}}),this.addSettingTab(new Ne(this.app,this)),I()?this.toolbar=new Ee(this.app,this.popoverCallbacks()):this.popover=new Pe(this.app,this.popoverCallbacks()),this.registerDomEvent(activeDocument,"selectionchange",()=>this.onSelectionChange()),this.registerDomEvent(activeDocument,"mousedown",e=>{let t=e.target;t&&(t.closest(".promptuary-popover")||t.closest(".cm-editor")&&(this.isDraggingSelection=!0,this.popover?.hide()))}),this.registerDomEvent(activeDocument,"mouseup",()=>{this.isDraggingSelection&&(this.isDraggingSelection=!1,window.setTimeout(()=>this.onSelectionChange(),0))}),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>{this.refreshDecorations()})),this.registerEvent(this.app.workspace.on("file-open",()=>{this.refreshDecorations()})),this.store.on("change",e=>{this.app.workspace.getActiveViewOfType(w.MarkdownView)?.file?.path===e&&this.refreshDecorations()}),this.addCommand({id:"highlight-yellow",name:a("main.cmd.highlightYellow"),editorCheckCallback:(e,t,n)=>n.file?(e||this.createHighlightFromSelection("yellow"),!0):!1}),this.addCommand({id:"create-note",name:a("main.cmd.addNote"),editorCheckCallback:(e,t,n)=>n.file?(e||this.openNoteModalForSelection(),!0):!1}),this.addCommand({id:"create-review",name:a("main.cmd.addReview"),editorCheckCallback:(e,t,n)=>n.file?(e||this.openReviewModalForSelection(),!0):!1}),this.addCommand({id:"export-review",name:a("main.cmd.exportReview"),callback:()=>{this.runExport()}}),this.addCommand({id:"copy-prompt",name:a("main.cmd.copyPrompt"),callback:()=>{this.runCopyPrompt()}}),this.registerAgentCommands(),this.addCommand({id:"api-execute",name:a("main.cmd.apiExecute"),callback:()=>{this.runAPIExecute()}}),this.app.workspace.onLayoutReady(()=>{this.app.workspace.getLeavesOfType(H).length===0?this.openSidebar():this.refreshDecorations()})}onunload(){this.store.flushAll(),this.store.destroy(),this.popover?.destroy(),this.toolbar?.destroy(),this.fileChangeMonitor?.cancel()}async loadSettings(){this.settings=Object.assign({},U,await this.loadData()),["Promptuary/exports","MultiAIEdit/exports",".multiaiedit/exports"].includes(this.settings.exportDir)&&(this.settings.exportDir=U.exportDir,await this.saveSettings()),this.settings.sidecarDir===".multiaiedit/annotations"&&(this.settings.sidecarDir=U.sidecarDir,await this.saveSettings())}async saveSettings(){await this.saveData(this.settings),this.onSettingsChanged?.()}registerAgentCommands(){for(let e of K)this.addCommand({id:`agent-${e.id}`,name:a("main.cmd.runAgent",{label:e.label}),callback:()=>{this.runAgent(e.id)}});this.addCommand({id:"copy-agent",name:a("main.cmd.copyAgentCommand"),callback:()=>{this.runCopyAgentCommand()}})}getAgentInfo(){return this.agentCache||(this.agentCache=Ie(this.commandRuleStore.allRules())),this.agentCache}invalidateAgentCache(){this.agentCache=null}async runAPIExecute(){let e=this.resolveTargetMarkdownPath();if(!e){new w.Notice(a("main.notice.openMdFile"));return}let t=this.settings.apiSettings;if(!t.apiKey){new w.Notice(a("main.notice.configureAPIKey"));return}await this.store.flushAll();let n=await this.store.getFile(e),r=n.annotations.filter(C=>C.type==="review");if(r.length===0){new w.Notice(a("main.notice.noReviewAnnotations"));return}let o=this.app.vault.getAbstractFileByPath(e);if(!(o instanceof w.TFile)){new w.Notice(a("export.notice.fileNotFound"));return}let l=await this.app.vault.read(o),c=o.basename,d=it(c,e,n,{includeReadingNotes:this.settings.includeReadingNotesInExport}),p=tt(l,d),m=Be(Fe+p),u={provider:t.provider,apiKey:t.apiKey,model:t.model,customEndpoint:t.customEndpoint,maxTokens:t.maxTokens};if((await new _e(this.app,u,m,r.length).openForResult()).action!=="execute")return;let h=new Ge(this.app),g=h.openForResult();h.setState({phase:"calling"});let b=await et(u,{systemPrompt:Fe,userMessage:p});if(!b.success||!b.text){h.setState({phase:"error",message:b.error??a("common.error")}),await g;return}h.setState({phase:"done",text:b.text});let A=await g;if(!A)return;if(l===A){new w.Notice(a("main.notice.noChangesNeeded"));return}let y=await new ve(this.app,l,A,c).openForResult();switch(y.action){case"accept-all":{let C=y.mergedText??A;await this.app.vault.modify(o,C),await this.reanchorAndConfirm(e,l,C),new w.Notice(a("main.notice.allAccepted"));break}case"accept-partial":{y.mergedText!==void 0&&(await this.app.vault.modify(o,y.mergedText),await this.reanchorAndConfirm(e,l,y.mergedText),new w.Notice(a("main.notice.selectedApplied")));break}case"reject":{new w.Notice(a("main.notice.cancelledNoChange"));break}}}async runAgent(e){if(I()){new w.Notice(a("main.notice.mobileNoAgent"));return}let t=this.commandRuleStore.getById(e);if(!t){new w.Notice(a("main.notice.ruleNotFound",{id:e}));return}let n=this.resolveTargetMarkdownPath();if(!n){new w.Notice(a("main.notice.openMdFile"));return}await this.store.flushAll();let r=await this.store.getFile(n),o=r.annotations.filter(y=>y.type==="review");if(o.length===0){new w.Notice(a("main.notice.noReviewAnnotations"));return}let l=this.app.vault.getAbstractFileByPath(n);if(!(l instanceof w.TFile)){new w.Notice(a("export.notice.fileNotFound"));return}let c=await this.app.vault.read(l),d=l.basename,p=`${this.settings.exportDir}/${d}-agent-instruction.md`,m=this.app.vault.adapter.basePath??this.app.vault.getRoot().path,u=`${m}/${n}`,f=$e(d,u,r,{includeReadingNotes:this.settings.includeReadingNotesInExport}),h=this.app.vault.adapter;await h.exists(this.settings.exportDir)||await h.mkdir(this.settings.exportDir),await h.write(p,f);let g={vaultPath:m,instructionFile:p,filePath:n,fileName:l.name,prompt:f},b=rt(t,g);await new We(this.app,b,t,p).openForConfirmation()&&(this.originalTextBeforeAgent=c,this.reviewIdsBeforeAgent={filePath:n,ids:o.map(y=>y.id)},$t({command:b,vaultPath:m,terminalApp:this.settings.terminalApp,onLaunched:()=>{this.startFileMonitoring(n)},onCopied:()=>{this.startFileMonitoring(n)}}))}async runAgentWithSelect(){if(I()){new w.Notice(a("main.notice.mobileNoAgent"));return}let e=this.getAgentInfo(),{rule:t}=await new qe(this.app,e).openForResult();t&&await this.runAgent(t.id)}async runCopyAgentCommand(){if(!this.resolveTargetMarkdownPath()){new w.Notice(a("main.notice.openMdFile"));return}let n=this.getAgentInfo().filter(r=>r.installed);if(n.length===0){new w.Notice(a("main.notice.noAgentCLI"));return}if(n.length===1){await this.buildAndCopyCommand(n[0].rule);return}await this.buildAndCopyCommand(n[0].rule)}async buildAndCopyCommand(e){let t=this.resolveTargetMarkdownPath();if(!t)return;await this.store.flushAll();let n=await this.store.getFile(t),r=this.app.vault.getAbstractFileByPath(t);if(!(r instanceof w.TFile))return;let o=r.basename,l=this.app.vault.adapter.basePath??this.app.vault.getRoot().path,c=`${l}/${t}`,d=`${this.settings.exportDir}/${o}-agent-instruction.md`,p=$e(o,c,n,{includeReadingNotes:this.settings.includeReadingNotesInExport}),m=this.app.vault.adapter;await m.exists(this.settings.exportDir)||await m.mkdir(this.settings.exportDir),await m.write(d,p);let u={vaultPath:l,instructionFile:d,filePath:t,fileName:r.name,prompt:p},f=rt(e,u);O(f),new w.Notice(a("main.notice.commandCopied",{label:e.label}))}startFileMonitoring(e){this.fileChangeMonitor?.cancel(),this.fileChangeMonitor=new he,new w.Notice(a("main.notice.monitoringChanges")),(async()=>{let n=new he;if(this.fileChangeMonitor=n,!await n.startMonitor(this.app,e)){new w.Notice(a("main.notice.monitorTimeout")),this.fileChangeMonitor=null;return}new w.Notice(a("main.notice.changeDetected")),await this.showDiffForFile(e),this.fileChangeMonitor=null})()}async showDiffForFile(e){let t=this.app.vault.getAbstractFileByPath(e);if(!(t instanceof w.TFile))return;let n=this.originalTextBeforeAgent;if(!n){new w.Notice(a("main.notice.noOriginalSnapshot"));return}let r=await this.app.vault.read(t);if(n===r){new w.Notice(a("main.notice.noChangesDetected"));return}let o=t.basename,l=await new ve(this.app,n,r,o,{reloadModifiedText:()=>this.app.vault.read(t)}).openForResult();switch(l.action){case"accept-all":{let c=l.mergedText??r;await this.reanchorAndConfirm(e,n,c),this.originalTextBeforeAgent=null,new w.Notice(a("main.notice.allAccepted"));break}case"accept-partial":{if(l.mergedText!==void 0){await this.app.vault.modify(t,l.mergedText);let c=l.mergedText;await this.reanchorAndConfirm(e,n,c),this.originalTextBeforeAgent=null,new w.Notice(a("main.notice.selectedApplied"))}break}case"reject":{await this.app.vault.modify(t,n),this.originalTextBeforeAgent=null,this.reviewIdsBeforeAgent=null,this.refreshDecorations(),new w.Notice(a("main.notice.allRolledBack"));break}}}onModeChange(e){let t=this.app.workspace.getLeavesOfType(H);if(t.length>0&&t[0].view.setModeExternal(e),this.popover?.setMode(e),this.toolbar?.setMode(e),this.lastSelection){let{cm:n,from:r,to:o}=this.lastSelection;try{n.dispatch({selection:{anchor:r,head:o}}),n.focus()}catch{this.lastSelection=null,this.popover?.hide();return}this.popover&&this.popover.show(n,r,o),this.toolbar&&this.toolbar.show()}}currentMode(){let e=this.app.workspace.getLeavesOfType(H);return e.length===0?this.settings.defaultMode:e[0].view.getMode()}async reanchorAndConfirm(e,t,n){let r=await this.store.getFile(e),o=Tt(t,n,r.annotations,this.settings.contextSpan),l=0,c=0,d=0;for(let u of o){let f=r.annotations.find(h=>h.id===u.id);if(f){if(u.status==="healed"&&Object.keys(u.patch).length>0)await this.store.updateAnnotation(e,u.id,u.patch),l++;else if(u.status==="drifted"){if(f.type==="review"){await this.store.removeAnnotation(e,u.id),c++;continue}let h=Ce(n,f);if(h.status==="auto-healed"&&h.from!==void 0&&h.to!==void 0){let g=this.settings.contextSpan,b=Math.max(0,h.from-g),A=Math.min(n.length,h.to+g),y=n.slice(h.from,h.to),C=n.slice(b,h.from),v=n.slice(h.to,A),S=Q(n,h.from),T=X(n,y,h.from);await this.store.updateAnnotation(e,u.id,{selectedText:y,contextBefore:C,contextAfter:v,lineHint:S,occurrenceIndex:T}),l++}else await this.store.removeAnnotation(e,u.id),d++}}}let p=await ae(n);await this.store.confirmBaseline(e,p),this.refreshDecorations();let m=[];l>0&&m.push(a("main.notice.autoHealed",{n:l})),c>0&&m.push(a("main.notice.reviewExecuted",{n:c})),d>0&&m.push(a("main.notice.invalidReadingRemoved",{n:d})),m.length>0&&new w.Notice(m.join("\uFF0C")),await this.promptReviewCleanupForAgent(e)}async promptReviewCleanupForAgent(e){if(!this.reviewIdsBeforeAgent||this.reviewIdsBeforeAgent.filePath!==e)return;let t=new Set(this.reviewIdsBeforeAgent.ids);this.reviewIdsBeforeAgent=null;let r=(await this.store.getFile(e)).annotations.filter(o=>o.type==="review"&&t.has(o.id)).map(o=>o.id);r.length!==0&&(this.pendingReviewCleanup.set(e,{ids:r,count:r.length}),this.refreshSidebarViews(e))}getPendingReviewCleanup(e){return this.pendingReviewCleanup.get(e)??null}async cleanupProcessedReviews(e){let t=this.pendingReviewCleanup.get(e);if(!t)return;let n=await this.store.getFile(e),r=new Set(n.annotations.map(l=>l.id)),o=0;for(let l of t.ids)r.has(l)&&(await this.store.removeAnnotation(e,l),o++);this.pendingReviewCleanup.delete(e),this.refreshDecorations(),this.refreshSidebarViews(e),o>0&&new w.Notice(a("main.notice.reviewCleanupDone",{n:o}))}dismissReviewCleanup(e){this.pendingReviewCleanup.delete(e),this.refreshSidebarViews(e)}refreshSidebarViews(e){let t=this.app.workspace.getLeavesOfType(H);for(let n of t){let r=n.view;r.getCurrentFilePath()===e&&r.refresh()}}onSelectionChange(){if(this.isDraggingSelection||this.popover?.isEditing)return;let e=this.app.workspace.getActiveViewOfType(w.MarkdownView);if(!e)return;let t=e.editor,n=t.getSelection();if(!n||n.length===0){this.lastSelection=null,this.popover?.hide();return}let r=t.cm;if(!r)return;let o=r.state.selection.main;if(o.from===o.to)return;this.lastSelection={cm:r,from:o.from,to:o.to};let l=this.currentMode();this.popover&&(this.popover.setMode(l),this.popover.show(r,o.from,o.to)),this.toolbar&&(this.toolbar.setMode(l),this.toolbar.show())}popoverCallbacks(){let e=()=>{let t=this.app.workspace.getActiveViewOfType(w.MarkdownView);if(!t)return;let n=t.editor.cm;if(!n)return;let r=n.state.selection.main.head;n.dispatch({selection:{anchor:r}})};return{onHighlight:(t,n)=>{if(n){let r=this.findAnnotationFilePath(n);r&&this.store.updateAnnotation(r,n,{type:"highlight",highlightColor:t,reviewText:void 0,strike:void 0}),this.refreshDecorations(),this.lastSelection=null,e()}else this.createHighlightFromSelection(t).then(()=>{this.lastSelection=null,e()})},onNote:(t,n,r)=>{if(r){let o=this.findAnnotationFilePath(r);o&&this.store.updateAnnotation(o,r,{type:"note",noteText:t,highlightColor:n,reviewText:void 0,strike:void 0}),this.refreshDecorations(),this.lastSelection=null,e()}else this.createNoteFromSelection(t,n).then(()=>{this.lastSelection=null,e()})},onReview:(t,n,r)=>{if(r){let o=this.findAnnotationFilePath(r);if(o){let l={type:"review",strike:n,noteText:void 0,highlightColor:void 0};t&&(l.reviewText=t),this.store.updateAnnotation(o,r,l)}this.refreshDecorations(),this.lastSelection=null,e()}else this.createReviewFromSelection(t,n).then(()=>{this.lastSelection=null,e()})},onStrikeCreate:async()=>{this.lastSelection=null;let t=this.getActiveSelectionContext();if(!t)return"";let r={...await this.buildAnchor(t.file,t.doc,t.from,t.to,t.selectedText),type:"review",reviewText:void 0,strike:!0};return await this.store.addAnnotation(t.file.path,r),this.refreshDecorations(),r.id},onStrikeRemove:t=>{this.lastSelection=null;let n=this.findAnnotationFilePath(t);n&&(this.store.removeAnnotation(n,t),this.refreshDecorations())},onModeSwitch:t=>{this.onModeChange(t)}}}findAnnotationFilePath(e){let t=this.resolveTargetMarkdownPath();return t||null}getActiveSelectionContext(){let e=this.app.workspace.getActiveViewOfType(w.MarkdownView);if(!e||!e.file)return null;let t=e.editor.cm;if(!t)return null;let n=t.state.selection.main;if(n.from===n.to)return null;let r=t.state.doc.toString(),o=r.slice(n.from,n.to);return{view:e,file:e.file,editor:e.editor,cm:t,from:n.from,to:n.to,selectedText:o,doc:r}}async buildAnchor(e,t,n,r,o){let l=this.settings.contextSpan,{contextBefore:c,contextAfter:d}=Ct(t,n,r,l),p=Q(t,n),m=X(t,o,n),u=await ae(t),f=Date.now();return{id:vt(),filePath:e.path,selectedText:o,contextBefore:c,contextAfter:d,lineHint:p,occurrenceIndex:m,baselineHash:u,createdAt:f,updatedAt:f}}async createHighlightFromSelection(e){let t=this.getActiveSelectionContext();if(!t)return;let r={...await this.buildAnchor(t.file,t.doc,t.from,t.to,t.selectedText),type:"highlight",highlightColor:e};await this.store.addAnnotation(t.file.path,r),this.refreshDecorations()}async openNoteModalForSelection(){let e=this.getActiveSelectionContext();if(!e){new w.Notice(a("main.notice.selectTextFirst"));return}let t=await this.buildAnchor(e.file,e.doc,e.from,e.to,e.selectedText);new ce(this.app,"",n=>{let r={...t,type:"note",noteText:n};this.store.addAnnotation(e.file.path,r).then(()=>this.refreshDecorations())}).open()}async createNoteFromSelection(e,t){let n=this.getActiveSelectionContext();if(!n){new w.Notice(a("main.notice.selectTextFirst"));return}let o={...await this.buildAnchor(n.file,n.doc,n.from,n.to,n.selectedText),type:"note",noteText:e,highlightColor:t};await this.store.addAnnotation(n.file.path,o),this.refreshDecorations()}async openReviewModalForSelection(){let e=this.getActiveSelectionContext();if(!e){new w.Notice(a("main.notice.selectReviewTextFirst"));return}let t=await this.buildAnchor(e.file,e.doc,e.from,e.to,e.selectedText);new de(this.app,{},(n,r)=>{let o={...t,type:"review",reviewText:n||void 0,strike:r};this.store.addAnnotation(e.file.path,o).then(()=>this.refreshDecorations())}).open()}async createReviewFromSelection(e,t){let n=this.getActiveSelectionContext();if(!n){new w.Notice(a("main.notice.selectReviewTextFirst"));return}let o={...await this.buildAnchor(n.file,n.doc,n.from,n.to,n.selectedText),type:"review",reviewText:e||void 0,strike:t};await this.store.addAnnotation(n.file.path,o),this.refreshDecorations()}async editAnnotation(e){if(e.type==="note")new ce(this.app,e.noteText??"",t=>{this.store.updateAnnotation(e.filePath,e.id,{noteText:t})}).open();else if(e.type==="review")new de(this.app,{text:e.reviewText??"",strike:e.strike,isEdit:!0},(t,n)=>{this.store.updateAnnotation(e.filePath,e.id,{reviewText:t||void 0,strike:n})}).open();else if(e.type==="highlight"){let t=["yellow","blue","green","purple"],n=t[(t.indexOf(e.highlightColor??"yellow")+1)%t.length];await this.store.updateAnnotation(e.filePath,e.id,{highlightColor:n})}}async deleteAnnotation(e){await this.store.removeAnnotation(e.filePath,e.id),this.refreshDecorations()}async refreshDecorations(){let e=this.app.workspace.getLeavesOfType("markdown");for(let t of e){let n=t.view;if(!n?.file)continue;let r=n.editor.cm;if(!r)continue;let o=await this.store.getFile(n.file.path);r.dispatch({effects:le.of(o.annotations)})}}async runExport(e){let t=e??this.resolveTargetMarkdownPath();if(!t){new w.Notice(a("main.notice.openMdFile"));return}await this.store.flushAll();let n=await this.store.getFile(t);if(n.annotations.filter(l=>l.type==="review").length===0){new w.Notice(a("main.notice.noReviewAnnotations"));return}let o=await this.reviewExporter.exportToVault(t,n,{includeReadingNotes:this.settings.includeReadingNotesInExport});if(o){new w.Notice(a("main.notice.exportSuccess",{target:o}));let l=await Bt(this.app,o);l.success||new w.Notice(a("folder.notice.openFailed",{error:l.error??""}))}else new w.Notice(a("main.notice.exportFailed"))}async runCopyPrompt(e){let t=e??this.resolveTargetMarkdownPath();if(!t){new w.Notice(a("main.notice.openMdFile"));return}await this.store.flushAll();let n=await this.store.getFile(t);await this.promptExporter.copyToClipboard(t,n,{includeReadingNotes:this.settings.includeReadingNotesInExport})}resolveTargetMarkdownPath(){let e=this.app.workspace.getActiveViewOfType(w.MarkdownView);if(e?.file)return e.file.path;let t=this.app.workspace.getLeavesOfType(H);if(t.length>0){let o=t[0].view.getCurrentFilePath();if(o)return o}let n=this.app.workspace.getLeavesOfType("markdown");for(let r of n){let o=r.view;if(o?.file)return o.file.path}return null}async openSidebar(){let e=this.app.workspace.getLeavesOfType(H)[0];if(!e){let t=this.app.workspace.getRightLeaf(!1);t&&(await t.setViewState({type:H,active:!0}),e=t)}if(e){let t=this.app.workspace;typeof t.revealLeaf=="function"?await t.revealLeaf(e):this.app.workspace.setActiveLeaf(e,{focus:!0})}}}; diff --git a/src/agent/TerminalLauncher.ts b/src/agent/TerminalLauncher.ts index f2197e2..cac87b6 100644 --- a/src/agent/TerminalLauncher.ts +++ b/src/agent/TerminalLauncher.ts @@ -2,9 +2,11 @@ import { App, Notice } from "obsidian"; import { isMobile } from "../utils/platform"; import { copyToClipboard } from "../export/Exporters"; import { t } from "../i18n/i18n"; -import { execSync, fs, os, nodePath } from "../utils/nodeApi"; +import { execFileSync, fs, os, nodePath, nodeCrypto } from "../utils/nodeApi"; +import { shellEscape } from "../utils/shellescape"; export type TerminalApp = "Terminal" | "iTerm2"; +const AGENT_TERMINAL_TITLE_PREFIX = "Promptuary Agent"; export interface LaunchOptions { command: string; @@ -49,23 +51,21 @@ export function launchInTerminal(opts: LaunchOptions): void { function launchMacOS(opts: LaunchOptions): void { // Write the command to a temp shell script to avoid all AppleScript quoting issues. - // The script path is safe ASCII — no special chars to escape. + // The script path is safe ASCII - no special chars to escape. const tmpScript = nodePath.join(os.tmpdir(), `prm-agent-${Date.now()}.sh`); fs.writeFileSync(tmpScript, `#!/bin/bash\n${opts.command}\n`, { mode: 0o755 }); // Schedule cleanup after 60 s (well after execution starts) window.setTimeout(() => { try { fs.unlinkSync(tmpScript); } catch { /* ignore */ } }, 60_000); - let appleScript: string; - - if (opts.terminalApp === "iTerm2") { - appleScript = `tell application "iTerm"\nactivate\ncreate window with default profile command "${tmpScript}"\nend tell`; - } else { - appleScript = `tell application "Terminal"\ndo script "${tmpScript}"\nactivate\nend tell`; - } + const terminalCommand = buildTerminalSessionCommand(tmpScript, opts.vaultPath); + const appleScript = opts.terminalApp === "iTerm2" + ? buildITermAppleScript(terminalCommand, opts.vaultPath) + : buildTerminalAppleScript(terminalCommand, opts.vaultPath); try { - execSync(`osascript -e '${appleScript}'`, { + execFileSync("osascript", [], { + input: appleScript, encoding: "utf-8", timeout: 10_000, stdio: "pipe", @@ -79,15 +79,184 @@ function launchMacOS(opts: LaunchOptions): void { } } +function buildTerminalAppleScript(command: string, vaultPath: string): string { + const commandText = escapeAppleScriptString(command); + const sessionTitle = escapeAppleScriptString(buildAgentTerminalTitle(vaultPath)); + const targetCwd = escapeAppleScriptString(normalizeVaultPath(vaultPath)); + + return ` +${buildCwdLookupAppleScriptHandler()} + +tell application "Terminal" + activate + set targetTab to missing value + set targetCwd to "${targetCwd}" + + repeat with terminalWindow in windows + repeat with terminalTab in tabs of terminalWindow + if (custom title of terminalTab is "${sessionTitle}") and (busy of terminalTab is false) then + set targetTab to terminalTab + set index of terminalWindow to 1 + set selected of terminalTab to true + exit repeat + end if + end repeat + if targetTab is not missing value then exit repeat + end repeat + + if targetTab is missing value then + repeat with terminalWindow in windows + repeat with terminalTab in tabs of terminalWindow + if busy of terminalTab is false then + set tabCwd to my promptuaryCwdForTty(tty of terminalTab) + if tabCwd is targetCwd then + set targetTab to terminalTab + set index of terminalWindow to 1 + set selected of terminalTab to true + exit repeat + end if + end if + end repeat + if targetTab is not missing value then exit repeat + end repeat + end if + + if targetTab is missing value then + set targetTab to do script "${commandText}" + set custom title of targetTab to "${sessionTitle}" + else + do script "${commandText}" in targetTab + set custom title of targetTab to "${sessionTitle}" + end if +end tell +`.trim(); +} + +function buildITermAppleScript(command: string, vaultPath: string): string { + const commandText = escapeAppleScriptString(command); + const sessionTitle = escapeAppleScriptString(buildAgentTerminalTitle(vaultPath)); + const targetCwd = escapeAppleScriptString(normalizeVaultPath(vaultPath)); + + return ` +${buildCwdLookupAppleScriptHandler()} + +tell application "iTerm" + activate + set targetSession to missing value + set targetCwd to "${targetCwd}" + + repeat with terminalWindow in windows + repeat with terminalTab in tabs of terminalWindow + repeat with terminalSession in sessions of terminalTab + if (name of terminalSession is "${sessionTitle}") and (is processing of terminalSession is false) then + set targetSession to terminalSession + exit repeat + end if + end repeat + if targetSession is not missing value then exit repeat + end repeat + if targetSession is not missing value then exit repeat + end repeat + + if targetSession is missing value then + repeat with terminalWindow in windows + repeat with terminalTab in tabs of terminalWindow + repeat with terminalSession in sessions of terminalTab + if (is processing of terminalSession is false) then + set sessionCwd to my promptuaryCwdForTty(tty of terminalSession) + if sessionCwd is targetCwd then + set targetSession to terminalSession + exit repeat + end if + end if + end repeat + if targetSession is not missing value then exit repeat + end repeat + if targetSession is not missing value then exit repeat + end repeat + end if + + if targetSession is missing value then + if (count of windows) is 0 then + set targetWindow to (create window with default profile) + else + set targetWindow to current window + tell targetWindow + create tab with default profile + end tell + end if + set targetSession to current session of targetWindow + end if + + tell targetSession + set name to "${sessionTitle}" + write text "${commandText}" + end tell +end tell +`.trim(); +} + +function buildTerminalSessionCommand(tmpScript: string, vaultPath: string): string { + return `cd ${shellEscape(normalizeVaultPath(vaultPath))} && ${shellEscape(tmpScript)}`; +} + +function escapeAppleScriptString(value: string): string { + return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\""); +} + +function buildCwdLookupAppleScriptHandler(): string { + return ` +on promptuaryCwdForTty(tabTty) + if tabTty is missing value then return "" + set ttyText to tabTty as text + if ttyText is "" then return "" + if ttyText starts with "/dev/" then set ttyText to text 6 thru -1 of ttyText + set lookupCmd to "tty=" & quoted form of ttyText & "; pid=$(/bin/ps -t \\"$tty\\" -o pid= 2>/dev/null | /usr/bin/head -n 1 | /usr/bin/tr -d ' '); if [ -n \\"$pid\\" ]; then /usr/sbin/lsof -a -p \\"$pid\\" -d cwd -Fn 2>/dev/null | /usr/bin/sed -n 's/^n//p' | /usr/bin/head -n 1; fi" + try + return do shell script lookupCmd + on error + return "" + end try +end promptuaryCwdForTty +`.trim(); +} + +function buildAgentTerminalTitle(vaultPath: string): string { + const normalizedPath = normalizeVaultPath(vaultPath); + const vaultName = sanitizeTitlePart(nodePath.basename(normalizedPath) || "Vault"); + const pathHash = nodeCrypto.createHash("sha256") + .update(normalizedPath) + .digest("hex") + .slice(0, 12); + return `${AGENT_TERMINAL_TITLE_PREFIX} - ${vaultName} - ${pathHash}`; +} + +function normalizeVaultPath(vaultPath: string): string { + let resolved = nodePath.resolve(vaultPath); + try { + resolved = fs.realpathSync.native(resolved); + } catch { + // Keep the resolved path when the directory cannot be realpathed. + } + const parsed = nodePath.parse(resolved); + return resolved === parsed.root ? resolved : resolved.replace(/[\\/]+$/, ""); +} + +function sanitizeTitlePart(value: string): string { + return value.replace(/\s+/g, " ").trim() || "Vault"; +} + // ---------- file change monitor ---------- export type ChangeStatus = "idle" | "running" | "detected" | "timeout"; export class FileChangeMonitor { private status: ChangeStatus = "idle"; - private timer: number | null = null; + private timeoutTimer: number | null = null; + private settleTimer: number | null = null; private resolve: ((detected: boolean) => void) | null = null; private watchedAbsPath: string | null = null; + private unwatch: (() => void) | null = null; /** * Start monitoring a file for changes made by an external process. @@ -96,12 +265,13 @@ export class FileChangeMonitor { * because vault events are only fired for writes Obsidian itself initiates — * external CLI Agents write directly to disk and vault events are unreliable. * - * Resolves `true` when mtime changes, `false` on timeout. + * Resolves `true` after a detected change stays quiet briefly, `false` on timeout. */ startMonitor( app: App, filePath: string, timeoutMs = 5 * 60 * 1000, + settleMs = 1500, ): Promise { this.status = "running"; @@ -112,29 +282,35 @@ export class FileChangeMonitor { return new Promise((resolve) => { this.resolve = resolve; - // Timeout guard - this.timer = window.setTimeout(() => { + const finish = (detected: boolean, status: ChangeStatus) => { + if (this.status !== "running") return; this.cleanup(); - this.status = "timeout"; - resolve(false); + this.status = status; + this.resolve = null; + resolve(detected); + }; + + this.timeoutTimer = window.setTimeout(() => { + finish(false, "timeout"); }, timeoutMs); - // Poll every 1 s using fs.watchFile const listener = (curr: import("fs").Stats, prev: import("fs").Stats) => { - if (curr.mtimeMs !== prev.mtimeMs && this.status === "running") { - this.cleanup(); - this.status = "detected"; - resolve(true); - } + if (this.status !== "running") return; + if (curr.mtimeMs === prev.mtimeMs && curr.size === prev.size) return; + + if (this.settleTimer) window.clearTimeout(this.settleTimer); + this.settleTimer = window.setTimeout(() => { + finish(true, "detected"); + }, settleMs); }; fs.watchFile(absPath, { persistent: false, interval: 1000 }, listener); - - // Override cleanup to also stop the watcher - const origCleanup: () => void = this.cleanup; - this.cleanup = () => { - origCleanup(); - try { fs.unwatchFile(absPath, listener); } catch { /* ignore */ } + this.unwatch = () => { + try { + fs.unwatchFile(absPath, listener); + } catch { + // ignore + } }; }); } @@ -142,9 +318,11 @@ export class FileChangeMonitor { /** Cancel an in-progress monitor */ cancel(): void { if (this.status === "running") { + const resolve = this.resolve; this.cleanup(); this.status = "idle"; - this.resolve?.(false); + this.resolve = null; + resolve?.(false); } } @@ -153,10 +331,17 @@ export class FileChangeMonitor { } private cleanup = (): void => { - if (this.timer) { - window.clearTimeout(this.timer); - this.timer = null; + if (this.timeoutTimer) { + window.clearTimeout(this.timeoutTimer); + this.timeoutTimer = null; + } + if (this.settleTimer) { + window.clearTimeout(this.settleTimer); + this.settleTimer = null; + } + if (this.unwatch) { + this.unwatch(); + this.unwatch = null; } }; } - diff --git a/src/diff/DiffModal.ts b/src/diff/DiffModal.ts index 80deac2..71cf79b 100644 --- a/src/diff/DiffModal.ts +++ b/src/diff/DiffModal.ts @@ -1,4 +1,4 @@ -import { App, Modal, setIcon } from "obsidian"; +import { App, Modal, Notice, setIcon } from "obsidian"; import { DiffBlock, computeDiff, @@ -12,6 +12,10 @@ export interface DiffModalResult { mergedText?: string; } +interface DiffModalOptions { + reloadModifiedText?: () => Promise; +} + interface Hunk { header: string; blocks: DiffBlock[]; @@ -57,8 +61,8 @@ function groupIntoHunks(blocks: DiffBlock[], ctxLines = 2): Hunk[] { } export class DiffModal extends Modal { - private blocks: DiffBlock[]; - private hunks: Hunk[]; + private blocks: DiffBlock[] = []; + private hunks: Hunk[] = []; /** true = accepted, false = rejected, undefined = pending */ private hunkDecisions: Map = new Map(); private acceptMap: Map = new Map(); @@ -70,11 +74,18 @@ export class DiffModal extends Modal { private originalText: string, private modifiedText: string, private fileName: string, + private options: DiffModalOptions = {}, ) { super(app); - this.blocks = computeDiff(originalText, modifiedText); - this.hunks = groupIntoHunks(this.blocks); - // Default: all changes accepted + this.resetDiff(modifiedText); + } + + private resetDiff(modifiedText: string): void { + this.modifiedText = modifiedText; + this.blocks = computeDiff(this.originalText, modifiedText); + this.hunks = groupIntoHunks(this.blocks).filter((hunk) => hunk.changeIndices.length > 0); + this.acceptMap.clear(); + this.hunkDecisions.clear(); for (const b of this.blocks) { if (b.type !== "unchanged") this.acceptMap.set(b.index, true); } @@ -110,7 +121,19 @@ export class DiffModal extends Modal { const hunkBadge = headerRight.createSpan({ cls: "prm-dm-hunk-badge" }); hunkBadge.setText(`${this.hunks.length} ${t("diff.hunks")}`); + if (this.options.reloadModifiedText) { + const refreshBtn = headerRight.createEl("button", { cls: "prm-dm-refresh" }); + refreshBtn.title = t("diff.btn.refresh"); + refreshBtn.setAttribute("aria-label", t("diff.btn.refresh")); + setIcon(refreshBtn, "refresh-cw"); + refreshBtn.createSpan({ text: t("diff.btn.refresh") }); + refreshBtn.onclick = () => { + void this.refreshDiff(refreshBtn); + }; + } + const closeBtn = headerRight.createEl("button", { cls: "prm-dm-close" }); + closeBtn.title = t("common.close"); setIcon(closeBtn, "x"); closeBtn.onclick = () => { this.result = { action: "reject" }; @@ -150,15 +173,14 @@ export class DiffModal extends Modal { setIcon(applyBtn, "check"); applyBtn.createSpan({ text: t("diff.btn.applySelected") }); applyBtn.onclick = () => { - this.result = this.buildResultFromAcceptMap(); - this.close(); + void this.applySelected(); }; } onClose(): void { if (this.resolve) { if (!this.result) { - this.result = this.buildResultFromAcceptMap(); + this.result = { action: "reject" }; } this.resolve(this.result); this.resolve = null; @@ -168,6 +190,9 @@ export class DiffModal extends Modal { private buildResultFromAcceptMap(): DiffModalResult { // Build the result from current hunk-level decisions. // Default map value is true, so untouched hunks are accepted unless rejected. + if (this.acceptMap.size === 0) { + return { action: "reject" }; + } const decisions = [...this.acceptMap.values()]; const allAccepted = decisions.every(v => v); const allRejected = decisions.every(v => !v); @@ -175,12 +200,52 @@ export class DiffModal extends Modal { return { action: "reject" }; } if (allAccepted) { - return { action: "accept-all" }; + return { action: "accept-all", mergedText: this.modifiedText }; } const merged = applyPartialDiff(this.originalText, this.blocks, this.acceptMap); return { action: "accept-partial", mergedText: merged }; } + private async refreshDiff(refreshBtn: HTMLButtonElement): Promise { + if (!this.options.reloadModifiedText) return; + + refreshBtn.disabled = true; + refreshBtn.addClass("is-loading"); + + try { + const modifiedText = await this.options.reloadModifiedText(); + this.result = null; + this.resetDiff(modifiedText); + this.onOpen(); + new Notice(t("diff.notice.refreshed")); + } catch { + refreshBtn.disabled = false; + refreshBtn.removeClass("is-loading"); + new Notice(t("diff.notice.refreshFailed")); + } + } + + private async applySelected(): Promise { + if (this.options.reloadModifiedText) { + try { + const latestModifiedText = await this.options.reloadModifiedText(); + if (latestModifiedText !== this.modifiedText) { + this.result = null; + this.resetDiff(latestModifiedText); + this.onOpen(); + new Notice(t("diff.notice.changedBeforeApply")); + return; + } + } catch { + new Notice(t("diff.notice.refreshFailed")); + return; + } + } + + this.result = this.buildResultFromAcceptMap(); + this.close(); + } + private renderHunk(parent: HTMLElement, hunk: Hunk, idx: number): void { const wrap = parent.createDiv({ cls: "prm-dm-hunk" }); diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index d37b1fa..91ae4cf 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -305,6 +305,10 @@ const en: Record = { "diff.btn.applySelected": "Apply selected", "diff.btn.reject": "Reject", "diff.btn.accept": "Accept", + "diff.btn.refresh": "Refresh", + "diff.notice.refreshed": "Diff refreshed", + "diff.notice.refreshFailed": "Failed to refresh diff", + "diff.notice.changedBeforeApply": "File changed again. Diff refreshed, please review again.", "diff.hunks": "changes", // ==================== api ==================== diff --git a/src/i18n/locales/zh-CN.ts b/src/i18n/locales/zh-CN.ts index a51d48f..99d2a6b 100644 --- a/src/i18n/locales/zh-CN.ts +++ b/src/i18n/locales/zh-CN.ts @@ -322,6 +322,10 @@ const zhCN: Record = { "diff.btn.applySelected": "应用选中", "diff.btn.reject": "拒绝", "diff.btn.accept": "接受", + "diff.btn.refresh": "刷新", + "diff.notice.refreshed": "已刷新 Diff", + "diff.notice.refreshFailed": "刷新 Diff 失败", + "diff.notice.changedBeforeApply": "文件有新变化,已刷新 Diff,请重新确认", "diff.hunks": "个变更", // ==================== api ==================== diff --git a/src/main.ts b/src/main.ts index 0b17376..9ac4688 100644 --- a/src/main.ts +++ b/src/main.ts @@ -396,8 +396,9 @@ export default class PromptuaryPlugin extends Plugin { switch (diffResult.action) { case "accept-all": { - await this.app.vault.modify(file, modifiedText); - await this.reanchorAndConfirm(targetPath, originalText, modifiedText); + const finalText = diffResult.mergedText ?? modifiedText; + await this.app.vault.modify(file, finalText); + await this.reanchorAndConfirm(targetPath, originalText, finalText); new Notice(t("main.notice.allAccepted")); break; } @@ -665,11 +666,14 @@ export default class PromptuaryPlugin extends Plugin { original, modified, fileName, + { + reloadModifiedText: () => this.app.vault.read(file), + }, ).openForResult(); switch (result.action) { case "accept-all": { - const finalText = modified; + const finalText = result.mergedText ?? modified; await this.reanchorAndConfirm(filePath, original, finalText); this.originalTextBeforeAgent = null; new Notice(t("main.notice.allAccepted")); diff --git a/src/utils/nodeApi.ts b/src/utils/nodeApi.ts index 482c03d..d73ea49 100644 --- a/src/utils/nodeApi.ts +++ b/src/utils/nodeApi.ts @@ -14,7 +14,8 @@ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports -- window.require is the only way to access Node.js builtins in Obsidian's renderer process const nodeRequire = (window as unknown as { require?: NodeRequire }).require ?? require; -export const { execSync, exec } = nodeRequire("child_process") as typeof import("child_process"); +export const { execSync, exec, execFileSync } = nodeRequire("child_process") as typeof import("child_process"); export const fs = nodeRequire("fs") as typeof import("fs"); export const os = nodeRequire("os") as typeof import("os"); export const nodePath = nodeRequire("path") as typeof import("path"); +export const nodeCrypto = nodeRequire("crypto") as typeof import("crypto"); diff --git a/styles.css b/styles.css index e6d502e..adb2e9b 100644 --- a/styles.css +++ b/styles.css @@ -1540,6 +1540,40 @@ border: 1px solid var(--background-modifier-border); color: var(--text-muted); } +.prm-dm-refresh { + display: inline-flex; align-items: center; gap: 4px; + height: 28px; + padding: 0 8px; + border-radius: 6px; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + color: var(--text-muted); + cursor: pointer; + font-size: 10px; + font-family: var(--font-monospace); + transition: background 0.12s, color 0.12s, border-color 0.12s; +} +.prm-dm-refresh:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} +.prm-dm-refresh:disabled { + cursor: default; + opacity: 0.75; +} +.prm-dm-refresh svg { + width: 14px; + height: 14px; + display: block; + flex-shrink: 0; +} +.prm-dm-refresh.is-loading svg { + animation: prm-dm-spin 0.8s linear infinite; +} +@keyframes prm-dm-spin { + from { transform: rotate(0deg); } + to { transform: rotate(360deg); } +} .prm-dm-close { width: 28px; height: 28px; border-radius: 6px; @@ -1572,6 +1606,7 @@ border-radius: 8px; overflow: hidden; background: var(--background-primary); transition: opacity 0.2s, transform 0.2s; + flex: 0 0 auto; } .prm-dm-hunk.prm-dm-hunk-decided { opacity: 0; @@ -1580,9 +1615,11 @@ } .prm-dm-hunk-header { display: flex; align-items: center; justify-content: space-between; + gap: 12px; padding: 6px 12px; background: var(--background-secondary); border-bottom: 1px solid var(--background-modifier-border); + flex-shrink: 0; } .prm-dm-hunk-header-left { display: flex; align-items: center; gap: 8px; } .prm-dm-hunk-pos { @@ -1642,7 +1679,8 @@ .prm-dm-lines { font-family: var(--font-monospace); font-size: 11px; line-height: 1.7; - max-height: min(52vh, 520px); + max-height: min(46vh, 460px); + min-height: 0; overflow-y: auto; overscroll-behavior: contain; } @@ -1654,6 +1692,7 @@ .prm-dm-line { display: flex; align-items: baseline; padding: 0 12px; + min-height: 19px; } .prm-dm-line-unchanged { color: var(--text-normal); @@ -1694,6 +1733,17 @@ } .prm-dm-text { white-space: pre-wrap; word-break: break-all; flex: 1; } +@media (max-width: 640px) { + .prm-dm-refresh span { display: none; } + .prm-dm-hunk-header { + align-items: flex-start; + flex-direction: column; + } + .prm-dm-hunk-actions { + align-self: flex-end; + } +} + /* Footer */ .prm-dm-footer { display: flex; align-items: center; justify-content: space-between;