Files
2026-04-27 12:18:37 +08:00

16 lines
50 KiB
JavaScript

var global = globalThis;
"use strict";var je=Object.create;var G=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var Ke=(s,r)=>{for(var e in r)G(s,e,{get:r[e],enumerable:!0})},pe=(s,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Ye(r))!Xe.call(s,i)&&i!==e&&G(s,i,{get:()=>r[i],enumerable:!(t=ze(r,i))||t.enumerable});return s};var Ze=(s,r,e)=>(e=s!=null?je(Je(s)):{},pe(r||!s||!s.__esModule?G(e,"default",{value:s,enumerable:!0}):e,s)),Qe=s=>pe(G({},"__esModule",{value:!0}),s);var mt={};Ke(mt,{default:()=>K});module.exports=Qe(mt);var g=require("obsidian");var ye=require("child_process"),se=Ze(require("path"));function ee(s){let r=[`Current file: ${s.filePath??"(none)"}`,`Note title: ${s.noteTitle??"(none)"}`,`Is wiki page: ${s.isWikiPage?"yes":"no"}`,`Page sources: ${s.sources.length?s.sources.join(", "):"(none)"}`,`Selection lines: ${s.selectionFromLine??"-"} to ${s.selectionToLine??"-"}`,`Editor dirty: ${s.editorDirty?"yes":"no"}`];return s.selectionText.trim()&&r.push("","Selected text:",s.selectionText.trim()),s.bufferSnapshot?.trim()&&r.push("","Unsaved buffer snapshot:",s.bufferSnapshot.trim()),r.join(`
`)}function ge(s){return["You are assisting from inside an Obsidian plugin for the LLM-Wiki vault.","Discuss the current note and related vault context.","Do not write files.","Do not register new sources.","",ee(s.pageContext),"","User question:",s.userPrompt.trim()].join(`
`)}function fe(s){return["Use the loaded plugin skill lw2:deep-research as the workflow contract for this task.","You are in the planning and confirmation phase of a deep research session for the LLM-Wiki vault.","Stay conversational and concise.","Do not write files.","Do not mutate the source registry.","Do not claim the report has been registered.","Do not return a final full report draft unless the user explicitly asks for draft generation or revision.","",ee(s.pageContext),"",`Research topic: ${s.topic.trim()}`,s.userIntent?.trim()?`Current user instruction: ${s.userIntent.trim()}`:"",s.currentDraft?.trim()?["","Current draft for reference:",s.currentDraft.trim()].join(`
`):"","","Help with:","- confirming scope and direction","- choosing or adjusting research methods","- deciding what evidence or searches are still needed","- identifying risks, blind spots, or contradictions to investigate next"].filter(Boolean).join(`
`)}function me(s){return s.topic.trim()||s.pageContext.noteTitle||"Untitled research topic"}function we(s){return["Use the loaded plugin skill lw2:deep-research as the workflow contract for this task.","You are preparing a deep research draft for the LLM-Wiki vault.","Return completed markdown only.","Return the full current markdown draft, not a patch or partial section.","Do not write files.","Do not mutate the source registry.","Do not claim the report has been registered.","",ee(s.pageContext),"",`Research topic: ${s.topic.trim()}`,`Draft title: ${me(s)}`,s.userIntent?.trim()?`User intent: ${s.userIntent.trim()}`:"",s.currentDraft?.trim()?["","Current draft to revise:",s.currentDraft.trim()].join(`
`):"","","Write a report with:","- title","- date","- research question","- scope","- summary","- findings","- source links","- uncertainty notes","- suggested compile targets"].filter(Boolean).join(`
`)}function xe(s){return me(s)}function te(s){let r=s.trim();if(!r)return[];let e;try{e=JSON.parse(r)}catch{return[{type:"warning",message:`Unparseable Claude stream line: ${r}`}]}let t=[];if(e.session_id&&t.push({type:"session",sessionId:e.session_id}),e.type==="assistant"){t.push({type:"message_start",role:"assistant"});let i=e.message?.content?.filter(n=>n.type==="text"&&n.text).map(n=>n.text).join("");return i&&t.push({type:"text_delta",text:i}),t.push({type:"message_stop"}),t}return e.type==="content_block_delta"&&e.delta?.text&&t.push({type:"text_delta",text:e.delta.text}),e.type==="content_block_start"&&e.content_block?.type==="text"&&(t.push({type:"message_start",role:"assistant"}),e.content_block.text&&t.push({type:"text_delta",text:e.content_block.text})),e.type==="content_block_stop"&&t.push({type:"message_stop"}),e.type==="result"&&e.result&&t.push({type:"tool_status",message:e.result}),e.type==="error"&&t.push({type:"error",message:e.error||"Claude stream error"}),t}function et(s,r){return se.default.isAbsolute(r)?r:se.default.join(s.runtimeRoot,r)}function tt(s){return s==="research"?["--allowedTools","Read,Grep,Glob,Bash,mcp__graphify__query_graph,mcp__graphify__get_node,mcp__graphify__get_neighbors,mcp__exa__*"]:["--allowedTools","Read,Grep,Glob,mcp__graphify__query_graph,mcp__graphify__get_node,mcp__graphify__get_neighbors"]}function st(s,r,e,t){let i=["-p","--verbose","--output-format","stream-json","--plugin-dir",et(s,s.claudePluginDir),...tt(e),...s.claudeArgs];return t&&i.push("--resume",t),i.push("--",r),i}var B=class{constructor(r){this.settings=r}async chat(r,e){return this.runPrompt(ge(r),r.sessionId,r.allowedToolsMode,e).then(({sessionId:t,text:i,warnings:n})=>({sessionId:t,text:i,warnings:n}))}async discussResearch(r,e){return this.runPrompt(fe(r),r.sessionId,"research",e).then(({sessionId:t,text:i,warnings:n})=>({sessionId:t,text:i,warnings:n}))}async generateResearchDraft(r,e){let t=await this.runPrompt(we(r),r.sessionId,"research",e);return{sessionId:t.sessionId,title:xe(r),topic:r.topic,markdownBody:t.text,warnings:t.warnings}}runPrompt(r,e,t,i){return new Promise((n,o)=>{if(!this.settings.runtimeRoot.trim()){o(new Error("LLM-Wiki runtime root is not configured in plugin settings."));return}let a=st(this.settings,r,t,e),c=(0,ye.spawn)(this.settings.claudeCommand,a,{cwd:this.settings.runtimeRoot,stdio:["ignore","pipe","pipe"]}),d=e||"",h="",w=[],y="",l="",f=p=>{for(let u of p)u.type==="session"&&(d=u.sessionId),u.type==="text_delta"&&(h+=u.text),u.type==="warning"&&w.push(u.message),i(u)};c.stdout.setEncoding("utf8"),c.stdout.on("data",p=>{y+=p;let u=y.split(/\r?\n/);y=u.pop()??"";for(let v of u)f(te(v))}),c.stderr.setEncoding("utf8"),c.stderr.on("data",p=>{l+=p}),c.on("error",p=>{o(p)}),c.on("close",p=>{if(y.trim()&&f(te(y)),p!==0){o(new Error(l.trim()||`Claude exited with code ${p}`));return}d||w.push("Claude did not report a session ID; future resume may be unavailable."),n({sessionId:d,text:h.trim(),warnings:w})})})}};var ve=require("child_process"),_=require("fs/promises"),q=require("path"),Re=require("os");function rt(s,r,e,t){return{command:"/bin/bash",args:["-ilc",'exec "$1" "$2" "${@:3}"',"_",s.nodeCommand,(0,q.resolve)(s.runtimeRoot,e),...t],env:{...process.env,LW2_ROOT:s.runtimeRoot,LW2_WORKSPACE_ROOT:r},cwd:s.runtimeRoot}}function Ce(s){let r=s.trim();if(!r)return null;try{return JSON.parse(r)}catch{let e=r.indexOf("{"),t=r.lastIndexOf("}");if(e===-1||t<=e)return null;try{return JSON.parse(r.slice(e,t+1))}catch{return null}}}async function D(s,r,e,t){return new Promise((i,n)=>{let o=rt(s,r,e,t),a=(0,ve.spawn)(o.command,o.args,{cwd:o.cwd,env:o.env,stdio:["ignore","pipe","pipe"]}),c="",d="";a.stdout.setEncoding("utf8"),a.stdout.on("data",h=>{c+=h}),a.stderr.setEncoding("utf8"),a.stderr.on("data",h=>{d+=h}),a.on("error",h=>n(h)),a.on("close",h=>{i({code:h??1,stdout:c,stderr:d,data:Ce(c)??Ce(d)})})})}async function re(s,r,e){let t=s.trim()||(0,Re.tmpdir)();await(0,_.mkdir)(t,{recursive:!0});let i=await(0,_.mkdtemp)((0,q.join)(t,`${r}-`)),n=(0,q.join)(i,`${r}.md`);return await(0,_.writeFile)(n,e,"utf8"),n}var Ee=require("@codemirror/state"),F=require("@codemirror/view");function ie(s){let r=s.match(/^---\n([\s\S]*?)\n---\n?/);if(!r)return[];let t=(r[1]??"").match(/(^|\n)sources:\s*\n((?:\s+- .*\n?)*)/);return t?(t[2]??"").split(/\r?\n/).map(i=>i.match(/^\s+-\s+(.+)$/)?.[1]?.trim()??"").filter(Boolean):[]}function Se(s){let r=[],e=/\*(EXTRACTED|INFERRED|AMBIGUOUS)\s+([01](?:\.\d+)?)\*/g;for(let t of s.matchAll(e)){let i=t[1],n=Number(t[2]);if(!Number.isFinite(n))continue;let o=n>=.85?"high":n>=.6?"medium":"low";r.push({raw:t[0],evidence:i,confidence:n,confidenceLevel:o,index:t.index??0})}return r}function be(s,r){let e=s?.file??null,t=s?.editor,i=t?.getSelection()??"",n=s?.getViewData?.()??"",o=s?.data??"",a=!!(s&&n!==o),c=a&&(r==="never"||r==="prompt")?n:void 0;return{filePath:e?.path??null,noteTitle:e?.basename??null,isWikiPage:!!e?.path?.startsWith("wiki/"),sources:ie(n||o),selectionText:i,selectionFromLine:i?t?.getCursor("from").line??null:null,selectionToLine:i?t?.getCursor("to").line??null:null,editorDirty:a,bufferSnapshot:c}}function it(s,r){return`lw2-confidence-pill lw2-confidence-${s.toLowerCase()} lw2-confidence-${r}`}function ke(s){return F.ViewPlugin.fromClass(class{constructor(r){this.decorations=this.build(r)}update(r){(r.docChanged||r.viewportChanged)&&(this.decorations=this.build(r.view))}build(r){if(!s.isEnabled())return F.Decoration.none;let e=new Ee.RangeSetBuilder;for(let t of Se(r.state.doc.toString()))e.add(t.index,t.index+t.raw.length,F.Decoration.mark({class:it(t.evidence,t.confidenceLevel)}));return e.finish()}},{decorations:r=>r.decorations})}var C=require("obsidian");var Pe="lw2-editor-actions";var Te=[{id:"high",label:"Mark Confidence: High",marker:"*EXTRACTED 0.9*"},{id:"medium",label:"Mark Confidence: Medium",marker:"*INFERRED 0.7*"},{id:"low",label:"Mark Confidence: Low",marker:"*AMBIGUOUS 0.4*"},{id:"untrusted",label:"Mark Confidence: Untrusted",marker:"*AMBIGUOUS 0.1*"}];function Ie(s){return s.getSelection().trim().length>0}function ne(s,r){return s.length>r}function j(s){if(s.length<=3e3)return s;let r=s.length-2e3-1e3;return`${s.slice(0,2e3)}
[... preview truncated ${r} characters ...]
${s.slice(-1e3)}`}function _e(s,r){let e=/\s$/.test(s)?"":" ";return`${s}${e}${r}`}function De(s){return["Use the loaded plugin skill lw2:fast-research as the workflow contract for this task.","Run a fast research pass on the selected excerpt.","Stay read-only.","Do not write files.","Do not register new sources.","Be concise and useful.","","Respond with:","- quick interpretation","- important context or likely implications","- uncertainty or ambiguity to watch","- suggested next research directions","","Selected excerpt:",s.trim()].join(`
`)}var M=require("obsidian");function Me(s,r){return r instanceof M.MarkdownView?r:s.app.workspace.getActiveViewOfType(M.MarkdownView)}function ot(s,r,e){let t=r.getSelection();if(!t.trim())return;if(ne(t,24e3)){new M.Notice("Selection is too large for Deep Research. Narrow the selection and try again.");return}let i=Me(s,e),n=s.getCurrentPageContext(i);s.openDeepResearchView({pageContext:n,topic:t,userIntent:t})}function at(s,r,e){let t=r.getSelection();if(!t.trim())return;if(ne(t,12e3)){new M.Notice("Selection is too large for Fast Research. Narrow the selection and try again.");return}let i=Me(s,e),o={pageContext:{...s.getCurrentPageContext(i),selectionText:t},userPrompt:De(t)};s.openFastResearchView(o)}function ct(s,r){let e=s.getSelection();e.trim()&&s.replaceSelection(_e(e,r.marker))}function oe(s,r,e,t){s.addItem(i=>{i.setSection(Pe).setTitle(`LLM-Wiki: ${r}`).setIcon(e).onClick(t)})}function Le(s){s.registerEvent(s.app.workspace.on("editor-menu",(r,e,t)=>{if(Ie(e)){oe(r,"Deep Research Selection","search",()=>{ot(s,e,t)}),oe(r,"Fast Research Selection","bot",()=>{at(s,e,t)});for(let i of Te)oe(r,i.label,"badge-help",()=>{ct(e,i)})}}))}function Ae(s){Le(s),s.addCommand({id:"lw2-open-chat-sidebar",name:"Open LLM-Wiki chat sidebar",callback:async()=>{await s.activateChatSidebar()}}),s.addCommand({id:"lw2-run-deep-research",name:"Run deep research from current note or selection",editorCallback:(r,e)=>{let t=e instanceof C.MarkdownView?e:s.app.workspace.getActiveViewOfType(C.MarkdownView),i=s.getCurrentPageContext(t),n=r.getSelection().trim();if(n.length>24e3){new C.Notice("Selection is too large for Deep Research. Narrow the selection and try again.");return}let o=n||i.noteTitle||"";s.openDeepResearchView({pageContext:i,topic:o,userIntent:n||i.bufferSnapshot||""})}}),s.addCommand({id:"lw2-refresh-source-index",name:"Refresh LLM-Wiki source trust index",callback:async()=>{await s.refreshRegistryIndex()}}),s.addCommand({id:"lw2-update-current-page-sources-trust",name:"Update trust for current page sources",callback:()=>{s.openCurrentPageSourceTrustModal()}}),s.addCommand({id:"lw2-run-compile-preflight",name:"Run LLM-Wiki compile preflight",callback:async()=>{try{new C.Notice("Running LLM-Wiki compile preflight...");let r=await s.runCompilePreflight(),e=r.registered_sources?.length??0,t=r.active_uncompiled_sources?.length??0,i=r.warnings?.length?` Warnings: ${r.warnings.length}.`:"";new C.Notice(`Compile preflight complete. Registered ${e} new source(s). ${t} Active source(s) remain uncompiled.${i}`)}catch(r){let e=r instanceof Error?r.message:String(r);new C.Notice(`Compile preflight failed: ${e}`)}}}),s.addCommand({id:"lw2-run-lint-pass",name:"Run LLM-Wiki lint deterministic pass",callback:async()=>{try{new C.Notice("Running LLM-Wiki lint deterministic pass...");let r=await s.runLintPass(!1);if(r.status==="noop"){new C.Notice(`Lint complete: ${r.reason||"No risky sources required action."}`);return}let e=r.affected_pages?.length??0,t=r.pages_deprecated??0,i=r.queue_changed?" Review queue updated.":"",n=r.warnings?.length?` Warnings: ${r.warnings.length}.`:"";new C.Notice(`Lint complete. Affected pages: ${e}. Deprecated: ${t}.${i}${n}`)}catch(r){let e=r instanceof Error?r.message:String(r);new C.Notice(`Lint failed: ${e}`)}}})}var Ve=require("@codemirror/state"),S=require("@codemirror/view");function lt(s){return`lw2-source-badge-${s.toLowerCase()}`}var ce=class extends S.WidgetType{constructor(e,t){super();this.entries=e;this.openSourceTrustModal=t}toDOM(){let e=document.createElement("span");if(e.className="lw2-source-badge-row",this.entries.length>1){let t=document.createElement("button");t.className="lw2-source-badge lw2-source-badge-batch",t.textContent="All Sources",t.title="Update trust for all sources on this page",t.onclick=()=>this.openSourceTrustModal(this.entries.map(i=>i.id)),e.appendChild(t)}for(let t of this.entries){let i=document.createElement("button");i.className=`lw2-source-badge ${lt(t.trust)}`,i.textContent=`${t.id} ${t.trust}`,i.title=t.status_reason||t.path,i.onclick=()=>this.openSourceTrustModal([t.id]),e.appendChild(i)}return e}};function Oe(s){return S.ViewPlugin.fromClass(class{constructor(r){this.decorations=this.build(r)}update(r){(r.docChanged||r.viewportChanged)&&(this.decorations=this.build(r.view))}build(r){if(!s.isEnabled())return S.Decoration.none;let e=ie(r.state.doc.toString());if(!e.length)return S.Decoration.none;let t=s.getRegistryIndex(),i=e.map(o=>t.byId.get(o)).filter(o=>!!o);if(!i.length)return S.Decoration.none;let n=new Ve.RangeSetBuilder;return n.add(0,0,S.Decoration.widget({widget:new ce(i,s.openSourceTrustModal),side:-1})),n.finish()}},{decorations:r=>r.decorations})}function dt(s){let r=s.match(/^(EXTRACTED|INFERRED|AMBIGUOUS)\s+([01](?:\.\d+)?)$/);if(!r||!r[1]||!r[2])return null;let e=Number(r[2]),t=e>=.85?"high":e>=.6?"medium":"low";return{evidence:r[1],confidenceLevel:t}}function $e(s){return r=>{if(s.isEnabled())for(let e of Array.from(r.querySelectorAll("em"))){let t=dt(e.textContent?.trim()||"");if(!t)continue;let i=document.createElement("span");i.className=`lw2-confidence-pill lw2-confidence-${t.evidence.toLowerCase()} lw2-confidence-${t.confidenceLevel}`,i.textContent=e.textContent||"",e.replaceWith(i)}}}var Be=require("obsidian");function ut(s){return`lw2-source-badge-${s.toLowerCase()}`}function qe(s){return async(r,e)=>{if(!s.settings.showSourceTrustBadges||!e.sourcePath?.startsWith("wiki/"))return;let t=s.app.vault.getAbstractFileByPath(e.sourcePath);if(!(t instanceof Be.TFile))return;let i=s.app.metadataCache.getFileCache(t),n=Array.isArray(i?.frontmatter?.sources)?i.frontmatter.sources.filter(c=>typeof c=="string"):[];if(!n.length)return;let o=n.map(c=>s.registryIndex.byId.get(c)).filter(c=>!!c);if(!o.length)return;let a=document.createElement("div");if(a.className="lw2-source-badge-row lw2-source-badge-row-preview",o.length>1){let c=document.createElement("button");c.className="lw2-source-badge lw2-source-badge-batch",c.textContent="All Sources",c.title="Update trust for all sources on this page",c.onclick=()=>s.openSourceTrustModal(o.map(d=>d.id)),a.appendChild(c)}for(let c of o){let d=document.createElement("button");d.className=`lw2-source-badge ${ut(c.trust)}`,d.textContent=`${c.id} ${c.trust}`,d.title=c.status_reason||c.path,d.onclick=()=>s.openSourceTrustModal([c.id]),a.appendChild(d)}r.prepend(a)}}var x=require("obsidian"),Fe={runtimeRoot:"",claudeCommand:"claude",nodeCommand:"node",claudeArgs:[],claudePluginDir:"plugins/lw2",autoResumeChatSession:!0,autoSaveBeforeAiRead:"prompt",defaultAllowedToolsMode:"minimal",deepResearchTempDir:"/tmp",insightTempDir:"/tmp",showConfidenceDecorations:!0,showSourceTrustBadges:!0},z=class extends x.PluginSettingTab{constructor(r){super(r.app,r),this.plugin=r}display(){let{containerEl:r}=this;r.empty(),r.createEl("h2",{text:"LLM-Wiki Obsidian Settings"}),new x.Setting(r).setName("Runtime root").setDesc("Absolute path to the LLM-Wiki automation runtime that contains scripts/, plugins/lw2/, and schemas/. This is separate from the currently opened Obsidian vault.").addText(e=>e.setPlaceholder("/path/to/my-llm-wiki").setValue(this.plugin.settings.runtimeRoot).onChange(async t=>{this.plugin.settings.runtimeRoot=t.trim(),await this.plugin.saveSettings()})),new x.Setting(r).setName("Claude command").setDesc("Executable used for Claude Code headless calls.").addText(e=>e.setPlaceholder("claude").setValue(this.plugin.settings.claudeCommand).onChange(async t=>{this.plugin.settings.claudeCommand=t.trim()||"claude",await this.plugin.saveSettings()})),new x.Setting(r).setName("Node command").setDesc("Executable used for repo-local workflow scripts. Set an absolute path if Obsidian is launched outside your shell PATH, such as a GUI app with nvm-managed Node.").addText(e=>e.setPlaceholder("node").setValue(this.plugin.settings.nodeCommand).onChange(async t=>{this.plugin.settings.nodeCommand=t.trim()||"node",await this.plugin.saveSettings()})),new x.Setting(r).setName("Claude plugin dir").setDesc("Runtime-root-relative path to the Phase 1 Claude Code plugin.").addText(e=>e.setPlaceholder("plugins/lw2").setValue(this.plugin.settings.claudePluginDir).onChange(async t=>{this.plugin.settings.claudePluginDir=t.trim()||"plugins/lw2",await this.plugin.saveSettings()})),new x.Setting(r).setName("Claude args").setDesc("Extra CLI arguments, space-separated.").addText(e=>e.setPlaceholder("--verbose").setValue(this.plugin.settings.claudeArgs.join(" ")).onChange(async t=>{this.plugin.settings.claudeArgs=t.split(/\s+/).map(i=>i.trim()).filter(Boolean),await this.plugin.saveSettings()})),new x.Setting(r).setName("Auto resume chat").setDesc("Resume the last sidebar chat session for the current view.").addToggle(e=>e.setValue(this.plugin.settings.autoResumeChatSession).onChange(async t=>{this.plugin.settings.autoResumeChatSession=t,await this.plugin.saveSettings()})),new x.Setting(r).setName("Unsaved editor handling").setDesc("What to do before AI reads context from the current note.").addDropdown(e=>e.addOption("never","Never auto-save").addOption("prompt","Prompt before save").addOption("always","Always save").setValue(this.plugin.settings.autoSaveBeforeAiRead).onChange(async t=>{this.plugin.settings.autoSaveBeforeAiRead=t,await this.plugin.saveSettings()})),new x.Setting(r).setName("Default AI tools mode").setDesc("Default backend posture for chat-oriented actions. Use Minimal for ordinary note discussion. Use Research when chat turns should share the broader read-only tool posture used by Fast Research and Deep Research.").addDropdown(e=>e.addOption("minimal","Minimal").addOption("research","Research").setValue(this.plugin.settings.defaultAllowedToolsMode).onChange(async t=>{this.plugin.settings.defaultAllowedToolsMode=t,await this.plugin.saveSettings()})),new x.Setting(r).setName("Insight temp dir").setDesc("Temporary file directory used before running lw2-save-insight.").addText(e=>e.setValue(this.plugin.settings.insightTempDir).onChange(async t=>{this.plugin.settings.insightTempDir=t.trim()||"/tmp",await this.plugin.saveSettings()})),new x.Setting(r).setName("Deep research temp dir").setDesc("Temporary file directory used before running lw2-deep-research.").addText(e=>e.setValue(this.plugin.settings.deepResearchTempDir).onChange(async t=>{this.plugin.settings.deepResearchTempDir=t.trim()||"/tmp",await this.plugin.saveSettings()})),new x.Setting(r).setName("Confidence decorations").setDesc("Show confidence markers in editor and preview once implemented.").addToggle(e=>e.setValue(this.plugin.settings.showConfidenceDecorations).onChange(async t=>{this.plugin.settings.showConfidenceDecorations=t,await this.plugin.saveSettings()})),new x.Setting(r).setName("Source trust badges").setDesc("Show source trust badges once implemented.").addToggle(e=>e.setValue(this.plugin.settings.showSourceTrustBadges).onChange(async t=>{this.plugin.settings.showSourceTrustBadges=t,await this.plugin.saveSettings()})),r.createEl("p",{cls:"lw2-obsidian-settings-note",text:"This plugin reads and writes note content in the opened Obsidian vault, but it expects Phase 1 runtime assets to live under the configured runtime root."})}};function ht(s){if(!s.startsWith(`---
`))return"";let r=s.indexOf(`
---
`,4);return r===-1?"":s.slice(4,r)}function le(s){return s.trim().replace(/^["']|["']$/g,"")}function pt(s){return{id:s.id,path:s.path??"",kind:s.kind??"external",trust:s.trust??"Active",status_reason:s.status_reason??"",status_changed:s.status_changed??"",added_at:s.added_at??"",content_hash:s.content_hash??"",compile_state:s.compile_state??"uncompiled",compiled_at:s.compiled_at??"",last_graph_update:s.last_graph_update??""}}function Ne(s,r=new Date().toISOString()){let t=ht(s).split(/\r?\n/),i=[],n=new Map,o=1,a=null;for(let c of t){let d=c.replace(/\s+$/g,"");if(!d.trim())continue;let h=d.match(/^version:\s*(.+)$/);if(h){let l=Number(le(h[1]??""));o=Number.isFinite(l)?l:1;continue}let w=d.match(/^ - id:\s*(.+)$/);if(w){a=pt({id:le(w[1]??"")}),i.push(a),n.set(a.id,a);continue}let y=d.match(/^ ([A-Za-z_][A-Za-z0-9_-]*):\s*(.*)$/);if(y&&a){let[,l,f]=y,p=a;p[l??""]=le(f??"")}}return{version:o,byId:n,entries:i,loadedAt:r}}function de(s=new Date().toISOString()){return{version:1,byId:new Map,entries:[],loadedAt:s}}function ue(s){return typeof s=="object"&&s!==null&&"getViewType"in s&&typeof s.getViewType=="function"&&s.getViewType()==="markdown"}function We(s,r,e){if(ue(s))return s;if(ue(r?.view))return r.view;for(let t of e)if(ue(t.view))return t.view;return null}function Ue(s,r){return s.trim()||r?.trim()||""}var P="lw2-chat-sidebar",L="lw2-fast-research",b="lw2-deep-research";var E=require("obsidian"),Y=class extends E.Modal{constructor(e,t){super(e.app);this.plugin=e;this.entries=t;this.saving=!1;this.trust=t[0]?.trust??"Active",this.reason=t.length===1?t[0]?.status_reason??"":""}onOpen(){let{contentEl:e}=this;e.empty();let t=this.entries.map(o=>o.id);e.createEl("h2",{text:this.entries.length===1?`Source Trust: ${t[0]}`:`Batch Source Trust: ${this.entries.length} sources`}),e.createEl("p",{cls:"lw2-modal-context",text:this.entries.length===1?this.entries[0]?.path??"":t.join(", ")}),new E.Setting(e).setName("Trust").addDropdown(o=>o.addOption("Active","Active").addOption("Flagged","Flagged").addOption("Obsolete","Obsolete").addOption("Excluded","Excluded").setValue(this.trust).onChange(a=>{this.trust=a})),new E.Setting(e).setName("Reason").setDesc("Required for Flagged, Obsolete, and Excluded.").addTextArea(o=>o.setValue(this.reason).onChange(a=>{this.reason=a.trim()}));let i=e.createDiv({cls:"lw2-modal-actions"}),n=i.createEl("button",{text:"Apply"});n.addClass("mod-cta"),i.createEl("button",{text:"Cancel"}).onclick=()=>this.close(),n.onclick=async()=>{if(!this.saving){this.saving=!0,n.disabled=!0;try{let o=await this.plugin.updateSourceTrust(t,this.trust,this.reason);new E.Notice(`Source trust updated. Next: ${o.primary_next_action}`),this.close()}catch(o){let a=o instanceof Error?o.message:String(o);new E.Notice(`Source trust update failed: ${a}`)}finally{this.saving=!1,n.disabled=!1}}}}};var V=require("obsidian");var k=require("obsidian"),A=class extends k.Modal{constructor(e,t,i){super(e.app);this.plugin=e;this.body=i;this.saving=!1;this.title=t}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Save Insight"}),new k.Setting(e).setName("Title").addText(o=>o.setValue(this.title).onChange(a=>{this.title=a.trim()}));let t=e.createEl("textarea",{cls:"lw2-modal-textarea"});t.value=this.body,t.readOnly=!0;let i=e.createDiv({cls:"lw2-modal-actions"}),n=i.createEl("button",{text:"Save"});n.addClass("mod-cta"),i.createEl("button",{text:"Cancel"}).onclick=()=>this.close(),n.onclick=async()=>{if(!this.saving){if(!this.title.trim()){new k.Notice("Insight title is required.");return}this.saving=!0,n.disabled=!0;try{let o=await this.plugin.saveInsight(this.title,this.body);if(o.status==="confirmation_required"){if(!window.confirm(o.risk_review?.confirmation_prompt||"Save this sensitive-looking insight?"))return;o=await this.plugin.saveInsight(this.title,this.body,!0)}if(o.status!=="saved")throw new Error(o.status||"Insight save did not complete.");new k.Notice(`Insight saved as ${o.source_id}`),this.close()}catch(o){let a=o instanceof Error?o.message:String(o);new k.Notice(`Save Insight failed: ${a}`)}finally{this.saving=!1,n.disabled=!1}}}}};function He(){return`msg-${Date.now()}-${Math.random().toString(16).slice(2,8)}`}function gt(s){return s.split(/\r?\n/).map(e=>e.replace(/^#+\s*/,"").trim()).find(Boolean)?.slice(0,80)||"Session Insight"}var N=class extends V.ItemView{constructor(e,t){super(e);this.plugin=t;this.messages=[];this.sessionId="";this.sending=!1}getViewType(){return P}getDisplayText(){return"LLM-Wiki Chat"}getIcon(){return"bot"}async onOpen(){this.render()}async onClose(){this.contentEl.empty()}refresh(){this.render()}render(){let{contentEl:e}=this,t=this.plugin.getCurrentPageContext();e.empty(),e.addClass("lw2-chat-view");let i=e.createDiv({cls:"lw2-chat-header"}),n=i.createDiv({cls:"lw2-chat-header-top"});n.createEl("h2",{text:"LLM-Wiki Chat"});let o=n.createEl("button",{cls:"clickable-icon lw2-chat-close-button",attr:{"aria-label":"Close LLM-Wiki chat",title:"Close LLM-Wiki chat"}});(0,V.setIcon)(o,"x"),o.onclick=async()=>{await this.leaf.setViewState({type:"empty"})},i.createEl("div",{cls:"lw2-chat-context",text:t.filePath||"No note context"});let a=e.createDiv({cls:"lw2-chat-transcript"});this.messages.length||a.createEl("p",{cls:"lw2-chat-empty",text:"Ask about the current note, then save useful replies as insights or launch deep research."});for(let l of this.messages){let f=a.createDiv({cls:`lw2-chat-message lw2-chat-message-${l.role}`});if(f.createDiv({cls:"lw2-chat-message-role",text:l.role}),f.createEl("pre",{cls:"lw2-chat-message-body",text:l.text||(l.pending?"...":"")}),l.pagePath&&f.createDiv({cls:"lw2-chat-message-context",text:l.pagePath}),l.role==="assistant"&&!l.pending&&l.text.trim()){let p=f.createDiv({cls:"lw2-chat-message-actions"});p.createEl("button",{text:"Save Insight"}).onclick=()=>{new A(this.plugin,gt(l.text),l.text).open()}}}let c=e.createDiv({cls:"lw2-chat-composer"}),d=c.createEl("textarea",{cls:"lw2-chat-input",attr:{placeholder:"Discuss the current wiki page..."}}),h=c.createDiv({cls:"lw2-chat-actions"}),w=h.createEl("button",{text:"Send"});w.addClass("mod-cta");let y=h.createEl("button",{text:"Deep Research"});y.onclick=async()=>{let l=this.plugin.getCurrentPageContext();await this.plugin.openDeepResearchView({pageContext:l,topic:l.selectionText||l.noteTitle||"",userIntent:l.selectionText||l.bufferSnapshot||""})},w.onclick=async()=>{let l=d.value.trim();if(!l||this.sending)return;let f=await this.plugin.getCurrentPageContextForAiRead();if(!f.filePath){new V.Notice("Open a Markdown note before chatting about wiki content.");return}this.sending=!0,w.disabled=!0,d.value="";let p={id:He(),role:"user",text:l,createdAt:new Date().toISOString(),pagePath:f.filePath,selectionExcerpt:f.selectionText||void 0},u={id:He(),role:"assistant",text:"",createdAt:new Date().toISOString(),pagePath:f.filePath,pending:!0};this.messages.push(p,u),this.render();try{let v=await this.plugin.backend.chat({sessionId:this.plugin.settings.autoResumeChatSession&&this.sessionId||void 0,pageContext:f,userPrompt:l,allowedToolsMode:this.plugin.settings.defaultAllowedToolsMode},T=>{T.type==="session"&&(this.sessionId=T.sessionId),T.type==="text_delta"&&(u.text+=T.text,u.pending=!1,this.render())});this.sessionId=v.sessionId||this.sessionId,u.text=v.text,u.pending=!1}catch(v){u.text=v instanceof Error?v.message:String(v),u.pending=!1}finally{this.sending=!1,w.disabled=!1,this.render()}}}};var m=require("obsidian");function W(){return`research-${Date.now()}-${Math.random().toString(16).slice(2,8)}`}function ft(s,r){return r.trim()?[`Topic: ${s}`,"","Research brief:",r.trim()].join(`
`):`Topic: ${s}`}var J=class extends m.ItemView{constructor(e,t){super(e);this.plugin=t;this.request=null;this.sessionId="";this.turns=[];this.topic="";this.userIntent="";this.followUpText="";this.draftMarkdown="";this.turnMode="orchestration";this.running=!1;this.finalizing=!1;this.statusText="";this.registeredSourceId="";this.registeredPath="";this.headerCollapsed=!1;this.controlsCollapsed=!1}getViewType(){return b}getDisplayText(){return"LLM-Wiki Deep Research"}getIcon(){return"microscope"}getState(){return{request:this.request??void 0,sessionId:this.sessionId||void 0,turns:this.turns,topic:this.topic,userIntent:this.userIntent,draftMarkdown:this.draftMarkdown,registeredSourceId:this.registeredSourceId||void 0,registeredPath:this.registeredPath||void 0,turnMode:this.turnMode,headerCollapsed:this.headerCollapsed,controlsCollapsed:this.controlsCollapsed}}async setState(e){let t=e.request;(t?!this.request||t.pageContext.filePath!==this.request.pageContext.filePath||t.topic!==this.request.topic||t.userIntent!==this.request.userIntent||t.pageContext.selectionText!==this.request.pageContext.selectionText:!1)&&t?(this.request=t,this.sessionId="",this.turns=[],this.followUpText="",this.draftMarkdown="",this.statusText="",this.registeredSourceId="",this.registeredPath="",this.turnMode="orchestration",this.headerCollapsed=!1,this.controlsCollapsed=!1):this.request=t??this.request,this.sessionId=e.sessionId??this.sessionId,this.turns=e.turns??this.turns,this.topic=e.topic??this.request?.topic??this.topic,this.userIntent=e.userIntent??this.request?.userIntent??this.userIntent,this.draftMarkdown=e.draftMarkdown??this.draftMarkdown,this.registeredSourceId=e.registeredSourceId??this.registeredSourceId,this.registeredPath=e.registeredPath??this.registeredPath,this.turnMode=e.turnMode??this.turnMode,this.headerCollapsed=e.headerCollapsed??this.headerCollapsed,this.controlsCollapsed=e.controlsCollapsed??this.controlsCollapsed,this.render()}async onOpen(){this.render()}async onClose(){this.contentEl.empty()}render(){let{contentEl:e}=this;e.empty(),e.addClass("lw2-chat-view"),e.addClass("lw2-deep-research-view");let t=e.createDiv({cls:"lw2-chat-header"}),i=t.createDiv({cls:"lw2-chat-header-top"});i.createEl("h2",{text:"LLM-Wiki Deep Research"});let n=i.createDiv({cls:"lw2-chat-actions"}),o=n.createEl("button",{text:this.headerCollapsed?"Show Details":"Hide Details"});o.onclick=()=>{this.headerCollapsed=!this.headerCollapsed,this.render()};let a=i.createEl("button",{cls:"clickable-icon lw2-chat-close-button",attr:{"aria-label":"Close deep research",title:"Close deep research"}});(0,m.setIcon)(a,"x"),a.onclick=async()=>{await this.leaf.setViewState({type:"empty"})},n.appendChild(a),this.headerCollapsed||(t.createEl("div",{cls:"lw2-chat-context",text:this.request?.pageContext.filePath||"No note context"}),this.sessionId&&t.createEl("div",{cls:"lw2-chat-context",text:`Claude session: ${this.sessionId}`}),this.statusText&&t.createEl("div",{cls:"lw2-chat-context",text:this.statusText}),t.createEl("div",{cls:"lw2-chat-context",text:this.turnMode==="orchestration"?"Mode: Planning research direction, scope, and methods":"Mode: Generating or revising the current research draft"}));let c=e.createDiv({cls:"lw2-deep-research-scroll"});if(this.request?.pageContext.selectionText.trim()){let R=c.createDiv({cls:"lw2-chat-message lw2-chat-message-user"});R.createDiv({cls:"lw2-chat-message-role",text:"selection"}),R.createEl("pre",{cls:"lw2-chat-message-body",text:j(this.request.pageContext.selectionText)})}let d=c.createDiv({cls:"lw2-chat-transcript lw2-deep-research-transcript"});this.turns.length||d.createEl("p",{cls:"lw2-chat-empty",text:"Deep research keeps a dedicated Claude session for scope confirmation, method planning, and full-draft revision before registration."});for(let R of this.turns){let $=d.createDiv({cls:`lw2-chat-message lw2-chat-message-${R.role}`});$.createDiv({cls:"lw2-chat-message-role",text:R.role}),$.createEl("pre",{cls:"lw2-chat-message-body",text:R.text||(R.pending?"...":"")})}let h=c.createDiv({cls:"lw2-chat-message lw2-chat-message-assistant"});h.createDiv({cls:"lw2-chat-message-role",text:"current draft"}),h.createEl("pre",{cls:"lw2-chat-message-body",text:this.draftMarkdown||"No draft yet."}),this.registeredSourceId&&h.createDiv({cls:"lw2-chat-message-context",text:`Registered as ${this.registeredSourceId}${this.registeredPath?` -> ${this.registeredPath}`:""}`});let w=e.createDiv({cls:"lw2-deep-research-footer"}),y=w.createDiv({cls:"lw2-chat-header-top"});y.createEl("div",{cls:"lw2-chat-context",text:this.turnMode==="orchestration"?"Planning mode":this.draftMarkdown.trim()?"Draft revision mode":"Draft generation mode"});let f=y.createDiv({cls:"lw2-chat-actions"}).createEl("button",{text:this.controlsCollapsed?"Show Controls":"Hide Controls"});f.onclick=()=>{this.controlsCollapsed=!this.controlsCollapsed,this.render()};let p=w.createDiv({cls:"lw2-chat-actions"}),u=w.createDiv({cls:"lw2-research-controls"}),v=w.createDiv({cls:"lw2-chat-actions"}),T=u.createEl("label",{text:"Topic"}),U=u.createEl("input",{type:"text",value:this.topic,cls:"lw2-research-input",attr:{placeholder:"Research topic"}});U.disabled=this.running||!!this.registeredSourceId,U.oninput=()=>{this.topic=U.value.trim()};let Ge=u.createEl("label",{text:this.turnMode==="draft_revision"?this.draftMarkdown.trim()?"Draft revision prompt":"Draft generation prompt":this.turns.length?"Planning follow-up prompt":"Research planning prompt"}),I=u.createEl("textarea",{cls:"lw2-modal-textarea",attr:{placeholder:this.turnMode==="draft_revision"?"Ask for a draft revision, restructure, expansion, or correction.":"Confirm scope, methods, exclusions, or next research steps."}});I.value=this.turns.length?this.followUpText:this.userIntent,I.disabled=this.running||!!this.registeredSourceId,I.oninput=()=>{this.turns.length?this.followUpText=I.value:this.userIntent=I.value};let Z=p.createEl("button",{text:"Plan Research"}),Q=p.createEl("button",{text:"Edit Draft"});this.turnMode==="orchestration"&&Z.addClass("mod-cta"),this.turnMode==="draft_revision"&&Q.addClass("mod-cta"),Z.disabled=this.running||this.finalizing||!!this.registeredSourceId,Q.disabled=this.running||this.finalizing||!!this.registeredSourceId,Z.onclick=()=>{this.turnMode="orchestration",this.render()},Q.onclick=()=>{this.turnMode="draft_revision",this.render()};let H=v.createEl("button",{text:this.turnMode==="draft_revision"?this.draftMarkdown.trim()?"Revise Draft":"Generate Draft":"Send Planning Turn"});H.addClass("mod-cta"),H.disabled=this.running||this.finalizing||!!this.registeredSourceId;let he=v.createEl("button",{text:"Register Research"});he.disabled=!this.draftMarkdown.trim()||this.running||this.finalizing||!!this.registeredSourceId,this.controlsCollapsed&&(T.style.display="none",U.style.display="none",Ge.style.display="none",I.style.display="none",p.style.display="none",H.style.display="none"),H.onclick=async()=>{if(this.running||this.finalizing||this.registeredSourceId)return;if(!this.topic.trim()){new m.Notice("Research topic is required.");return}let R=this.turns.length?this.followUpText.trim():ft(this.topic,this.userIntent),$=this.turns.length?this.followUpText.trim():this.userIntent.trim();!R.trim()&&(new m.Notice(this.turns.length?"Add a follow-up brief before continuing.":"Research brief may be empty, but topic is required."),this.turns.length)||(this.turnMode==="draft_revision"?await this.runDraftTurn(R.trim()||`Topic: ${this.topic}`,$):await this.runOrchestrationTurn(R.trim()||`Topic: ${this.topic}`,$))},he.onclick=async()=>{this.finalizing||!this.draftMarkdown.trim()||await this.registerCurrentDraft()}}async runOrchestrationTurn(e,t){if(!this.request||this.running)return;if(!this.topic.trim()){new m.Notice("Research topic is required.");return}if(!this.request.pageContext.filePath){new m.Notice("Open a Markdown note before running deep research.");return}this.running=!0,this.statusText="Discussing research direction...";let i={id:W(),role:"user",text:e,createdAt:new Date().toISOString(),pagePath:this.request.pageContext.filePath,selectionExcerpt:this.request.pageContext.selectionText||void 0},n={id:W(),role:"assistant",text:"",createdAt:new Date().toISOString(),pagePath:this.request.pageContext.filePath,pending:!0};this.turns.push(i,n),this.render();try{let o=await this.plugin.normalizePageContextForAiRead(this.request.pageContext),a=await this.plugin.backend.discussResearch({sessionId:this.sessionId||void 0,pageContext:o.filePath===this.request.pageContext.filePath?{...o,selectionText:this.request.pageContext.selectionText}:this.request.pageContext,topic:this.topic,userIntent:t,currentDraft:this.draftMarkdown||void 0},c=>{c.type==="session"&&(this.sessionId=c.sessionId),c.type==="tool_status"&&(this.statusText=c.message,this.render()),c.type==="text_delta"&&(n.text+=c.text,n.pending=!1,this.render())});this.sessionId=a.sessionId||this.sessionId,n.text=a.text,n.pending=!1,this.statusText="Research direction updated.",this.followUpText="",a.warnings.length&&new m.Notice(`Deep research warning: ${a.warnings.join(" | ")}`),await this.leaf.setViewState({type:b,active:!0,state:this.getState()})}catch(o){let a=o instanceof Error?o.message:String(o);n.text=`Deep research discussion failed: ${a}`,n.pending=!1,this.statusText=n.text,new m.Notice(n.text)}finally{this.running=!1,this.render()}}async runDraftTurn(e,t){if(!this.request||this.running)return;if(!this.topic.trim()){new m.Notice("Research topic is required.");return}if(!this.request.pageContext.filePath){new m.Notice("Open a Markdown note before running deep research.");return}this.running=!0,this.statusText=this.draftMarkdown.trim()?"Revising research draft...":"Generating research draft...";let i={id:W(),role:"user",text:e,createdAt:new Date().toISOString(),pagePath:this.request.pageContext.filePath,selectionExcerpt:this.request.pageContext.selectionText||void 0},n={id:W(),role:"assistant",text:"",createdAt:new Date().toISOString(),pagePath:this.request.pageContext.filePath,pending:!0};this.turns.push(i,n),this.render();try{let o=await this.plugin.normalizePageContextForAiRead(this.request.pageContext),a=await this.plugin.backend.generateResearchDraft({sessionId:this.sessionId||void 0,pageContext:o.filePath===this.request.pageContext.filePath?{...o,selectionText:this.request.pageContext.selectionText}:this.request.pageContext,topic:this.topic,userIntent:t,currentDraft:this.draftMarkdown||void 0},c=>{c.type==="session"&&(this.sessionId=c.sessionId),c.type==="tool_status"&&(this.statusText=c.message,this.render()),c.type==="text_delta"&&(n.text+=c.text,n.pending=!1,this.render())});this.sessionId=a.sessionId||this.sessionId,n.text=a.markdownBody,n.pending=!1,this.draftMarkdown=a.markdownBody,this.statusText=this.draftMarkdown.trim()?"Draft updated.":"Draft generated.",this.followUpText="",a.warnings.length&&new m.Notice(`Deep research warning: ${a.warnings.join(" | ")}`),await this.leaf.setViewState({type:b,active:!0,state:this.getState()})}catch(o){let a=o instanceof Error?o.message:String(o);n.text=`Deep research failed: ${a}`,n.pending=!1,this.statusText=n.text,new m.Notice(n.text)}finally{this.running=!1,this.render()}}async registerCurrentDraft(){if(this.draftMarkdown.trim()){this.finalizing=!0,this.statusText="Registering research source...",this.render();try{let e=await this.plugin.registerDeepResearchDraft(this.topic,this.draftMarkdown);this.registeredSourceId=e.source_id,this.registeredPath=e.path,this.statusText=`Registered as ${e.source_id}`,this.turns.push({id:W(),role:"system",text:`Registered research as ${e.source_id}. Next step: /lw2:compile`,createdAt:new Date().toISOString(),pagePath:this.request?.pageContext.filePath??null}),await this.leaf.setViewState({type:b,active:!0,state:this.getState()}),new m.Notice(`Research registered as ${e.source_id}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.statusText=`Deep research registration failed: ${t}`,new m.Notice(this.statusText)}finally{this.finalizing=!1,this.render()}}}};var O=require("obsidian");var X=class extends O.ItemView{constructor(e,t){super(e);this.plugin=t;this.request=null;this.responseText="";this.loading=!1;this.errorText="";this.executed=!1}getViewType(){return L}getDisplayText(){return"LLM-Wiki Fast Research"}getIcon(){return"bot"}getState(){return{}}async setState(e){this.request=e.request??null,this.responseText="",this.errorText="",this.executed=!1,this.render(),this.request&&await this.runResearch()}async onOpen(){this.render()}async onClose(){this.contentEl.empty()}render(){let{contentEl:e}=this;e.empty(),e.addClass("lw2-fast-research-view");let t=e.createDiv({cls:"lw2-chat-header"}),i=t.createDiv({cls:"lw2-chat-header-top"});i.createEl("h2",{text:"LLM-Wiki Fast Research"});let n=i.createEl("button",{cls:"clickable-icon lw2-chat-close-button",attr:{"aria-label":"Close fast research",title:"Close fast research"}});if((0,O.setIcon)(n,"x"),n.onclick=async()=>{await this.leaf.setViewState({type:"empty"})},t.createEl("div",{cls:"lw2-chat-context",text:this.request?.pageContext.filePath||"No note context"}),!this.request){e.createEl("p",{cls:"lw2-chat-empty",text:"Trigger Fast Research from a text selection in a Markdown editor."});return}let o=e.createDiv({cls:"lw2-chat-message lw2-chat-message-user"});o.createDiv({cls:"lw2-chat-message-role",text:"selection"}),o.createEl("pre",{cls:"lw2-chat-message-body",text:j(this.request.pageContext.selectionText)});let a=e.createDiv({cls:"lw2-chat-message lw2-chat-message-assistant"});if(a.createDiv({cls:"lw2-chat-message-role",text:"fast research"}),a.createEl("pre",{cls:"lw2-chat-message-body",text:this.loading?"Running fast research...":this.errorText||this.responseText||"No response yet."}),!this.loading&&!this.errorText&&this.responseText.trim()){let c=a.createDiv({cls:"lw2-chat-message-actions"});c.createEl("button",{text:"Save Insight"}).onclick=()=>{new A(this.plugin,"Fast Research Insight",this.responseText).open()}}}async runResearch(){if(!(!this.request||this.loading||this.executed)){this.loading=!0,this.errorText="",this.render();try{let e=await this.plugin.normalizePageContextForAiRead(this.request.pageContext),t=await this.plugin.backend.chat({pageContext:e.filePath===this.request.pageContext.filePath?{...e,selectionText:this.request.pageContext.selectionText}:this.request.pageContext,userPrompt:this.request.userPrompt,allowedToolsMode:"research"},()=>{});this.responseText=t.text}catch(e){let t=e instanceof Error?e.message:String(e);this.errorText=`Fast research failed: ${t}`,new O.Notice(this.errorText)}finally{this.executed=!0,this.loading=!1,this.render()}}}};var K=class extends g.Plugin{constructor(){super(...arguments);this.registryIndex=de()}async onload(){await this.loadSettings(),this.backend=new B(this.settings),await this.refreshRegistryIndex(),this.registerView(P,e=>new N(e,this)),this.registerView(b,e=>new J(e,this)),this.registerView(L,e=>new X(e,this)),this.addSettingTab(new z(this)),Ae(this),this.addRibbonIcon("bot","Open LLM-Wiki chat",async()=>{await this.activateChatSidebar()}),this.addCommand({id:"lw2-show-plugin-status",name:"Show LLM-Wiki plugin status",callback:()=>{let e=this.settings.runtimeRoot||"(not configured)",t=this.detectVaultRoot()||"(unavailable)";new g.Notice(`LLM-Wiki Obsidian ready. Runtime root: ${e}; vault root: ${t}`)}}),this.addCommand({id:"lw2-run-backend-smoke-test",name:"Run Claude backend smoke test on current note",callback:async()=>{let e=await this.getCurrentPageContextForAiRead();if(!e.filePath){new g.Notice("Open a Markdown note before running the Claude backend smoke test.");return}if(!this.settings.runtimeRoot.trim()){new g.Notice("Configure the LLM-Wiki runtime root in plugin settings first.");return}new g.Notice("Running Claude backend smoke test...");try{let i=(await this.backend.chat({pageContext:e,userPrompt:"Summarize the current note in two short bullet points.",allowedToolsMode:this.settings.defaultAllowedToolsMode},()=>{})).text.replace(/\s+/g," ").slice(0,120)||"(empty response)";new g.Notice(`Claude backend OK: ${i}`)}catch(t){let i=t instanceof Error?t.message:String(t);new g.Notice(`Claude backend failed: ${i}`)}}}),this.registerEditorExtension(Oe({isEnabled:()=>this.settings.showSourceTrustBadges,getRegistryIndex:()=>this.registryIndex,openSourceTrustModal:e=>this.openSourceTrustModal(e)})),this.registerEditorExtension(ke({isEnabled:()=>this.settings.showConfidenceDecorations})),this.registerMarkdownPostProcessor(qe(this)),this.registerMarkdownPostProcessor($e({isEnabled:()=>this.settings.showConfidenceDecorations})),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>{this.refreshOpenChatViews()})),this.registerEvent(this.app.vault.on("modify",async e=>{e.path==="raw/source_registry.md"&&await this.refreshRegistryIndex(),(e.path.startsWith("wiki/")||e.path==="raw/source_registry.md")&&this.refreshOpenChatViews()}))}onunload(){for(let e of this.app.workspace.getLeavesOfType(P))e.setViewState({type:"empty"});for(let e of this.app.workspace.getLeavesOfType(b))e.setViewState({type:"empty"});for(let e of this.app.workspace.getLeavesOfType(L))e.setViewState({type:"empty"})}async loadSettings(){let e=await this.loadData()??{};this.settings={...Fe,...e,runtimeRoot:Ue(e.runtimeRoot??"",e.repoRoot)}}async saveSettings(){await this.saveData(this.settings),this.backend=new B(this.settings),await this.refreshRegistryIndex(),this.refreshOpenChatViews()}detectVaultRoot(){return this.app.vault.adapter.getBasePath?.()??""}getPreferredMarkdownView(){return We(this.app.workspace.getActiveViewOfType(g.MarkdownView),this.app.workspace.getMostRecentLeaf(),this.app.workspace.getLeavesOfType("markdown"))}getCurrentPageContext(e){return be(e??this.getPreferredMarkdownView(),this.settings.autoSaveBeforeAiRead)}async getCurrentPageContextForAiRead(e){let t=e??this.getPreferredMarkdownView(),i=t;return i&&this.settings.autoSaveBeforeAiRead==="always"&&i.getViewData()!==i.data&&typeof i.save=="function"&&await i.save(),this.getCurrentPageContext(t)}async normalizePageContextForAiRead(e){let t=this.getPreferredMarkdownView();return e?t?.file?.path&&t.file.path===e.filePath?this.getCurrentPageContextForAiRead(t):e:this.getCurrentPageContextForAiRead(t)}async refreshRegistryIndex(){let e=this.app.vault.getAbstractFileByPath("raw/source_registry.md");if(!(e instanceof g.TFile)){this.registryIndex=de();return}let t=await this.app.vault.cachedRead(e);this.registryIndex=Ne(t),this.refreshVisibleMarkdownViews()}async activateChatSidebar(){let e=this.app.workspace.activeLeaf,t=e&&e.view instanceof g.MarkdownView?e:this.app.workspace.getLeavesOfType("markdown").find(n=>n.view instanceof g.MarkdownView)??null,i=await this.app.workspace.ensureSideLeaf(P,"right",{active:!1,reveal:!0});t&&this.app.workspace.setActiveLeaf(t,{focus:!0}),this.refreshOpenChatViews()}async openDeepResearchView(e){let t=this.app.workspace.getLeaf(!0);await t.setViewState({type:b,active:!0,state:{request:e}}),await this.app.workspace.revealLeaf(t)}async openFastResearchView(e){let t=this.app.workspace.getLeaf(!0);await t.setViewState({type:L,active:!0,state:{request:e}}),await this.app.workspace.revealLeaf(t)}refreshOpenChatViews(){for(let e of this.app.workspace.getLeavesOfType(P))e.view instanceof N&&e.view.refresh()}refreshVisibleMarkdownViews(){for(let e of this.app.workspace.getLeavesOfType("markdown")){if(!(e.view instanceof g.MarkdownView))continue;e.view.editor?.refresh?.()}}openCurrentPageSourceTrustModal(){let e=this.getCurrentPageContext();if(!e.sources.length){new g.Notice("Current note has no page-level sources in frontmatter.");return}this.openSourceTrustModal(e.sources)}openSourceTrustModal(e){let t=e.map(i=>this.registryIndex.byId.get(i)).filter(i=>!!i);if(!t.length){new g.Notice("None of the requested sources are present in the current registry index.");return}new Y(this,t).open()}async saveInsight(e,t,i=!1){this.ensureRuntimeRoot();let n=this.getVaultRoot(),o=await re(this.settings.insightTempDir,"lw2-insight",t),a=["--title",e,"--body-file",o];i&&a.push("--confirm-risk");let c=await D(this.settings,n,"scripts/lw2-save-insight",a);if(c.data)return await this.refreshRegistryIndex(),c.data;throw new Error(c.stderr.trim()||c.stdout.trim()||"lw2-save-insight failed.")}async updateSourceTrust(e,t,i){this.ensureRuntimeRoot();let n=this.getVaultRoot(),o=e.flatMap(c=>["--source",c]);o.push("--trust",t),i.trim()&&o.push("--reason",i.trim());let a=await D(this.settings,n,"scripts/lw2-source-trust",o);if(!a.data||a.code!==0)throw new Error(a.stderr.trim()||a.stdout.trim()||"lw2-source-trust failed.");return await this.refreshRegistryIndex(),a.data}async registerDeepResearchDraft(e,t){this.ensureRuntimeRoot();let i=this.getVaultRoot(),n=await re(this.settings.deepResearchTempDir,"lw2-research",t),o=await D(this.settings,i,"scripts/lw2-deep-research",["--topic",e,"--body-file",n]);if(!o.data||o.code!==0)throw new Error(o.stderr.trim()||o.stdout.trim()||"lw2-deep-research failed.");return await this.refreshRegistryIndex(),o.data}async runCompilePreflight(){this.ensureRuntimeRoot();let e=this.getVaultRoot(),t=await D(this.settings,e,"scripts/lw2-compile",[]);if(!t.data||t.code!==0)throw new Error(t.stderr.trim()||t.stdout.trim()||"lw2-compile preflight failed.");return await this.refreshRegistryIndex(),t.data}async runLintPass(e=!1){this.ensureRuntimeRoot();let t=this.getVaultRoot(),i=e?["--dry-run"]:[],n=await D(this.settings,t,"scripts/lw2-lint",i);if(!n.data||n.code!==0)throw new Error(n.stderr.trim()||n.stdout.trim()||"lw2-lint failed.");return await this.refreshRegistryIndex(),this.refreshOpenChatViews(),n.data}getVaultRoot(){return this.detectVaultRoot()}ensureRuntimeRoot(){if(!this.settings.runtimeRoot.trim())throw new Error("Configure the LLM-Wiki runtime root in plugin settings first.");if(!this.detectVaultRoot())throw new Error("Could not detect the current Obsidian vault root.")}};