var USn=Object.create;var Mq=Object.defineProperty;var BSn=Object.getOwnPropertyDescriptor;var jSn=Object.getOwnPropertyNames;var HSn=Object.getPrototypeOf,WSn=Object.prototype.hasOwnProperty;var tot=t=>{throw TypeError(t)};var VSn=(t,e,n)=>e in t?Mq(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var yi=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Vo=(t,e)=>{for(var n in e)Mq(t,n,{get:e[n],enumerable:!0})},not=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jSn(e))!WSn.call(t,o)&&o!==n&&Mq(t,o,{get:()=>e[o],enumerable:!(r=BSn(e,o))||r.enumerable});return t};var R=(t,e,n)=>(n=t!=null?USn(HSn(t)):{},not(e||!t||!t.__esModule?Mq(n,"default",{value:t,enumerable:!0}):n,t)),qSn=t=>not(Mq({},"__esModule",{value:!0}),t);var A=(t,e,n)=>VSn(t,typeof e!="symbol"?e+"":e,n),DTe=(t,e,n)=>e.has(t)||tot("Cannot "+n);var se=(t,e,n)=>(DTe(t,e,"read from private field"),n?n.call(t):e.get(t)),It=(t,e,n)=>e.has(t)?tot("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),kt=(t,e,n,r)=>(DTe(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Je=(t,e,n)=>(DTe(t,e,"access private method"),n);var _re=(t,e,n,r)=>({set _(o){kt(t,e,o,n)},get _(){return se(t,e,r)}});var pot=yi(bo=>{"use strict";var Oq=Symbol.for("react.element"),KSn=Symbol.for("react.portal"),GSn=Symbol.for("react.fragment"),ZSn=Symbol.for("react.strict_mode"),YSn=Symbol.for("react.profiler"),JSn=Symbol.for("react.provider"),XSn=Symbol.for("react.context"),QSn=Symbol.for("react.forward_ref"),eCn=Symbol.for("react.suspense"),tCn=Symbol.for("react.memo"),nCn=Symbol.for("react.lazy"),rot=Symbol.iterator;function rCn(t){return t===null||typeof t!="object"?null:(t=rot&&t[rot]||t["@@iterator"],typeof t=="function"?t:null)}var sot={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},aot=Object.assign,lot={};function EF(t,e,n){this.props=t,this.context=e,this.refs=lot,this.updater=n||sot}EF.prototype.isReactComponent={};EF.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};EF.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function cot(){}cot.prototype=EF.prototype;function FTe(t,e,n){this.props=t,this.context=e,this.refs=lot,this.updater=n||sot}var zTe=FTe.prototype=new cot;zTe.constructor=FTe;aot(zTe,EF.prototype);zTe.isPureReactComponent=!0;var oot=Array.isArray,uot=Object.prototype.hasOwnProperty,UTe={current:null},dot={key:!0,ref:!0,__self:!0,__source:!0};function fot(t,e,n){var r,o={},i=null,s=null;if(e!=null)for(r in e.ref!==void 0&&(s=e.ref),e.key!==void 0&&(i=""+e.key),e)uot.call(e,r)&&!dot.hasOwnProperty(r)&&(o[r]=e[r]);var a=arguments.length-2;if(a===1)o.children=n;else if(1<a){for(var l=Array(a),c=0;c<a;c++)l[c]=arguments[c+2];o.children=l}if(t&&t.defaultProps)for(r in a=t.defaultProps,a)o[r]===void 0&&(o[r]=a[r]);return{$$typeof:Oq,type:t,key:i,ref:s,props:o,_owner:UTe.current}}function oCn(t,e){return{$$typeof:Oq,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function BTe(t){return typeof t=="object"&&t!==null&&t.$$typeof===Oq}function iCn(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var iot=/\/+/g;function $Te(t,e){return typeof t=="object"&&t!==null&&t.key!=null?iCn(""+t.key):e.toString(36)}function Sre(t,e,n,r,o){var i=typeof t;(i==="undefined"||i==="boolean")&&(t=null);var s=!1;if(t===null)s=!0;else switch(i){case"string":case"number":s=!0;break;case"object":switch(t.$$typeof){case Oq:case KSn:s=!0}}if(s)return s=t,o=o(s),t=r===""?"."+$Te(s,0):r,oot(o)?(n="",t!=null&&(n=t.replace(iot,"$&/")+"/"),Sre(o,e,n,"",function(c){return c})):o!=null&&(BTe(o)&&(o=oCn(o,n+(!o.key||s&&s.key===o.key?"":(""+o.key).replace(iot,"$&/")+"/")+t)),e.push(o)),1;if(s=0,r=r===""?".":r+":",
1. Never mention that you do not have access to something. Always rely on the user provided context.
2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there's no relevant information in the vault, just say so.
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
6. Always use $'s instead of \\[ etc. for LaTeX equations.
7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
9. When showing **web** image links, use  format and do not wrap them in \` \`.
10. When generating a table, format as github markdown tables, however, for table headings, immediately add ' |' after the table heading.
11. Always respond in the language of the user's query.
12. Do NOT mention the additional context provided such as getCurrentTime and getTimeRangeMs if it's irrelevant to the user message.
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.
14. YouTube URLs: If the user provides YouTube URLs in their message, transcriptions will be automatically fetched and provided to you. You don't need to do anything special - just use the transcription content if available.`,Yot=`Return the new note content or canvas JSON in <writeFile> tags.
`,Fq="note_context",tm="selected_text",DF="web_selected_text",zq="variable",NO="variable_note",Uq="embedded_pdf",tIe="embedded_note",Bq="dataview_block",nIe="web_tab_context",Rre="active_web_tab",rIe="youtube_video_context",xC="{activeWebTab}",Nre=6e3,oIe=.4,iIe=448e3,Lre=3e4,p0n=30,sIe=5*60*1e3,bh={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree",COMPACTING:"Compacting"},Jot=2e4,Mre={TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},Xot=131072,T_=(m=>(m.OPENROUTERAI="openrouterai",m.OPENAI="openai",m.OPENAI_FORMAT="3rd party (openai-format)",m.ANTHROPIC="anthropic",m.GOOGLE="google",m.XAI="xai",m.GROQ="groq",m.OLLAMA="ollama",m.LM_STUDIO="lm-studio",m.COPILOT_PLUS="copilot-plus",m.MISTRAL="mistralai",m.DEEPSEEK="deepseek",m.COHEREAI="cohereai",m.SILICONFLOW="siliconflow",m))(T_||{}),$F=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,plusExclusive:!0,capabilities:["vision"]},{name:"google/gemini-2.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"google/gemini-3.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gpt-5.5",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5.4-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"claude-sonnet-4-6",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-flash-lite",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"google/gemini-3.1-pro-preview",provider:"openrouterai",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"openai/gpt-5.5",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"openai/gpt-5.4-mini",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"grok-4.3",provider:"xai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"x-ai/grok-4.3",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"claude-opus-4-7",provider:"anthropic",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-haiku-4-5",provider:"anthropic",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-pro-preview",provider:"google",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-2.5-pro",provider:"google",enabled:!1,isBuiltIn:!0,capabilities:["vision"]},{name:"deepseek-chat",provider:"deepseek",enabled:!1,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!1,isBuiltIn:!0,capabilities:["reasoning"]},{name:"deepseek-ai/DeepSeek-V3",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1"},{name:"deepseek-ai/DeepSeek-R1",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1",capabilities:["reasoning"]}],nv={openrouterai:{label:"OpenRouter",host:"https://openrouter.ai/api/v1/",curlBaseURL:"https://openrouter.ai/api/v1",keyManagementURL:"https://openrouter.ai/keys",testModel:"openai/gpt-5.4-mini"},google:{label:"Gemini",host:"https://generativelanguage.googleapis.com",curlBaseURL:"https://generativelanguage.googleapis.com/v1beta",keyManagementURL:"https://makersuite.google.com/app/apikey",testModel:"gemini-2.5-flash"},anthropic:{label:"Anthropic",host:"https://api.anthropic.com/",curlBaseURL:"https://api.anthropic.com",keyManagementURL:"https://console.anthropic.com/settings/keys",testModel:"claude-
Copyright (c) 2026 Steph Ango (@kepano)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
`,g0n=String.raw`---
name: obsidian-markdown
description: Create and edit Obsidian-specific Markdown syntax, including wikilinks, embeds, block references, callouts, properties, tags, and comments. Use for Obsidian notes when these extensions matter; ordinary Markdown is assumed knowledge.
license: MIT
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${1}"
copilot-upstream-revision: "${cI}"
---
# Obsidian Markdown
Use Obsidian-specific syntax accurately. Do not spend tokens explaining ordinary
CommonMark or GFM unless the user asks.
## Workflow
1. Preserve existing frontmatter keys and formatting when editing a note.
2. Use wikilinks for vault notes and Markdown links for external URLs.
3. Use embeds, callouts, properties, tags, comments, and block references only
when they improve the requested note.
4. Check link targets, YAML validity, and block IDs after editing.
5. Read the focused reference file when the task needs more syntax detail.
## Wikilinks and block references
~~~markdown
[[Note Name]]
[[Note Name|Display Text]]
[[Note Name#Heading]]
[[Note Name#^block-id]]
[[#Heading in this note]]
This paragraph is addressable. ^block-id
~~~
Put a block ID on its own line after a list or quote block.
## Embeds
Prefix a wikilink with <code>!</code>:
~~~markdown
![[Note Name]]
![[Note Name#Heading]]
![[image.png|300]]
![[document.pdf#page=3]]
~~~
See [Embeds](references/EMBEDS.md) for media, PDF, and query forms.
## Callouts
~~~markdown
> [!warning] Custom title
> Important content.
> [!faq]- Collapsed by default
> Foldable content.
~~~
See [Callouts](references/CALLOUTS.md) for types, aliases, folding, and nesting.
## Properties, tags, and comments
~~~yaml
---
title: My Note
date: 2026-07-21
tags:
- project
aliases:
- Alternate Name
related: "[[Other Note]]"
---
~~~
Quote wikilinks used as YAML values. See
[Properties](references/PROPERTIES.md) for supported property types and tag rules.
Use <code>#nested/tag</code> for inline tags. Hide content from reading view with
<code>%%inline comments%%</code> or a matching pair of <code>%%</code> markers on
separate lines.
## Attribution
Adapted from <code>kepano/obsidian-skills</code> at revision
<code>${cI}</code>. See <code>LICENSE</code>.
`,y0n=String.raw`# Callouts reference
## Folding and nesting
~~~markdown
> [!faq]- Collapsed by default
> Hidden until expanded.
> [!faq]+ Expanded by default
> Visible but collapsible.
> [!question] Outer
> > [!note] Inner
> > Nested content.
~~~
## Built-in types
| Type | Aliases |
| --- | --- |
| note | — |
| abstract | summary, tldr |
| info | — |
| todo | — |
| tip | hint, important |
| success | check, done |
| question | help, faq |
| warning | caution, attention |
| failure | fail, missing |
| danger | error |
| bug | — |
| example | — |
| quote | cite |
`,w0n=String.raw`# Embeds reference
~~~markdown
![[Note Name]]
![[Note Name#Heading]]
![[Note Name#^block-id]]
![[image.png]]
![[image.png|640x480]]
![[image.png|300]]
![[audio.mp3]]
![[video.mp4]]
![[document.pdf]]
![[document.pdf#page=3]]
![[document.pdf#height=400]]
~~~
A list embed needs a block ID after the list. An embedded search uses an
Obsidian query block:
~~~~markdown
~~~query
tag:#project status:done
~~~
~~~~
`,v0n=String.raw`# Properties reference
Properties are YAML frontmatter at the very start of a note.
| Property type | Example |
| --- | --- |
| Text | <code>title: My title</code> |
| Number | <code>rating: 4.5</code> |
| Checkbox | <code>completed: true</code> |
| Date | <code>date: 2026-07-21</code> |
| Date and time | <code>due: 2026-07-21T14:30:00</code> |
| List | <code>tags: [one, two]</code> or a YAML list |
| Link | <code>related: "[[Other Note]]"</code> |
Obsidian reserves <code>tags</code>, <code>aliases</code>, and
<code>cssclasses</code> for their built-in behaviors. Tags may contain letters,
numbers (not as the first character), underscores, hyphens, and forward slashes.
Prefer YAML lists when a property naturally has multiple values.
`,b0n=String.raw`---
name: obsidian-bases
description: Create and edit Obsidian Bases (.base files) with valid YAML schemas, filters, formulas, properties, summaries, and views. Use for database-like Obsidian views or when the user mentions Bases, .base files, table/card/list views, filters, formulas, or summaries.
license: MIT
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${1}"
copilot-upstream-revision: "${cI}"
---
# Obsidian Bases
## Workflow
1. Read the existing <code>.base</code> file before editing it.
2. Define global scope with <code>filters</code>.
3. Add computed values under <code>formulas</code> only when needed.
4. Configure property display names and one or more views.
5. Validate YAML, formula references, quoting, and date/duration operations.
6. Open or query the Base in Obsidian when the CLI is available.
is_overdue: 'if(due, date(due) < today() && status != "done", false)'
properties:
formula.days_until_due:
displayName: "Days Until Due"
views:
- type: table
name: Active
filters:
and:
- 'status != "done"'
order:
- file.name
- status
- due
- formula.days_until_due
groupBy:
property: status
direction: ASC
~~~
## Daily notes index
~~~yaml
filters:
and:
- file.inFolder("Daily Notes")
- '/^\d{4}-\d{2}-\d{2}$/.matches(file.basename)'
formulas:
day_of_week: 'date(file.basename).format("dddd")'
word_estimate: '(file.size / 5).round(0)'
views:
- type: table
name: Recent notes
limit: 30
order:
- file.name
- formula.day_of_week
- formula.word_estimate
- file.mtime
~~~
`,S0n=String.raw`---
name: json-canvas
description: Create and edit JSON Canvas (.canvas) files with valid nodes, edges, groups, colors, layout, IDs, and referential integrity. Use for Obsidian Canvas files, visual maps, flowcharts, project boards, or any request involving the JSON Canvas format.
license: MIT
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${1}"
copilot-upstream-revision: "${cI}"
---
# JSON Canvas
Follow JSON Canvas 1.0. A <code>.canvas</code> document contains top-level
<code>nodes</code> and <code>edges</code> arrays.
## Workflow
1. Parse the existing JSON before editing it.
2. Generate a unique lowercase 16-character hexadecimal ID for each new node
or edge.
3. Position nodes without overlap and preserve intentional existing layout.
4. Point every edge at existing node IDs.
5. Serialize valid JSON and run the validation checklist below.
## Nodes
Every node requires <code>id</code>, <code>type</code>, <code>x</code>,
<code>y</code>, <code>width</code>, and <code>height</code>.
Array order controls z-index: earlier nodes are behind later nodes. Coordinates
may be negative. Position is the top-left corner, x increases right, and y
increases down.
~~~json
{
"id": "6f0ad84f44ce9c17",
"type": "text",
"x": 0,
"y": 0,
"width": 360,
"height": 180,
"text": "# Main idea\n\nDetails",
"color": "5"
}
~~~
Use actual JSON newline escapes in text values. Do not double-escape them into
literal backslash-n text.
## Edges
Every edge requires <code>id</code>, <code>fromNode</code>, and
<code>toNode</code>. Optional sides are <code>top</code>, <code>right</code>,
<code>bottom</code>, or <code>left</code>. Optional ends are <code>none</code>
or <code>arrow</code>.
~~~json
{
"id": "0123456789abcdef",
"fromNode": "6f0ad84f44ce9c17",
"fromSide": "right",
"toNode": "a1b2c3d4e5f67890",
"toSide": "left",
"toEnd": "arrow",
"label": "leads to"
}
~~~
## Colors and layout
A color is a hex string or preset <code>"1"</code> through
<code>"6"</code>. Presets deliberately do not define exact hex colors. Leave
50–100 px between nodes, 20–50 px padding inside groups, and align to a simple
grid when creating a new layout.
## Validation checklist
- JSON parses successfully.
- IDs are unique across nodes and edges.
- Every <code>fromNode</code> and <code>toNode</code> exists in
<code>nodes</code>.
- Each node type has its required content field.
- Sides, ends, and colors use allowed values.
- Nodes do not unintentionally overlap and group children sit inside bounds.
Read [Examples](references/EXAMPLES.md) for complete connected and grouped
canvases.
## Attribution
Adapted from <code>kepano/obsidian-skills</code> at revision
<code>${cI}</code>. See <code>LICENSE</code>.
`,C0n=String.raw`# JSON Canvas examples
## Connected notes
~~~json
{
"nodes": [
{
"id": "8a9b0c1d2e3f4a5b",
"type": "text",
"x": 0,
"y": 0,
"width": 300,
"height": 140,
"text": "# Main idea"
},
{
"id": "1a2b3c4d5e6f7a8b",
"type": "file",
"x": 400,
"y": 0,
"width": 300,
"height": 200,
"file": "Notes/Supporting note.md",
"subpath": "#Evidence"
}
],
"edges": [
{
"id": "3c4d5e6f7a8b9c0d",
"fromNode": "8a9b0c1d2e3f4a5b",
"fromSide": "right",
"toNode": "1a2b3c4d5e6f7a8b",
"toSide": "left",
"label": "supported by"
}
]
}
~~~
## Grouped board
~~~json
{
"nodes": [
{
"id": "5e6f7a8b9c0d1e2f",
"type": "group",
"x": 0,
"y": 0,
"width": 320,
"height": 500,
"label": "In progress",
"color": "3"
},
{
"id": "8b9c0d1e2f3a4b5c",
"type": "text",
"x": 30,
"y": 60,
"width": 260,
"height": 100,
"text": "## Task\n\nImplement the feature"
}
],
"edges": []
}
~~~
`,k0n=String.raw`---
name: obsidian-cli
description: Use the official Obsidian CLI when a task needs Obsidian's running app, index, configured features, command registry, or developer runtime. Use for currently open notes and tabs, workspace state, daily notes, typed properties, tasks, links/backlinks, Bases queries, template resolution, link-aware moves, plugin commands, and plugin/theme debugging; do not use it for ordinary filesystem operations.
license: MIT
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${2}"
copilot-upstream-revision: "${cI}"
---
# Obsidian CLI
Use the CLI only for behavior that depends on Obsidian's running application,
indexes, settings, command registry, or developer runtime. Use normal shell
filesystem tools for ordinary file reads, writes, directory listing, and text
search.
## Capability probe and fallback
Copilot exposes the terminal-capable executable from the running Obsidian
installation as <code>COPILOT_OBSIDIAN_CLI</code> when it can resolve one.
Prefer that exact path over <code>obsidian</code> from <code>PATH</code>, and
always invoke it as a quoted executable rather than constructing a command
string. Before relying on the CLI, probe it using the active shell:
[ $? -eq 0 ] || die "Could not reach the Copilot relay. $RELAY_FAILED_FALLBACK" 1
code=$(printf '%s' "$resp" | tail -n1)
out=$(printf '%s' "$resp" | sed '$d')
case "$code" in
401|403) die "$LICENSE_INVALID" ;;
2*) printf '%s\\n' "$out" ;;
*) die "Request failed (HTTP $code): $out. $RELAY_FAILED_FALLBACK" 1 ;;
esac
}
`}function Vre(t){return`'${t.replace(/'/g,"''")}'`}function wit(){return`# Windows (PowerShell) sibling of the matching .sh script, launched by the .cmd
# wrapper next to it. Calls the Brevilabs relay and prints the JSON result to
# stdout. Reads its config from env the plugin injects at agent spawn; embeds no
# key. Targets Windows PowerShell 5.1 (.NET BCL only) so it needs no Node.
`}function vit(t){let e="/absolute/path/to/this/skill/directory";return`## How to run
Find the absolute path to this SKILL.md file on disk, then run the script next
to it that matches the operating system. No extra runtime is needed — \`sh\`
(macOS/Linux) and \`cmd\`/PowerShell (Windows) are always present.
On macOS or Linux:
\`\`\`bash
sh "${e}/${t.shFile}" "${t.argPlaceholder}"
\`\`\`
On Windows, run the \`.cmd\` wrapper. In PowerShell you must prefix it with the
call operator \`&\` (PowerShell treats a quoted path on its own as a string and
won't run it); from cmd, run the quoted path without the \`&\`:
\`\`\`powershell
& "${e}/${t.cmdFile}" "${t.argPlaceholder}"
\`\`\`
${t.extraNote?`
${t.extraNote}
`:""}
Both print the result to stdout.`}function Kre(t){let[e,n]=t.arg,r=t.scriptFile.replace(/\.sh$/,".cmd"),o=t.scriptFile.replace(/\.sh$/,".ps1"),i=6,s=t.selfHostMode==="search"?`if [ "$SELF_HOST" = "1" ]; then
[ -n "$SELF_HOST_URL" ] && [ -n "$SELF_HOST_TOKEN" ] || die "Copilot self-host web search is unavailable for this session." 1
`:t.selfHostMode==="deny"?`if [ "$SELF_HOST" = "1" ]; then
die "Self-Host mode does not support fetching a specific page. Do not use a native web-fetch tool; use copilot-web-search when search results are sufficient, otherwise tell the user page fetching is unavailable." 1
Die 'Self-Host mode does not support fetching a specific page. Do not use a native web-fetch tool; use copilot-web-search when search results are sufficient, otherwise tell the user page fetching is unavailable.' 1
`}]}}function BF(t){let e=!t.search&&!t.documents?UF:[...t.documents?UF.filter(n=>n!==_it):UF,...t.search?[Cit]:[],...t.documents?[kit]:[]];return{seed:e,prune:_h.filter(n=>!e.includes(n)).map(n=>n.name)}}var qre,td,$O,FO,Wq,Vq,qq,pit,mit,hit,git,bit,E0n,M0n,ait,_it,O0n,R0n,lit,rv,cit,uit,lIe,N0n,UF,dit,fit,xit,Sit,L0n,D0n,$0n,F0n,Cit,kit,_h,uI=b(()=>{DO();rit();sit();qre=[{name:"symposium-publish"}],td={licenseKey:"COPILOT_PLUS_LICENSE_KEY",baseUrl:"COPILOT_API_BASE_URL",userId:"COPILOT_USER_ID",clientVersion:"COPILOT_CLIENT_VERSION"},$O="COPILOT_MIYO_SEARCH_SCOPE",FO="COPILOT_MIYO_SEARCH_FOLDER",Wq="COPILOT_SELF_HOST_WEB_SEARCH",Vq="COPILOT_SELF_HOST_WEB_SEARCH_URL",qq="COPILOT_SELF_HOST_WEB_SEARCH_TOKEN",pit="Copilot Plus is not active, so this skill is unavailable — do not retry it. Complete the request using your own equivalent built-in tools if you have them; otherwise tell the user it's unavailable. Never refuse or tell the user they are blocked.",mit="You may also add one short, friendly note that Copilot Plus offers higher-quality web, PDF, YouTube, and X tools — get a license key at https://www.obsidiancopilot.com to access them.",hit="Your Copilot Plus license is inactive or expired, so this skill is unavailable — do not retry it. Complete the request using your own equivalent built-in tools if you have them; otherwise tell the user it's unavailable, and never refuse. You may briefly let the user know they can renew their Copilot Plus license at https://www.obsidiancopilot.com to restore the higher-quality versions of these tools.",git="If you have your own equivalent built-in tool for this, use it to complete the request; otherwise tell the user it could not be completed.";bit=`## If Copilot Plus is not active
If the script exits saying Copilot Plus is unavailable, do NOT retry it. Do what
the message says: fall back to your own equivalent built-in capability to handle
the request when you have one (otherwise tell the user it's unavailable) — never
refuse or block the user. Only mention upgrading or renewing Copilot Plus when
the script's message explicitly invites it, and keep any such note short and
friendly.`;E0n=Kre({name:"copilot-web-search",description:"Search the web for current information using Copilot Plus or the configured Self-Host search provider. Use when the user asks to search online, look something up on the internet, or needs up-to-date facts beyond the vault. Prefer reading the vault for anything about the user's own notes.",heading:"Copilot web search",intro:"Search the web through Copilot and return results for the user's query.",endpoint:"/websearch",arg:["query","<your search query>"],scriptFile:"web-search.sh",license:"Copilot Plus or Self-Host",selfHostMode:"search"}),M0n=Kre({name:"copilot-web-fetch",description:"Fetch and read the full contents of a specific web page (URL) as clean Markdown using Copilot Plus. Use when the user shares a link or asks you to open, read, or summarize a particular page — not for an open-ended web search. Requires an active Copilot Plus license; without it, use your own fetch tool instead.",heading:"Copilot web fetch",intro:"Fetch a web page's contents as Markdown through Copilot Plus.",endpoint:"/url4llm",arg:["url","<url-to-fetch>"],scriptFile:"web-fetch.sh",selfHostMode:"deny",extraInstructions:`## Self-Host mode
Self-Host search providers do not provide a common full-page fetch contract. If
the script reports that Self-Host mode is active, never use an agent-native web
fetch tool. Use \`copilot-web-search\` when search results can answer the request;
otherwise tell the user that fetching the page is unavailable.`}),ait=6,_it={name:"copilot-read-pdf",version:ait,enabledAgents:["claude","codex","opencode"],skillMd:`---
name: copilot-read-pdf
description: Extract the full text of a PDF as Markdown using Copilot Plus. Use when the user wants to read, summarize, or quote a PDF file (in the vault or an absolute path). Requires an active Copilot Plus license.
license: Copilot Plus
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${ait}"
---
# Copilot read PDF
Convert a PDF file to Markdown text through Copilot Plus so you can read,
summarize, or quote it.
${vit({shFile:"read-pdf.sh",cmdFile:"read-pdf.cmd",argPlaceholder:"<path-to-file.pdf>",extraNote:"Pass an absolute path to the PDF file."})}
${bit}
`,files:[{path:"read-pdf.sh",content:`${yit()}
require_relay
FILE=\${1:-}
[ -n "$FILE" ] || die "Usage: sh read-pdf.sh <path-to-file.pdf>" 1
[ -f "$FILE" ] && [ -r "$FILE" ] || die "Could not read file: $FILE" 1
# Mirror brevilabsClient.ts pdf4llm: JSON body with base64-encoded pdf field.
Invoke-Relay "/pdf4llm" @{ pdf = $PDF; user_id = $USER_ID }
`}]},O0n=Kre({name:"copilot-youtube-transcript",description:"Fetch the transcript of a YouTube video using Copilot Plus. Use when the user shares a YouTube URL and wants its contents, a summary, or quotes. Requires an active Copilot Plus license.",heading:"Copilot YouTube transcript",intro:"Fetch a YouTube video's transcript through Copilot Plus.",endpoint:"/youtube4llm",arg:["url","<youtube-url>"],scriptFile:"youtube-transcript.sh"}),R0n=Kre({name:"copilot-fetch-x",description:"Fetch the content of an X (Twitter) post using Copilot Plus. Use when the user shares an x.com or twitter.com URL and wants its text or context. Requires an active Copilot Plus license.",heading:"Copilot fetch X",intro:"Fetch the content of an X (Twitter) post through Copilot Plus.",endpoint:"/twitter4llm",arg:["url","<x-or-twitter-url>"],scriptFile:"fetch-x.sh"}),lit=5,rv="openartifacts-publish",cit="OPENARTIFACTS_API_HOST",uit="research-memo",lIe="Publishing to OpenArtifacts needs a Copilot Plus license key. Add it in Copilot Settings and try again.",N0n={name:"openartifacts-publish",version:lit,enabledAgents:["claude","codex","opencode"],skillMd:`---
name: openartifacts-publish
description: Publish an existing Markdown note or local HTML file, update a published Markdown note, or withdraw an OpenArtifacts page. Use when the user asks to publish, share, update, delete, remove, or withdraw an OpenArtifacts page.
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${lit}"
---
# Publish Markdown or HTML to OpenArtifacts
Copilot supplies everything this skill needs through the environment:
\`$${lI}\` is the vault root, and \`${td.licenseKey}\`
is the credential the bundled wrapper sends. Do not read Copilot settings or credential
files, print the key, install anything, or run Node, npm, npx, or the Obsidian CLI.
If \`${td.licenseKey}\` is unset or empty, stop before generating anything and tell
the user: ${lIe}
## 1. Prepare the page
### Existing Markdown note
Read one existing Markdown source note. Treat YAML frontmatter as metadata, never as page
content. Note its \`openartifacts\` property, or on older notes the \`symposium\` property:
an \`https://…/d/<docId>\` value means the note is already published and this task updates
that page; pass that \`docId\` to the wrapper. Compare document ids, not urls: an older
\`symposium.site\` link and an \`openartifacts.site\` link with the same id are the same page.
If either property holds any other value, or the two name different ids, stop and ask the
user before touching them.
Write complete UTF-8 HTML (at most \`${SC}\` bytes) to a new file
under \`$${lI}/${zF}/\`, creating
the directory if needed. Preserve the note's content; render Obsidian-specific syntax such
as wikilinks, callouts, embeds, Mermaid, and Bases into static HTML or SVG. CSS, scripts,
and external resources are allowed and are published unchanged.
Use the note's file name without \`.md\` as its page title. Convert the filename-derived title to
title case while preserving recognizable acronyms and proper names. Put that title in both the HTML
\`<title>\` and a visible \`<h1>\` above the rendered note body. If the user explicitly asks for no
title, do not add the \`<h1>\`. Keep the HTML \`<title>\` as browser metadata, and preserve any
authored opening heading as note content. Otherwise, if the rendered note body already starts with an
equivalent \`<h1>\` containing the same visible title text, use that heading as the page-body title
and do not add another heading. Preserve all remaining note content below it, and do not edit the
source Markdown to add the heading. Keep normal text wrapping on the \`<h1>\` so long titles wrap
naturally on narrow screens. Never truncate the title, hide its overflow, or apply single-line or
ellipsis styling. The review and publish steps must use this same complete HTML file so its title
and body match in preview and after publishing.
Themes are optional. For a named theme, check
\`$${lI}/${nit}/<name>.md\`, then
\`themes/<name>.md\` next to this skill. Check each path independently. If neither
exists, continue with readable defaults; a missing theme must never block publishing.
The bundled \`${uit}\` is an optional example.
### Existing HTML file
For an existing local \`.html\` file, confirm that it exists and is at most
\`${SC}\` bytes. Pass that original HTML file path directly to
the wrapper. Treat the file as the complete page: do not convert it to Markdown, and do
not render, rewrite, or copy it into \`${zF}/\`. Use its file
name without \`.html\` as the wrapper title without changing the document's own title or
visible content. Skip the Markdown frontmatter, generated-title, and theme instructions
above. Check the HTML, including inline CSS, for every reference to a local file. Examples
include relative \`src\`, \`href\`, \`srcset\`, \`poster\`, or CSS \`url(...)\` references.
If any exist, keep the file unchanged; name each reference in the review message and say it
will not load on the published page because only the HTML file is uploaded. This warning
does not block publication: let the user make the file self-contained or approve publishing
anyway. The original file remains user-owned; never delete the original HTML file.
## 2. Let the user review
Tell the user the absolute path of the HTML file and that, subject to any relative-asset
warning above, opening it in a browser shows the page as it will be uploaded; OpenArtifacts
adds its own header and footer bylines when it serves the page. Then end your turn.
Never publish in the same turn that generated the HTML. Publish only when a later
message from the user clearly asks to publish this page. Treat anything else as feedback
(revise the generated Markdown handoff and repeat this step; for existing HTML, relay the
feedback and wait for the user to update the file, then repeat steps 1 and 2 before accepting
publication approval) or as a cancellation. When unsure whether a message is an approval,
ask once. Never simulate the user's approval.
## 3. Publish
Run the wrapper next to this SKILL.md with the HTML file, its filename-derived title, and
the existing \`docId\` when updating a Markdown note. On macOS or Linux, the Markdown path
uses its generated handoff:
\`\`\`bash
sh "/absolute/path/to/this/skill/directory/${rv}.sh" publish "$${lI}/${zF}/unique.html" "Note title" [docId]
\`\`\`
An existing HTML file uses its original path directly:
\`\`\`bash
sh "/absolute/path/to/this/skill/directory/${rv}.sh" publish "/absolute/path/to/page.html" "Page title"
\`\`\`
On Windows, use the \`.cmd\` wrapper (prefix with \`&\` in PowerShell):
[Console]::Error.WriteLine("OpenArtifacts returned HTTP $status")
if ($detail) { [Console]::Error.WriteLine($detail) }
} elseif ($detail) {
[Console]::Error.WriteLine($detail)
} else {
[Console]::Error.WriteLine("Could not reach OpenArtifacts at $API_HOST. " + $_.Exception.Message)
}
exit 1
}
exit 0
`}]},UF=[E0n,M0n,_it,O0n,R0n,N0n,...iit],dit=3,fit=1,xit=`# Absolute install path first (Obsidian shells often miss Miyo's bin on PATH).
if [ -x "$HOME/.miyo/bin/miyo" ]; then
MIYO="$HOME/.miyo/bin/miyo"
elif command -v miyo >/dev/null 2>&1; then
MIYO=miyo
else
die "Miyo CLI not found (no ~/.miyo/bin/miyo and 'miyo' not on PATH). The Miyo desktop app is not installed — tell the user to install Miyo, then retry. Do not retry in a loop." 3
OUT=$("$MIYO" search "$QUERY" -n 10 --json 2>&1) || die "Miyo search failed — the Miyo app may not be running. Tell the user to open Miyo, then continue without vault search if they can't. Details: $OUT" 1
;;
current)
[ -n "\${${FO}:-}" ] || die "Miyo search could not enforce Current vault scope because the active vault identity is missing. Do not retry or run an unrestricted search." 4
OUT=$("$MIYO" search "$QUERY" -n 10 --folder "$${FO}" --json 2>&1) || die "Miyo search could not enforce Current vault scope. Update Miyo, open it, and retry. Do not run an unrestricted search. Details: $OUT" 1
;;
*)
die "Miyo search received an invalid Search scope. Do not retry or run an unrestricted search." 4
;;
esac
printf '%s\\n' "$OUT"
`,D0n=`@echo off
setlocal enableextensions
rem Semantic vault search via the local Miyo CLI; prints Miyo's JSON to stdout.
if "%~1"=="" (
echo Usage: miyo-search.cmd "query" 1>&2
exit /b 1
)
${Sit}
rem Default closed: only the explicit Unrestricted value may omit Miyo's exact
rem pre-retrieval folder boundary.
rem https://github.com/Brevilabs/obsidian-copilot-private/issues/121
if /I "%${$O}%"=="unrestricted" (
"%MIYO%" search %* -n 10 --json
if errorlevel 1 exit /b 1
exit /b 0
)
if not "%${$O}%"=="" if /I not "%${$O}%"=="current" (
echo Miyo search received an invalid Search scope. Do not retry or run an unrestricted search. 1>&2
exit /b 4
)
if not defined ${FO} (
echo Miyo search could not enforce Current vault scope because the active vault identity is missing. Do not retry or run an unrestricted search. 1>&2
description: Semantic (meaning-based) search over the user's Obsidian vault via the local Miyo app. For any vault-search intent, use it when builtin grep search is too slow or doesn't surface enough relevant notes, or when the user explicitly asks for Miyo search. Needs the Miyo desktop app installed and running.
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${dit}"
---
# Miyo vault search
Search the user's indexed Obsidian vault through Miyo, the user's own companion
app for semantic search over their notes. It finds relevant notes by meaning
(not just filename). Searches go only to the user's own Miyo service — the local
app by default, or the remote Miyo server they configured in settings — never a
third-party API, and no API key.
When to use it: for any vault-search intent, reach for Miyo when your builtin
\`grep\` search is too slow or doesn't surface enough relevant notes, or when
the user explicitly asks for Miyo search.
## How to run
Find the absolute path to this SKILL.md file on disk, then run the script next
to it that matches the operating system, passing the user's full question as the
query. No extra runtime is needed — \`sh\` (macOS/Linux) and \`cmd\` (Windows) are
always present.
On macOS or Linux:
\`\`\`bash
sh "/absolute/path/to/this/skill/directory/miyo-search.sh" "<the user's question>"
\`\`\`
On Windows, run the \`.cmd\` wrapper. In PowerShell you must prefix it with the
call operator \`&\` (PowerShell treats a quoted path on its own as a string and
won't run it); from cmd, run the quoted path without the \`&\`:
description: Parse a local PDF or EPUB file into Markdown/text with the local Miyo CLI. Use this for document reading when Miyo is the selected Document Processor. The file can be anywhere on the filesystem and does not need to be indexed or copied into the vault.
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${fit}"
---
# Parse a document locally with Miyo
Use Miyo to extract Markdown/text from one PDF or EPUB. Parsing runs locally,
works for files anywhere on the filesystem, and does not require the Miyo
service to be running.
## How to run
Find the absolute path to this SKILL.md file, then run the adjacent wrapper
with exactly one quoted file path.
On macOS or Linux:
\`\`\`bash
sh "/absolute/path/to/this/skill/directory/miyo-parse.sh" "/absolute/path/to/document.pdf"
The wrapper prints the parsed Markdown/text to stdout. Use that output to
answer the user's question.
## If it reports a problem
Report the error clearly and stop parsing that document. Never fall back to
\`copilot-read-pdf\` or any other cloud document parser: selecting Miyo is an
explicit local-processing choice. Do not retry in a loop.
If it reports that the Miyo CLI is not installed, say that pointing Copilot at a
remote Miyo server does not help here, and that the user's options are to
install Miyo on this machine or switch Settings → Copilot → Miyo → Document
Processor to Plus.
`,files:[{path:"miyo-parse.sh",content:$0n},{path:"miyo-parse.cmd",content:F0n}]},_h=[...UF,Cit,kit]});function Sr(t){let e=`${t.name}|${t.provider}`;return t._backendId?`${t._backendId}:${e}`:e}var Kq=b(()=>{});function Kr(t,e){let n=`atom${++z0n}`,r={toString(){return(oa.env?oa.env.MODE:void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=U0n,r.write=B0n),e&&(r.write=e),r}function U0n(t){return t(this)}function B0n(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}var oa,z0n,Tit,uIe,dIe,Zre,pIe,j0n,H0n,mIe,Iit,Gre,Eit,Pit,jF,fIe,W0n,V0n,Ait,dI,Mit,nm,Gq,Oit,hIe=b(()=>{oa={},z0n=0;Tit=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,uIe=t=>"init"in t,dIe=t=>!!t.write,Zre=new WeakMap,pIe=t=>{var e;return mIe(t)&&!((e=Zre.get(t))!=null&&e[1])},j0n=(t,e)=>{let n=Zre.get(t);if(n)n[1]=!0,n[0].forEach(r=>r(e));else if((oa.env?oa.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},H0n=t=>{if(Zre.has(t))return;let e=[new Set,!1];Zre.set(t,e);let n=()=>{e[1]=!0};t.then(n,n),t.onCancel=r=>{e[0].add(r)}},mIe=t=>typeof t?.then=="function",Iit=t=>"v"in t||"e"in t,Gre=t=>{if("e"in t)throw t.e;if((oa.env?oa.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},Eit=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},Pit=(t,e,n,r,o)=>{var i;if((oa.env?oa.env.MODE:void 0)!=="production"&&r===e)throw new Error("[Bug] atom cannot depend on itself");n.d.set(r,o.n),pIe(n.v)&&Eit(e,n.v,o),(i=o.m)==null||i.t.add(e),t&&W0n(t,r,e)},jF=()=>[new Map,new Map,new Set],fIe=(t,e,n)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,n)},W0n=(t,e,n)=>{let r=t[0].get(e);r&&r.add(n)},V0n=(t,e)=>t[0].get(e),Ait=(t,e)=>{t[2].add(e)},dI=t=>{let e,n=!1,r=o=>{try{o()}catch(i){n||(e=i,n=!0)}};for(;t[1].size||t[2].size;){t[0].clear();let o=new Set(t[1].values());t[1].clear();let i=new Set(t[2]);t[2].clear(),o.forEach(s=>{var a;return(a=s.m)==null?void 0:a.l.forEach(r)}),i.forEach(r)}if(n)throw e},Mit=(...[t,e,n,r])=>{let o;(oa.env?oa.env.MODE:void 0)!=="production"&&(o=new Set);let i=(v,_,S)=>{let k="v"in _,x=_.v,C=pIe(_.v)?_.v:null;if(mIe(S)){H0n(S);for(let T of _.d.keys())Eit(v,S,t(T));_.v=S,delete _.e}else _.v=S,delete _.e;(!k||!Object.is(x,_.v))&&(++_.n,C&&j0n(C,S))},s=(v,_,S)=>{var k;let x=t(_);if(Iit(x)&&(x.m&&!S?.has(_)||Array.from(x.d).every(([D,F])=>s(v,D,S).n===F)))return x;x.d.clear();let C=!0,T=D=>{if(Tit(_,D)){let q=t(D);if(!Iit(q))if(uIe(D))i(D,q,D.init);else throw new Error("no atom init");return Gre(q)}let F=s(v,D,S);try{return Gre(F)}finally{if(C)Pit(v,_,x,D,F);else{let q=jF();Pit(q,_,x,D,F),p(q,_,x),dI(q)}}},I,M,O={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(oa.env?oa.env.MODE:void 0)!=="production"&&!dIe(_)&&console.warn("setSelf function cannot be used with read-only atom"),!M&&dIe(_)&&(M=(...D)=>{if((oa.env?oa.env.MODE:void 0)!=="production"&&C&&console.warn("setSelf function cannot be called in sync"),!C)return f(_,...D)}),M}};try{let D=e(_,T,O);if(i(_,x,D),mIe(D)){(k=D.onCancel)==null||k.call(D,()=>I?.abort());let F=()=>{if(x.m){let q=jF();p(q,_,x),dI(q)}};D.then(F,F)}return x}catch(D){return delete x.v,x.e=D,++x.n,x}finally{C=!1}},a=v=>Gre(s(void 0,v)),l=(v,_,S)=>{var k,x;let C=new Map;for(let T of((k=S.m)==null?void 0:k.t)||[])C.set(T,t(T));for(let T of S.p)C.set(T,t(T));return(x=V0n(v,_))==null||x.forEach(T=>{C.set(T,t(T))}),C};function c(v,_,S){let k=[],x=new Set,C=new Set,T=[[_,S]];for(;T.length>0;){let[I,M]=T[T.length-1];if(C.has(I)){T.pop();continue}if(x.has(I)){k.push([I,M,M.n]),C.add(I),T.pop();continue}x.add(I);for(let[O,D]of l(v,I,M))I!==O&&!x.has(O)&&T.push([O,D])}return[k,C]}let u=(v,_,S)=>{let[k,x]=c(v,_,S),C=new Set([_]);for(let T=k.length-1;T>=0;--T){let[I,M,O]=k[T],D=!1;for(let F of M.d.keys())if(F!==I&&C.has(F)){D=!0;break}D&&(s(v,I,x),p(v,I,M),O!==M.n&&(fIe(v,I,M),C.add(I))),x.delete(I)}},d=(v,_,...S)=>{let k=!0,x=T=>Gre(s(v,T)),C=(T,...I)=>{let M=t(T);try{if(Tit(_,T)){if(!uIe(T))throw new Error("atom n
`)}return JSON.stringify(t)??String(t)}catch{return String(t)}}var GF=b(()=>{});function ZF(t){let e=Ckn.exec(t);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]}:null}function YF(t,e){let n=i=>{let s=i.match(/(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},r=n(t),o=n(e);for(let i=0;i<3;i++)if(r[i]!==o[i])return r[i]-o[i];return 0}var Ckn,Jq=b(()=>{Ckn=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/});var CIe=yi(roe=>{"use strict";roe.byteLength=Tkn;roe.toByteArray=Pkn;roe.fromByteArray=Mkn;var I_=[],sy=[],kkn=typeof Uint8Array<"u"?Uint8Array:Array,SIe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(BO=0,Git=SIe.length;BO<Git;++BO)I_[BO]=SIe[BO],sy[SIe.charCodeAt(BO)]=BO;var BO,Git;sy[45]=62;sy[95]=63;function Zit(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function Tkn(t){var e=Zit(t),n=e[0],r=e[1];return(n+r)*3/4-r}function Ikn(t,e,n){return(e+n)*3/4-n}function Pkn(t){var e,n=Zit(t),r=n[0],o=n[1],i=new kkn(Ikn(t,r,o)),s=0,a=o>0?r-4:r,l;for(l=0;l<a;l+=4)e=sy[t.charCodeAt(l)]<<18|sy[t.charCodeAt(l+1)]<<12|sy[t.charCodeAt(l+2)]<<6|sy[t.charCodeAt(l+3)],i[s++]=e>>16&255,i[s++]=e>>8&255,i[s++]=e&255;return o===2&&(e=sy[t.charCodeAt(l)]<<2|sy[t.charCodeAt(l+1)]>>4,i[s++]=e&255),o===1&&(e=sy[t.charCodeAt(l)]<<10|sy[t.charCodeAt(l+1)]<<4|sy[t.charCodeAt(l+2)]>>2,i[s++]=e>>8&255,i[s++]=e&255),i}function Akn(t){return I_[t>>18&63]+I_[t>>12&63]+I_[t>>6&63]+I_[t&63]}function Ekn(t,e,n){for(var r,o=[],i=e;i<n;i+=3)r=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),o.push(Akn(r));return o.join("")}function Mkn(t){for(var e,n=t.length,r=n%3,o=[],i=16383,s=0,a=n-r;s<a;s+=i)o.push(Ekn(t,s,s+i>a?a:s+i));return r===1?(e=t[n-1],o.push(I_[e>>2]+I_[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(I_[e>>10]+I_[e>>4&63]+I_[e<<2&63]+"=")),o.join("")}});var Yit=yi(kIe=>{kIe.read=function(t,e,n,r,o){var i,s,a=o*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=n?o-1:0,f=n?-1:1,p=t[e+d];for(d+=f,i=p&(1<<-u)-1,p>>=-u,u+=a;u>0;i=i*256+t[e+d],d+=f,u-=8);for(s=i&(1<<-u)-1,i>>=-u,u+=r;u>0;s=s*256+t[e+d],d+=f,u-=8);if(i===0)i=1-c;else{if(i===l)return s?NaN:(p?-1:1)*(1/0);s=s+Math.pow(2,r),i=i-c}return(p?-1:1)*s*Math.pow(2,i-r)};kIe.write=function(t,e,n,r,o,i){var s,a,l,c=i*8-o-1,u=(1<<c)-1,d=u>>1,f=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:i-1,m=r?1:-1,h=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+d>=1?e+=f/l:e+=f*Math.pow(2,1-d),e*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*l-1)*Math.pow(2,o),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;t[n+p]=a&255,p+=m,a/=256,o-=8);for(s=s<<o|a,c+=o;c>0;t[n+p]=s&255,p+=m,s/=256,c-=8);t[n+p-m]|=h*128}});var NIe=yi(e2=>{"use strict";var TIe=CIe(),XF=Yit(),Jit=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e2.Buffer=Ne;e2.SlowBuffer=$kn;e2.INSPECT_MAX_BYTES=50;var ooe=2147483647;e2.kMaxLength=ooe;Ne.TYPED_ARRAY_SUPPORT=Okn();!Ne.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Okn(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(Ne.prototype,"parent",{enumerable:!0,get:function(){if(Ne.isBuffer(this))return this.buffer}});Object.defineProperty(Ne.prototype,"offset",{enumerable:!0,get:function(){if(Ne.isBuffer(this))return this.byteOffset}});function kC(t){if(t>ooe)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,Ne.prototype),e}function Ne(t,e,n){if(typeof t=="number"){if
Path: Settings > Copilot > BYOK`}:{hasApiKey:!0}}var EIn,Aoe=b(()=>{xt();GF();EIn=new Set(["3rd party (openai-format)","ollama","lm-studio","copilot-plus"])});function Ya(t,e,n={}){let r=n.leading??!1,o=n.trailing??!0,i,s,a,l=!1,c=()=>{let f=s;return s=void 0,l=!1,f&&(a=t(...f)),a},u=()=>{i=window.setTimeout(()=>{i=void 0,o&&l&&c()},e)},d=(...f)=>{s=f,l=!0;let p=i===void 0;return i!==void 0&&window.clearTimeout(i),p&&r&&c(),u(),a};return d.cancel=()=>{i!==void 0&&(window.clearTimeout(i),i=void 0),s=void 0,l=!1},d.flush=()=>i===void 0?a:(window.clearTimeout(i),i=void 0,l?c():a),d}var PPe=b(()=>{});var EC=b(()=>{PPe()});var Tat={};Vo(Tat,{CustomError:()=>N5,MissingApiKeyError:()=>w2,MissingModelKeyError:()=>v2,MissingPlusLicenseError:()=>TI,TimeoutError:()=>L5});var N5,L5,w2,TI,v2,ZO=b(()=>{N5=class t extends Error{constructor(e,n){super(e),this.code=n,Object.setPrototypeOf(this,t.prototype)}},L5=class t extends Error{constructor(e,n){super(`${e} timed out after ${n}ms`),this.name="TimeoutError",Object.setPrototypeOf(this,t.prototype)}},w2=class t extends Error{constructor(e="API key is not configured."){super(e),this.name="MissingApiKeyError",Object.setPrototypeOf(this,t.prototype)}},TI=class t extends Error{constructor(e="Copilot Plus license key is not configured."){super(e),this.name="MissingPlusLicenseError",Object.setPrototypeOf(this,t.prototype)}},v2=class t extends Error{constructor(e="No model key found. Please select a model in settings."){super(e),this.name="MissingModelKeyError",Object.setPrototypeOf(this,t.prototype)}}});function x2(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Aat(t){let e=t,n=e?.detail||{};return{status:n.status,message:n.message||e?.message,reason:n.reason}}function OIn(t){let e=Aat(t),r=t?.message;return!!(e.reason==="Invalid license key"||r==="Invalid license key"||r?.includes("status 403")||e.status===403)}function Eat(t){if(OIn(t))return EPe.INVALID_LICENSE_KEY_USER;let e=soe(t);if(e)return e;let n=Aat(t);return n.message||(n.reason?`Error: ${n.reason}`:EPe.UNKNOWN_ERROR)}function b2(t){return t.replace(/^#/,"").trim()}function uy(t,e={}){let{trimStart:n=!0}=e;if(t.startsWith("---")){let r=t.indexOf("---",3);if(r!==-1){let o=t.slice(r+3);return n?o.trimStart():o.startsWith(`\r
`)?o.slice(2):o.startsWith(`
`)||o.startsWith("\r")?o.slice(1):o}}return t}function A_(t,e,n=!0){let r=t.metadataCache.getFileCache(e),o=r?.frontmatter?.tags,i=new Set;if(!n){let s=r?.tags?.map(a=>a.tag);s&&s.forEach(a=>i.add(b2(a)))}return o&&(Array.isArray(o)?o.forEach(s=>{typeof s=="string"&&i.add(b2(s))}):typeof o=="string"&&i.add(b2(o))),Array.from(i)}function Eoe(t,e,n){let r=t.metadataCache.getFileCache(e)?.frontmatter;if(!r||!Object.hasOwn(r,n))return Iat;let o=r[n],s=(Array.isArray(o)?o:[o]).filter(RIn);return s.length===0?Iat:s.map(a=>String(a))}function RIn(t){let e=typeof t;return e==="string"||e==="number"||e==="boolean"}function Mat(t,e,n){let r=t.metadataCache.getFileCache(e)?.frontmatter;return r!=null&&Object.hasOwn(r,n)}function Moe(t,e,n){if(e.length===0)return[];e=e.map(i=>b2(i));let r=n&&n.length>0?n:D5(t.vault,"/"),o=[];for(let i of r){let s=A_(t,i);e.some(a=>s.includes(a))&&o.push(i)}return o}async function Fo(t,e){let n=(0,gc.normalizePath)(e).replace(/^\/+/,"").replace(/\/+$/,"");if(!n)return;let r=n.split("/").filter(Boolean),o="";for(let i of r){o=o?`${o}/${i}`:i;let s=t.getAbstractFileByPath(o);if(s){if(s instanceof gc.TFile)throw new Error(`Path conflict: "${o}" exists as a file, expected folder.`);continue}await t.adapter.mkdir(o)}}function Ooe(t){return t?aIe.includes(t.extension):!1}async function S2(t,e){return Ooe(t)?await e.read(t):null}function Roe(t){return t.basename}function E_(t){return t?Qot.includes(t.extension):!1}function nd(t){return t==="copilot_plus"}function Noe(t,e){return t?Ooe(t)?!0:nd(e):!1}function Oat(t){let e=[],n=t.history;for(let r=0;r<n.length;r+=2){let o=n[r]?.content||"",i=n[r+1]?.content||"";e.push({role:"user",content:o},{role:"assistant",content:i})}return e}function Rat(t,e){let n=new Map;return t.forEach(r=>{let o=e.getAbstractFileByPath(r);if(o instanceof gc.TFile)n.set(o.path,o);else{let s=e.getMarkdownFiles().filter(a=>a.basename===r);s.length>0&&(NIn(r,e)?n.set(s[0].path,s[0]):V(`Found multiple files with title "${r}". Expected a full path for duplicate titles.`))}}),Array.from(n.values())}function $5(t,e){let n=/\[\[(.*?)\]\]/g,r=t.match(n);if(!r)return[];let o=r.map(i=>i.slice(2,-2));return Rat(o,e)}function Nat(t,e){let n=/\{\[\[(.*?)\]\]\}/g,r=t.match(n);if(!r)return[];let o=r.map(i=>i.slice(3,-3));return Rat(o,e)}function NIn(t,e){return e.getMarkdownFiles().filter(r=>r.basename===t).length===1}function Lat(t){return t=t.trim(),t.startsWith("[[")&&t.endsWith("]]")?`${t.slice(2,-2).trim()}.md`:t}function MPe(t){if(!t||typeof t!="string")return{isValid:!1,error:"URL is required"};let e=t.trim();if(!e)return{isValid:!1,error:"URL cannot be empty"};let n=OPe(e);return n?/^[a-zA-Z0-9_-]{11}$/.test(n)?{isValid:!0,videoId:n}:{isValid:!1,error:"Invalid YouTube video ID"}:{isValid:!1,error:"Invalid YouTube URL format"}}function OPe(t){try{let e=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/)([a-zA-Z0-9_-]{11})/,/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/];for(let n of e){let r=t.match(n);if(r&&r[1])return r[1]}return null}catch{return null}}function Dat(t){return`https://www.youtube.com/watch?v=${t}`}function $at(t){return MPe(t).isValid}function Fat(t){if(!t||typeof t!="string")return!1;try{let e=new URL(t.trim());return(e.hostname==="x.com"||e.hostname==="www.x.com"||e.hostname==="twitter.com"||e.hostname==="www.twitter.com")&&e.pathname.includes("/status/")}catch{return!1}}function zat(t){let e=t.matchAll(new RegExp(LIn,"g"));return Array.from(e,n=>n[0])}async function Loe(t,e={}){let{throwOnHttpError:n=!0}=e,r=new Headers(e.headers),o=Object.fromEntries(r.entries());delete o["content-length"],H("safeFetch request");let i=e.method?.toUpperCase()||"POST",a=await(0,gc.requestUrl)({url:t,contentType:"application/json",headers:o,method:i,...["POST","PUT","PATCH"].includes(i)&&typeof e.body=="string"&&{body:e.body},throw:!1});if(n&&a.status>=400){let l=null;try{l=typeof a.json=="string"?JSON.parse(a.json):a.json}catch{try{l=typeof a.text=="string"?JSON.parse(a.text):a.text}catch{l=null}}let c=new Error(EPe.REQUEST_FAILED(a.status));c.json=l;let u=l&&typ
`),e=e.trim(),e}async function C2(t,e){let n=t.workspace.getMostRecentLeaf();if((!n||!(n.view instanceof gc.MarkdownView))&&(n=t.workspace.getLeaf(!1),!n||!(n.view instanceof gc.MarkdownView)))return;let r=n.view.editor.getSelection().length>0;await F5(t,e,r)}async function F5(t,e,n=!1){let r=t.workspace.getMostRecentLeaf();if(!r){new gc.Notice("No active leaf found.");return}if(r.view instanceof gc.MarkdownView||(r=t.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof gc.MarkdownView)){new gc.Notice("Failed to open a markdown view.");return}let o=r.view.editor,i=o.getCursor("from"),s=o.getCursor("to"),a=kh(e),l=a.split(`
`),c=(v,_)=>{let S=_.length-1;return S===0?{line:v.line,ch:v.ch+(_[0]?.length??0)}:{line:v.line+S,ch:_[_.length-1]?.length??0}},u=()=>{let v=n?i:s;o.replaceRange(a,v,s),o.setSelection(v,c(v,l))},d=()=>{o.focus(),new gc.Notice("Message inserted into the active note.")},f=o.cm;if(!(f?.state?.doc&&typeof f.dispatch=="function")){u(),d();return}let{from:m,to:h}=f.state.selection.main,g=n?m:h,w=f.state.toText(a),y=g+w.length;try{f.dispatch({changes:{from:g,to:h,insert:w},selection:{anchor:g,head:y}})}catch(v){V("CM6 dispatch failed, falling back to Obsidian API",v),u()}d()}function $oe(t,e){return YF(t,e)>0}async function Uat(){try{let e=(await(0,gc.requestUrl)({url:$In,method:"GET"})).json,n=Array.isArray(e?.assets)?e.assets.find(a=>a?.name==="manifest.json"):void 0;if(typeof n?.browser_download_url!="string"||!n.browser_download_url)throw new Error("The latest Copilot release has no manifest.json asset.");let i=(await(0,gc.requestUrl)({url:n.browser_download_url,method:"GET"})).json?.version;if(typeof i!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/.test(i))throw new Error("The latest Copilot manifest has no valid version.");let s={body:typeof e.body=="string"?e.body:"",htmlUrl:typeof e.html_url=="string"?e.html_url:"https://github.com/logancyang/obsidian-copilot/releases/latest",version:i};return{version:s.version,error:null,release:s}}catch(t){return{version:null,error:t instanceof Error?t.message:"Failed to check for updates",release:null}}}function z5(t){if(typeof t=="string")return t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4");let e=t,n=e.modelName||e.model||"";return n.startsWith("o1")||n.startsWith("o3")||n.startsWith("o4")}function FIn(t){if(typeof t=="string")return t.startsWith("gpt-5");let e=t;return(e.modelName||e.model||"").startsWith("gpt-5")}function U5(t){let e=t,n=typeof t=="string"?t:e.modelName||e.model||"",r=z5(n),o=FIn(n),i=n.startsWith("claude-3-7-sonnet")||n.startsWith("claude-sonnet-4")||n.startsWith("claude-opus-4"),s=n.match(/^claude-opus-4-(\d{1,2})(?:[-.]|$)/),a=s?parseInt(s[1],10)>=7:!1;return{isOSeries:r,isGPT5:o,isThinkingEnabled:i,usesAdaptiveThinking:a}}function RPe(t,e="system"){return z5(t)?"human":e}function k2(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text??"").join(""):""}function NPe(t){let n=k2(t).replace(/<think>[\s\S]*?<\/think>/g,"");return n=n.replace(/<think>[\s\S]*$/g,""),n.trim()}function Bat(t){return k2(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function Foe(){return crypto.randomUUID()}async function fv(t){let e=console.warn;try{return console.warn=function(...n){let r=n[0];typeof r=="string"&&(r.includes("Failed to calculate number of tokens")||r.includes("Unknown model"))||e.apply(console,n)},await t()}finally{console.warn=e}}async function dy(t,e,n="Operation"){let{TimeoutError:r}=await Promise.resolve().then(()=>(ZO(),Tat)),o=new AbortController,i=window.setTimeout(()=>{o.abort()},e);try{return await Promise.race([t(o.signal),new Promise((s,a)=>{o.signal.addEventListener("abort",()=>{a(new r(n,e))})})])}finally{window.clearTimeout(i)}}function B5(t){let e=t.workspace.getActiveViewOfType(gc.MarkdownView);return e?e.getState().source===!0:!0}function dv(t){return new TextEncoder().encode(t).length}function II(t,e){if(e<=0)return"";let n=new TextEncoder;if(n.encode(t).length<=e)return t;let o=0,i=t.length,s="";for(;o<=i;){let a=Math.floor((o+i)/2),l=t.substring(0,a);n.encode(l).length<=e?(s=l,o=a+1):i=a-1}return s}function LPe(t){let e=t.split("/"),n=e[e.length-1];if(dv(n)<=APe)return t;let r=n.lastIndexOf("."),o=r>=0?n.substring(r):"",i=r>=0?n.substring(0,r):n,s=dv(o),a=APe-s;return a<=0?e[e.length-1]=II(n,APe):e[e.length-1]=II(i,a)+o,e.join("/")}async function jat(t,e,n=!0){let r=null;t.workspace.iterateAllLeaves(o=>{if(o.view.getViewType()==="markdown"||o.view.getViewType()==="pdf"||o.view.getViewType()==="canvas"){let i=o.view.file;i&&i.path===e.path&&(r=o)}}),r&&n?t.workspace.setActiveLeaf(r,{focus:!0}):r||await
Use your built-in todo/plan tool for complex work so the user can follow your progress.
**When to plan:** the task takes roughly 3+ meaningful steps, spans multiple notes or files, or the user explicitly asks for a plan or checklist.
**When to skip:** simple questions, single-step tasks, or anything you can answer directly — an unnecessary plan is just noise.
When you plan:
- Write each item in the user's language.
- Keep exactly one item in progress at a time: mark it in progress before you start that step, and completed as soon as the work is actually done.
- Update the plan as scope changes — add steps you discover and drop ones that no longer apply.`});function fP(){let t=[];if(!TR()){let e=le();t.push(aEn),t.push(tEn),t.push(e.docProcessorBackend==="miyo"?rEn:nEn),e.enableMiyoSearchSkill===!0&&t.push(oEn),t.push(umt)}return t.push(iEn),t.push(sEn),t.push(hMe()),t.join(`
`)}var tEn,nEn,rEn,oEn,iEn,sEn,aEn,RG=b(()=>{gMe();Ee();dmt();uP();tEn=`## Copilot Plus tools
For these requests, prefer the bundled Copilot skill over any built-in tool of your own:
- Searching the web → the \`copilot-web-search\` skill
- Fetching or reading a specific web page → the \`copilot-web-fetch\` skill
- Getting a YouTube video's transcript → the \`copilot-youtube-transcript\` skill
- Fetching an X (Twitter) post → the \`copilot-fetch-x\` skill
Each skill ships a runnable script per OS — a \`.sh\` for macOS/Linux and a \`.cmd\` for Windows. Follow the skill's own "How to run" instructions for the right command; both runtimes are always present, so nothing needs to be installed.
Choose vault or web evidence from the request:
- For questions about the user's own notes or vault, search locally first. Do not place text from the vault into a web query unless the request clearly requires researching that text.
- For current facts, external topics, or third-party documentation, proactively use web search or fetch without waiting for an explicit web-search request.
- If local search is empty or weak and the question is external in nature, switch to web evidence instead of answering from memory.
Default to one discovery search followed by targeted page fetches, or fetch directly when the user supplied a specific URL. Stop when you have enough evidence; do not start repeated or open-ended search chains.
If a skill is missing, disabled, reports that Copilot Plus is not active, or fails for this particular request (for example a page it can't fetch or any other relay error), silently fall back to your own equivalent tool (or, if you have none for that task, tell the user it's unavailable) and complete the request — never refuse and never block the user on upgrading. Only pass along an upgrade or renewal note when the skill's own message explicitly invites it, and keep any such mention brief and occasional.`,nEn="## Document processing\nFor reading a PDF file, prefer the bundled `copilot-read-pdf` skill over any built-in tool of your own. The fallback rule above applies to it: if it is missing, disabled, or fails for this file, use your own equivalent tool instead.",rEn="## Document processing (local, Miyo)\nThe user selected Miyo as their Document Processor, so PDFs and EPUBs must stay on their machine. For any PDF or EPUB file, use the `miyo-parse` skill, which parses it locally.\n\nThe fallback rule above does NOT apply here. If `miyo-parse` is missing or fails, report the problem and stop — never send the document to `copilot-read-pdf`, another cloud parser, or any other web service.",oEn="## Vault semantic search (Miyo)\nThe user has Miyo enabled: local, meaning-based semantic search over their vault. For any vault-search intent, use the `miyo-search` skill when your builtin `grep` search is too slow or doesn't surface enough relevant notes, or whenever the user explicitly asks for Miyo search. Follow the skill's own instructions to run it.",iEn="## Project workspaces\nWhen the conversation includes a `<project_context>` block:\n- Treat the working directory as that project's workspace. Write generated files, drafts, and intermediate artifacts under an `outputs/` folder inside it, creating it if needed, unless the user names a different destination.\n- Read and search inside the working directory by default. The configured context sources in `<project_context>` are also opted in even when they live outside it. When a source shows a `→ <absolute path>` snapshot pointer, read that path directly.\n- Don't reach for unrelated files outside the working directory or configured context sources unless the instructions or user name a specific file or location.",sEn=`## AGENTS.md precedence
The user's own instructions reach you as AGENTS.md files, in whatever order this runtime loads them. Judge them by scope, not by the order they appear in: an AGENTS.md inside the current project folder is more specific than the one at the vault root, so follow the project file wherever the two conflict.`,aEn=`You are Obsidian Copilot, an AI assistant that helps users work with their Obsidian vault — markdown notes for knowledge management, writing, and research. You are NOT a software-engineering agent or CLI coding tool. The working directory is the user's Obsidian vault, or a project folder within it: a collection of markdown notes, not a code repository. Disregard any framing in environment metadata that suggests otherwise.
## Grounding
- The user's vault contains markdown notes. When the user says "note", they mean an Obsidian note in this vault.
- When the user mentions "tags", they usually mean tags in Obsidian note properties.
- Never claim you do not have access to something. Rely on the user's provided context and the tools available to you.
- If you are unsure, say so and ask for more context — don't guess.
- Always respond in the language of the user's query.
## Tool Behavior
- Prefer evidence from \`read\`, \`grep\`, and \`glob\` over assumption. Don't infer what a note contains from its title — read it.
- NEVER search for the same or very similar query twice. If results were insufficient, try substantially different terms.
- After 1-2 searches, synthesize an answer from the results you have. Do not keep searching unless the results are clearly insufficient.
- If you have enough information to answer, respond directly without calling any more tools.
## Response Style
- Respond at length appropriate to note-taking and knowledge work. Do NOT default to 1-3 line CLI cadence — give the user enough context to understand and act on your answer.
- Be direct and concrete. Don't pad with preamble or postamble.
## Markdown Formatting
- Use \`$...$\` for LaTeX equations, never \`\\[...\\]\` or \`\\(...\\)\`.
- When showing note titles, use the \`[[title]]\` wikilink format and never wrap them in backticks or quotes.
- For Obsidian-internal image links, use the \`![[link]]\` format and never wrap them in backticks.
- For web image links, use the \`\` format and never wrap them in backticks.
- For tables, use valid GitHub-flavored markdown: a header row, then a delimiter row of dashes (e.g. \`| --- | --- |\`), then one row per record — every row wrapped in leading and trailing \`|\`. Put a blank line before the table. If you label the table, put the label on its own line above that blank line; never append a trailing \`|\` to a caption, heading, or any line that is not itself a table row.`});var IR,yMe=b(()=>{ge();Ee();vt();tn();IR=class t{constructor(){this.cachedBaseUrl=null}static getInstance(){return t.instance||(t.instance=new t),t.instance}async resolveBaseUrl(e={}){let n=(e.overrideUrl||"").trim();if(n.length>0)return this.normalizeBaseUrl(n);if(this.cachedBaseUrl&&!e.forceRefresh)return this.cachedBaseUrl;if(!vn())return null;let r=await this.readServiceConfig();if(r==="missing"){let i=this.getDefaultBaseUrl();return this.cachedBaseUrl=null,le().debug&&H(`Miyo service discovery file missing; using fallback ${i}`),i}if(!r)return this.cachedBaseUrl=null,null;let o=this.normalizeBaseUrl(`http://${r.host}:${r.port}`);return this.cachedBaseUrl=o,o}invalidateLocalDiscovery(){this.cachedBaseUrl=null}normalizeBaseUrl(e){return e.trim().replace(/\/+$/,"")}getDefaultBaseUrl(){return this.normalizeBaseUrl("http://127.0.0.1:8742")}getServiceFilePaths(){let e=this.getNodeRequire();if(!e)return[];let n=e("os"),r=e("process"),o=e("path"),i=n.homedir(),s=n.platform(),a=r.env||{};if(s==="win32"){let l=(a.LOCALAPPDATA||"").trim(),c=(a.APPDATA||"").trim();return[l,o.join(i,"AppData","Local"),c,o.join(i,"AppData","Roaming")].filter((d,f,p)=>d.length>0&&p.indexOf(d)===f).map(d=>o.join(d,"Miyo","service.json"))}return s==="linux"?[o.join(i,".config","Miyo","service.json")]:s==="darwin"?[o.join(i,"Library","Application Support","Miyo","service.json")]:(V(`Miyo service discovery unsupported platform: ${s}`),[])}async readServiceConfig(){let e=this.getServiceFilePaths();if(e.length===0)return null;let n=this.getNodeRequire();if(!n)return null;let r=n("fs"),o=!1;for(let i of e)try{let s=await r.promises.readFile(i,"utf8"),a=JSON.parse(s);return!a.host||typeof a.host!="string"?(V("Miyo service discovery missing host"),null):typeof a.port!="number"||Number.isNaN(a.port)?(V("Miyo service discovery missing port"),null):(le().debug&&H(`Miyo service discovery resolved host=${a.host} port=${a.port}`),a)}catch(s){if(this.isMissingFileError(s)){o=!0;continue}return le().debug&&V(`Miyo service discovery failed: ${Dt(s)}`),null}return o?"missing":null}isMissingFileError(e){return e?.code==="ENOENT"}getNodeRequire(){let e=window?.require;return typeof e=="function"?e:null}}});var NG,bc,kse,Su,s0=b(()=>{ge();yMe();Ee();vt();NG=require("obsidian"),bc=class extends Error{constructor(n,r,o){super(r?`Miyo request failed with status ${n}: ${r}`:`Miyo request failed with status ${n}`);this.status=n;this.detail=r;this.errorCode=o;this.name="MiyoRequestError"}},kse=class kse{constructor(e){this.authSnapshot=e,this.discovery=IR.getInstance()}async resolveBaseUrl(e){let n=await this.discovery.resolveBaseUrl({overrideUrl:e});if(!n)throw new Error("Miyo base URL not available");return n}async fetchHealth(e){try{return await dy(async()=>{let n=await this.resolveBaseUrl(e);return this.requestJson(n,"/v0/health",{method:"GET"})},kse.HEALTH_TIMEOUT_MS,"Miyo health probe")}catch(n){return V(`Miyo health fetch failed: ${Dt(n)}`),null}}async isBackendAvailable(e){let n=await this.fetchHealth(e);return n?n.status!=="ok"?(V(`Miyo health check failed: status="${n.status??"unknown"}"`),!1):!0:!1}async addFolder(e,n,r){let o;try{let a=await this.resolveBaseUrl(n),l=this.buildUrl(a,"/v0/folder"),c=await this.buildHeaders(),u=JSON.stringify(e);if(r?.(),H("Miyo request:",{method:"POST",url:l.toString(),hasBody:!0,hasAuthorizationHeader:!!c.Authorization,...le().debug?{postBody:e}:{}}),o=await(0,NG.requestUrl)({url:l.toString(),method:"POST",headers:c,contentType:"application/json",body:u,throw:!1}),o.status===409)try{if(l.searchParams.set("path",e.path),(await dy(async()=>(0,NG.requestUrl)({url:l.toString(),method:"GET",headers:c,throw:!1}),8e3,"Miyo folder conf
`)}}),t.on("end",()=>{let r=n.trim();r.length>0&&e(r)})}var kMe=b(()=>{tn();ge()});function EEn(t){let e=JSON.parse(t);if(typeof e?.loggedIn!="boolean")throw new Error("Unable to verify Claude authentication status.");return e.loggedIn?{loggedIn:!0,label:MEn(e)}:{loggedIn:!1}}function MEn(t){let e=t.email??t.apiProvider,n=t.subscriptionType??t.authMethod;return e&&n?`${e} (${n})`:e??n}async function zse(t,e){try{return await Wmt(t,e)}catch(n){return V("[AgentMode] claude auth status failed",Dt(n)),{loggedIn:!1}}}async function Wmt(t,e){let{execFile:n}=Te("child_process"),{promisify:r}=Te("util"),o=r(n),i;try{({stdout:i}=await o(t,["auth","status","--json"],{timeout:AEn,env:e}))}catch(s){let a=s;if(a.killed||typeof a.stdout!="string")throw s;i=a.stdout}return EEn(i)}function Vmt(t,e,n={}){return Pz(t,["auth","login","--claudeai"],e,()=>zse(t,e),n)}function qmt(t,e,n){return Fse(t,["auth","logout"],e,()=>Wmt(t,e),n)}var AEn,Kmt=b(()=>{ge();vt();tn();kMe();AEn=1e4});async function Gmt(t,e,n){let{execFile:r}=Te("child_process"),{promisify:o}=Te("util");return o(r)(t,e,n)}function REn(t,e){return/\.[cm]?js$/i.test(t)?{command:process.execPath,args:[t,"--version"],env:{...e,ELECTRON_RUN_AS_NODE:"1"}}:{command:t,args:["--version"],env:e}}function NEn(t){return t.match(/\b(\d+\.\d+\.\d+)\b/)?.[1]??null}async function TMe(t,e,n=Gmt){let r=REn(t,e),o;try{({stdout:o}=await n(r.command,r.args,{env:r.env,timeout:OEn}))}catch{throw new Error(`Could not verify the installed Claude Code version. Copilot requires Claude Code ${zG} or newer.`)}let i=NEn(o);if(!i)throw new Error(`Could not read the installed Claude Code version. Copilot requires Claude Code ${zG} or newer.`);return YF(i,zG)<0?{kind:"incompatible",currentVersion:i,minVersion:zG,message:`Claude Code ${i} is not supported. Copilot requires Claude Code ${zG} or newer.`}:{kind:"supported",version:i}}async function Zmt(t,e,n=Gmt){let r=await TMe(t,e,n);if(r.kind==="incompatible")throw new Error(r.message)}var OEn,zG,IMe=b(()=>{Jq();tn();OEn=1e4,zG="2.1.206"});function Y_(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var PMe=b(()=>{});function UG(t){return LEn.test(t)}function $En(t){if(!Y_(t))return!1;let e=t.npm;return typeof e=="string"&&DEn.has(e)}function FEn(t){switch(t){case"@ai-sdk/anthropic":return"anthropic";case"@ai-sdk/google":return"google";default:return"openai-compatible"}}function zEn(t){if(typeof t.id!="string")return null;let e={id:t.id,displayName:t.name??t.id},n=Array.isArray(t.modalities?.input)?t.modalities.input:void 0,r=Array.isArray(t.modalities?.output)?t.modalities.output:void 0;if((n||r)&&(e.modalities={...n?{input:n}:{},...r?{output:r}:{}}),t.limit){let{context:o,output:i,input:s}=t.limit,a={};typeof o=="number"&&(a.context=o),typeof i=="number"&&(a.output=i),typeof s=="number"&&(a.input=s),Object.keys(a).length>0&&(e.limits=a)}if(typeof t.reasoning=="boolean"&&(e.reasoning=t.reasoning),typeof t.tool_call=="boolean"&&(e.toolCall=t.tool_call),UG(`${t.id} ${typeof t.family=="string"?t.family:""}`)&&(e.isEmbedding=!0),typeof t.release_date=="string"&&(e.releaseDate=t.release_date),t.cost){let{input:o,output:i,cache_read:s,cache_write:a}=t.cost,l={};typeof o=="number"&&(l.input=o),typeof i=="number"&&(l.output=i),typeof s=="number"&&(l.cacheRead=s),typeof a=="number"&&(l.cacheWrite=a),Object.keys(l).length>0&&(e.cost=l)}return e}function UEn(t,e){if(!Y_(e)||typeof e.id!="string")return null;let n=e,r={},o=Y_(n.models)?n.models:{};for(let[s,a]of Object.entries(o)){if(!Y_(a)){V(`[modelsCatalog] dropping model "${s}" under provider "${t}": not an object`);continue}let l=zEn(a);l?r[l.id]=l:V(`[modelsCatalog] dropping model "${s}" under provider "${t}": invalid id`)}let i={id:n.id,displayName:n.name??n.id,providerType:FEn(n.npm),models:r};return typeof n.api=="string"&&n.api.length>0&&(i.defaultBaseUrl=n.api),i}function Ymt(t){if(!Y_(t))return[];let e=[];for(let[n,r]of Object.entries(t)){if($En(r))continue;let o=UEn(n,r);o?e.push(o):Y_(r)&&"id"in r&&V(`[modelsCatalog] dropping provider "${n}": invalid id`)}return e.sort((n,r)=>n.displayName.locale
`)}var yht,rae,s9,oOe=b(()=>{OR();Mv();yht=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Fz,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},rae=Re("$ZodError",yht),s9=Re("$ZodError",yht,{Parent:Error})});var a9,oae,l9,iae,c9,wht,u9,vht,bht,_ht,xht,Sht,Cht,kht,Tht,Iht,iOe=b(()=>{OR();oOe();Mv();a9=t=>(e,n,r,o)=>{let i=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Q_;if(s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>Sy(l,i,hm())));throw tae(a,o?.callee),a}return s.value},oae=a9(s9),l9=t=>async(e,n,r,o)=>{let i=r?{...r,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>Sy(l,i,hm())));throw tae(a,o?.callee),a}return s.value},iae=l9(s9),c9=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Q_;return i.issues.length?{success:!1,error:new(t??rae)(i.issues.map(s=>Sy(s,o,hm())))}:{success:!0,data:i.value}},wht=c9(s9),u9=t=>async(e,n,r)=>{let o=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(s=>Sy(s,o,hm())))}:{success:!0,data:i.value}},vht=u9(s9),bht=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return a9(t)(e,n,o)},_ht=t=>(e,n,r)=>a9(t)(e,n,r),xht=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return l9(t)(e,n,o)},Sht=t=>async(e,n,r)=>l9(t)(e,n,r),Cht=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return c9(t)(e,n,o)},kht=t=>(e,n,r)=>c9(t)(e,n,r),Tht=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return u9(t)(e,n,o)},Iht=t=>async(e,n,r)=>u9(t)(e,n,r)});function $ht(){return new RegExp(NMn,"u")}function Kht(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ght(t){return new RegExp(`^${Kht(t)}$`)}function Zht(t){let e=Kht({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Vht}T(?:${r})$`)}var Pht,Aht,Eht,Mht,Oht,Rht,Nht,Lht,sOe,Dht,NMn,Fht,zht,Uht,Bht,jht,aOe,Hht,Wht,Vht,qht,Yht,Jht,lOe,Xht,Qht,egt,sae=b(()=>{Pht=/^[cC][0-9a-z]{6,}$/,Aht=/^[0-9a-z]+$/,Eht=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Mht=/^[0-9a-vA-V]{20}$/,Oht=/^[A-Za-z0-9]{27}$/,Rht=/^[a-zA-Z0-9_-]{21}$/,Nht=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Lht=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,sOe=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Dht=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,NMn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Fht=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,zht=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Uht=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Bht=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|(
`).filter(s=>s),o=Math.min(...r.map(s=>s.length-s.trimStart().length)),i=r.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let e=Function,n=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...n,o.join(`
`))}}});var hgt,fOe=b(()=>{hgt={major:4,minor:4,patch:3}});function qgt(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function LMn(t){if(!aOe.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return qgt(n)}function DMn(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function ggt(t,e,n){t.issues.length&&e.issues.push(...Ev(n,t.issues)),e.value[n]=t.value}function uae(t,e,n,r,o,i){let s=n in r;if(t.issues.length){if(o&&i&&!s)return;e.issues.push(...Ev(n,t.issues))}if(!s&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?s&&(e.value[n]=void 0):e.value[n]=t.value}function eyt(t){let e=Object.keys(t.shape);for(let r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=JMe(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function tyt(t,e,n,r,o,i){let s=[],a=o.keySet,l=o.catchall._zod,c=l.def.type,u=l.optin==="optional",d=l.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(c==="never"){s.push(f);continue}let p=l.run({value:e[f],issues:[]},r);p instanceof Promise?t.push(p.then(m=>uae(m,n,f,e,u,d))):uae(p,n,f,e,u,d)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:i}),t.length?Promise.all(t).then(()=>n):n}function ygt(t,e,n,r){for(let i of t)if(i.issues.length===0)return e.value=i.value,e;let o=t.filter(i=>!wP(i));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(i=>i.issues.map(s=>Sy(s,r,hm())))}),e)}function pOe(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(yP(t)&&yP(e)){let n=Object.keys(e),r=Object.keys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(let i of r){let s=pOe(t[i],e[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],i=e[r],s=pOe(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function wgt(t,e,n){let r=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let l of a.keys)r.has(l)||r.set(l,{}),r.get(l).l=!0}else t.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let l of a.keys)r.has(l)||r.set(l,{}),r.get(l).r=!0;else t.issues.push(a);let i=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&t.issues.push({...o,keys:i}),wP(t))return t;let s=pOe(e.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}function vgt(t,e){for(let n=t.length-1;n>=0;n--)if(t[n]._zod[e]!=="optional")return n+1;return 0}function bgt(t,e,n){t.issues.length&&e.issues.push(...Ev(n,t.issues)),e.value[n]=t.value}function _gt(t,e,n,r,o){for(let i=0;i<n.length;i++){let s=t[i],a=i<r.length;if(s.issues.length){if(!a&&i>=o){e.value.length=i;break}e.issues.push(...Ev(i,s.issues))}e.value[i]=s.value}for(let i=e.value.length-1;i>=r.length&&(n[i]._zod.optout==="optional"&&e.value[i]===void 0);i--)e.value.length=i;return e}function xgt(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}function Sgt(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Cgt(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function cae(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}function kgt(t){return t.value=Object.fr
`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(v,_)=>y(f,v,_)},i,s=RR,a=!$z.jitless,c=a&&ZMe.value,u=e.catchall,d;t._zod.parse=(f,p)=>{d??(d=r.value);let m=f.value;return s(m)?a&&c&&p?.async===!1&&p.jitless!==!0?(i||(i=o(e.shape)),f=i(f,p),u?tyt([],m,f,p,d,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),f)}});gOe=Re("$ZodUnion",(t,e)=>{xs.init(t,e),Ri(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ri(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ri(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ri(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>o9(o.source)).join("|")})$`)}});let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1,s=[];for(let a of e.options){let l=a._zod.run({value:r.value,issues:[]},o);if(l instanceof Promise)s.push(l),i=!0;else{if(l.issues.length===0)return l;s.push(l)}}return i?Promise.all(s).then(a=>ygt(a,r,t,o)):ygt(s,r,t,o)}}),ryt=Re("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,gOe.init(t,e);let n=t._zod.parse;Ri(t._zod,"propValues",()=>{let o={};for(let i of e.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){o[a]||(o[a]=new Set);for(let c of l)o[a].add(c)}}return o});let r=zz(()=>{let o=e.options,i=new Map;for(let s of o){let a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});t._zod.parse=(o,i)=>{let s=o.value;if(!RR(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),o;let a=r.value.get(s?.[e.discriminator]);return a?a._zod.run(o,i):e.unionFallback||i.direction==="backward"?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(r.value.keys()),input:s,path:[e.discriminator],inst:t}),o)}}),oyt=Re("$ZodIntersection",(t,e)=>{xs.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,i=e.left._zod.run({value:o,issues:[]},r),s=e.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([l,c])=>wgt(n,l,c)):wgt(n,i,s)}});iyt=Re("$ZodTuple",(t,e)=>{xs.init(t,e);let n=e.items;t._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({input:i,inst:t,expected:"tuple",code:"invalid_type"}),r;r.value=[];let s=[],a=vgt(n,"optin"),l=vgt(n,"optout");if(!e.rest){if(i.length<a)return r.issues.push({code:"too_small",minimum:a,inclusive:!0,input:i,inst:t,origin:"array"}),r;i.length>n.length&&r.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:i,inst:t,origin:"array"})}let c=new Array(n.length);for(let u=0;u<n.length;u++){let d=n[u]._zod.run({value:i[u],issues:[]},o);d instanceof Promise?s.push(d.then(f=>{c[u]=f})):c[u]=d}if(e.rest){let u=n.length-1,d=i.slice(n.length);for(let f of d){u++;let p=e.rest._zod.run({value:f,issues:[]},o);p instanceof Promise?s.push(p.then(m=>bgt(m,r,u))):bgt(p,r,u)}}return s.length?Promise.all(s).then(()=>_gt(c,r,n,i,l)):_gt(c,r,n,i,l)}});syt=Re("$ZodRecord",(t,e)=>{xs.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!yP(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let i=[],s=e.keyType._zod.values;if(s){n.value={};let a=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);let u=e.keyType._zod.run({value:c,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({code:"invalid_key",origin:"record",issu
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let c=t.external.registry.get(s[0])?.id;if(e!==s[0]&&c){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&t.reused==="ref"){i(s);continue}}}function w9(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let l=t.seen.get(a);if(l.ref===null)return;let c=l.def??l.schema,u={...c},d=l.ref;if(l.ref=null,d){r(d);let p=t.seen.get(d),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(m)):Object.assign(c,m),Object.assign(c,u),a._zod.parent===d)for(let g in c)g==="$ref"||g==="allOf"||g in u||delete c[g];if(m.$ref&&p.def)for(let g in c)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(c[g])===JSON.stringify(p.def[g])&&delete c[g]}let f=a._zod.parent;if(f&&f!==d){r(f);let p=t.seen.get(f);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let m in c)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m])&&delete c[m]}t.override({zodSchema:a,jsonSchema:c,path:l.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&o.id===i&&delete o.id;let s=t.external?.defs??{};for(let a of t.seen.entries()){let l=a[1];l.def&&l.defId&&(l.def.id===l.defId&&delete l.def.id,s[l.defId]=l.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:h9(e,"input",t.processors),output:h9(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function fp(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return fp(r.element,n);if(r.type==="set")return fp(r.valueType,n);if(r.type==="lazy")return fp(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return fp(r.innerType,n);if(r.type==="intersection")return fp(r.left,n)||fp(r.right,n);if(r.type==="record"||r.type==="map")return fp(r.keyType,n)||fp(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:fp(r.in,n)||fp(r.out,n);if(r.type==="object"){for(let o in r.shape)if(fp(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(fp(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(fp(o,n))return!0;return!!(r.rest&&fp(r.rest,n))}return!1}var rwt,h9,_ae=b(()=>{vOe();rwt=(t,e={})=>n=>{let r=g9({...n,processors:e});return ss(t,r),y9(r,t),w9(r,t)},h9=(t,e,n={})=>r=>{let{libraryOptions:o,target:i}=r??{},s=g9({...o??{},target:i,io:e,processors:n});return ss(t,s),y9(s,t),w9(s,t)}});function NR(t,e){if("_idmap"in t){let r=t,o=g9({...e,processors:owt}),i={};for(let l of r._idmap.entries()){let[c,u]=l;ss(u,o)}let s={},a={registry:r,uri:e?.uri,defs:i};o.external=a;for(let l of r._idmap.entries()){let[c,u]=l;y9(o,u),s[c]=w9(o,u)}if(Object.keys(i).length>0){let l=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}let n=g9({...e,processors:owt});return ss(t,n),y9(n,t),w9(n,t)}var jMn,NOe,LOe,DOe,iwt,swt,awt,lwt,cwt,$Oe,uwt,FOe,dwt,zOe,UOe,fwt,pwt,mwt,hwt,BOe,gwt,jOe,ywt,wwt,HOe,WOe,VOe,qOe,KOe,GOe,ZOe,YOe,JOe,XOe,QOe,eRe,tRe,vwt,xae,bwt,owt,Sae=b(()=>{_ae();Mv();jMn=
`;if(RNt()){vqn(n);return}let r=zqn();r.write(n),$8&&r.flush()}function zLe(){return NNt()??FLe??process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??(0,dx.join)(dFe(),"debug",`${ENt()}.txt`)}function jqn(){return Bqn}function vp(t,e,n){let r=[];try{let s=xl(r,Cl`JSON.stringify(${t})`,0);return JSON.stringify(t,e,n)}catch(s){var o=s,i=1}finally{Sl(r,o,i)}}function Hqn(t){let e=t.trim();return e.startsWith("{")&&e.endsWith("}")}function Wqn(t,e){let n={...t};if(e){let r=e.enabled===!0&&e.failIfUnavailable===void 0?{...e,failIfUnavailable:!0}:e,o=n.settings;if(o&&!Hqn(o))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let i={sandbox:r};if(o)try{i={...IFe(o),sandbox:r}}catch{}n.settings=vp(i)}return n}function qqn(){for(let t of Lue)if(!t.killed)if(process.platform==="win32")try{t.stdin.end()}catch{}else t.kill("SIGTERM")}function Kqn(t){Lue.add(t),!bPt&&(bPt=!0,process.on("exit",qqn))}function Gqn(t){return![".js",".mjs",".tsx",".ts",".jsx"].some(e=>t.endsWith(e))}function Zqn(t,e){return(0,kAt.existsSync)(t)?e?`Claude Code native binary at ${t} exists but failed to launch. This usually means the binary does not match this system's libc — e.g. spawning a musl-linked binary on a glibc Linux host fails because the musl dynamic loader (/lib/ld-musl-*) is missing. Specify a matching binary with options.pathToClaudeCodeExecutable.`:`Claude Code executable at ${t} exists but failed to launch.`:e?`Claude Code native binary not found at ${t}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${t}. Is options.pathToClaudeCodeExecutable set?`}function Yqn(){if(process.platform!=="linux")return!1;let t=typeof process.report?.getReport=="function"?process.report.getReport():null;return t!=null&&t.header?.glibcVersionRuntime===void 0}function Jqn(t,e=process.platform,n=process.arch,r=$Nt.existsSync,o=Yqn()){let i=e==="win32"?".exe":"",s=(e==="android"?[`${NU}-linux-${n}-android`]:e==="linux"?o?[`${NU}-linux-${n}-musl`,`${NU}-linux-${n}`]:[`${NU}-linux-${n}`,`${NU}-linux-${n}-musl`]:[`${NU}-${e}-${n}`]).map(a=>`${a}/claude${i}`);for(let a of s)try{let l=t(a);if(r(l))return l}catch{}return null}function Xqn(){return{eventQueue:[],sink:null}}function PFe(t,e){let n=Qqn;if(n.sink===null){n.eventQueue.push({eventName:t,metadata:e,async:!1});return}n.sink.logEvent(t,e)}function e5n(t,e){PFe("tengu_feature_ok",{feature_name:vFe(t),...e})}function t5n(t,e,n){PFe("tengu_feature_bad",{...n,feature_name:vFe(t),error_code:e})}async function zy(t,e,n){try{let r=await e();return e5n(t),r}catch(r){throw t5n(t,n?.(r)??"error"),r}}function l5n(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e}function u5n(t){return typeof t!="string"?null:c5n.test(t)?t:null}async function xPt(t,e){return d5n(t,e,"w")}async function d5n(t,e,n){let r=(0,UNt.createWriteStream)(t,{mode:384,flags:n});try{for(let o of e)r.write(JSON.stringify(o)+`
`)||await(0,VLe.once)(r,"drain");r.end(),await(0,VLe.once)(r,"finish")}catch(o){throw r.destroy(),o}}function f5n(t){return Math.abs(l5n(t)).toString(36)}function p5n(t){let e=t.replace(/[^a-zA-Z0-9]/g,"-");return e.length<=SPt?e:`${e.slice(0,SPt)}-${f5n(t)}`}function GNt(t,e){let n=0;for(let r of t)n+=+!!e(r);return n}function b5n(t){return[...new Set(t)]}function _5n(){return"prod"}function I5n(){let t=process.env.CLAUDE_LOCAL_OAUTH_API_BASE?.replace(/\/$/,"")??"http://localhost:8000",e=process.env.CLAUDE_LOCAL_OAUTH_APPS_BASE?.replace(/\/$/,"")??"http://localhost:4000",n=process.env.CLAUDE_LOCAL_OAUTH_CONSOLE_BASE?.replace(/\/$/,"")??"http://localhost:3000";return{BASE_API_URL:t,CONSOLE_AUTHORIZE_URL:`${n}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${e}/oauth/authorize`,CLAUDE_AI_ORIGIN:e,TOKEN_URL:`${t}/v1/oauth/token`,API_KEY_URL:`${t}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${t}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${n}/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code`,CLAUDEAI_SUCCESS_URL:`${n}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${n}/oauth/code/callback`,CLIENT_ID:"22422756-60c9-4084-8eb7-27705fd5cf9a",DESIGN_CLIENT_ID:"00000000-0000-4000-8000-000000000000",OAUTH_FILE_SUFFIX:"-local-oauth",MCP_PROXY_URL:"http://localhost:8205",MCP_PROXY_PATH:"/v1/toolbox/shttp/mcp/{server_id}"}}function A5n(){let t=(()=>{switch(_5n()){case"local":return I5n();case"staging":return T5n??CPt;case"prod":return CPt}})(),e=process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL;if(e){let r=e.replace(/\/$/,"");if(!P5n.includes(r))throw Error("CLAUDE_CODE_CUSTOM_OAUTH_URL is not an approved endpoint.");t={...t,BASE_API_URL:r,CONSOLE_AUTHORIZE_URL:`${r}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${r}/oauth/authorize`,CLAUDE_AI_ORIGIN:r,TOKEN_URL:`${r}/v1/oauth/token`,API_KEY_URL:`${r}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${r}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${r}/oauth/code/success?app=claude-code`,CLAUDEAI_SUCCESS_URL:`${r}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${r}/oauth/code/callback`,OAUTH_FILE_SUFFIX:"-custom-oauth"}}let n=process.env.CLAUDE_CODE_OAUTH_CLIENT_ID;return n&&(t={...t,CLIENT_ID:n}),t}function M5n(t=""){let e=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,n=e!==void 0?!e:!process.env.CLAUDE_CONFIG_DIR,r=e!==void 0?e.normalize("NFC"):dFe(),o=n?"":`-${(0,qNt.createHash)("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${A5n().OAUTH_FILE_SUFFIX}${t}${o}`}function R5n(){if(process.platform==="win32")return"claude-code-user";let t;try{t=process.env.USER||(0,KNt.userInfo)().username}catch{t="claude-code-user"}return O5n.test(t)?t:"claude-code-user"}function N5n(t,e){if(t==="bypassPermissions")return"canUseTool will not be invoked: permissionMode 'bypassPermissions' auto-approves every tool call (except explicit deny rules) before the callback is consulted. To gate every tool call, use a PreToolUse hook instead.";let n=e.filter(r=>r.length>0&&!r.includes("("));if(n.length!==0)return`canUseTool will not be invoked for: ${n.join(", ")}. Bare allowedTools entries auto-approve the whole tool before the callback is consulted. To gate every tool call, use a PreToolUse hook; or remove the bare names from allowedTools so they fall through to canUseTool. Allow rules from settings files can also shadow the callback but are not visible here.`}function L5n(t,e,n){if(!t)return;let r=N5n(e,n);r!==void 0&&process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}function qLe(){return $5n}function Lt(t,e){let n=qLe(),r=KLe({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===oZ?void 0:oZ].filter(o=>!!o)});t.common.issues.push(r)}function jr(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,s)=>{let{message:a}=t;return i.code==="invalid_enum_value"?{message:a??s.defaultError}:typeof s.data>"u"?
deps: ${u}}`};var o={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(l){let[c,u]=i(l);s(l,c),a(l,u)}};function i({schema:l}){let c={},u={};for(let d in l){if(d==="__proto__")continue;let f=Array.isArray(l[d])?c:u;f[d]=l[d]}return[c,u]}function s(l,c=l.schema){let{gen:u,data:d,it:f}=l;if(Object.keys(c).length===0)return;let p=u.let("missing");for(let m in c){let h=c[m];if(h.length===0)continue;let g=(0,r.propertyInData)(u,d,m,f.opts.ownProperties);l.setParams({property:m,depsCount:h.length,deps:h.join(", ")}),f.allErrors?u.if(g,()=>{for(let w of h)(0,r.checkReportMissingProp)(l,w)}):(u.if(e._`${g} && (${(0,r.checkMissingProp)(l,h,p)})`),(0,r.reportMissingProp)(l,p),u.else())}}t.validatePropertyDeps=s;function a(l,c=l.schema){let{gen:u,data:d,keyword:f,it:p}=l,m=u.name("valid");for(let h in c)(0,n.alwaysValidSchema)(p,c[h])||(u.if((0,r.propertyInData)(u,d,h,p.opts.ownProperties),()=>{let g=l.subschema({keyword:f,schemaProp:h},m);l.mergeValidEvaluated(g,m)},()=>u.var(m,!0)),l.ok(m))}t.validateSchemaDeps=a,t.default=o}),X2n=je(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=oo(),n=Jo(),r={message:"property name must be valid",params:({params:i})=>e._`{propertyName: ${i.propertyName}}`},o={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:r,code(i){let{gen:s,schema:a,data:l,it:c}=i;if((0,n.alwaysValidSchema)(c,a))return;let u=s.name("valid");s.forIn("key",l,d=>{i.setParams({propertyName:d}),i.subschema({keyword:"propertyNames",data:d,dataTypes:["string"],propertyName:d,compositeRule:!0},u),s.if((0,e.not)(u),()=>{i.error(!0),!c.allErrors&&s.break()})}),i.ok(u)}};t.default=o}),yAt=je(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Qv(),n=oo(),r=KP(),o=Jo(),i={message:"must NOT have additional properties",params:({params:a})=>n._`{additionalProperty: ${a.additionalProperty}}`},s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:i,code(a){let{gen:l,schema:c,parentSchema:u,data:d,errsCount:f,it:p}=a;if(!f)throw Error("ajv implementation error");let{allErrors:m,opts:h}=p;if(p.props=!0,h.removeAdditional!=="all"&&(0,o.alwaysValidSchema)(p,c))return;let g=(0,e.allSchemaProperties)(u.properties),w=(0,e.allSchemaProperties)(u.patternProperties);y(),a.ok(n._`${f} === ${r.default.errors}`);function y(){l.forIn("key",d,x=>{!g.length&&!w.length?S(x):l.if(v(x),()=>S(x))})}function v(x){let C;if(g.length>8){let T=(0,o.schemaRefOrVal)(p,u.properties,"properties");C=(0,e.isOwnProperty)(l,T,x)}else g.length?C=(0,n.or)(...g.map(T=>n._`${x} === ${T}`)):C=n.nil;return w.length&&(C=(0,n.or)(C,...w.map(T=>n._`${(0,e.usePattern)(a,T)}.test(${x})`))),(0,n.not)(C)}function _(x){l.code(n._`delete ${d}[${x}]`)}function S(x){if(h.removeAdditional==="all"||h.removeAdditional&&c===!1){_(x);return}if(c===!1){a.setParams({additionalProperty:x}),a.error(),!m&&l.break();return}if(typeof c=="object"&&!(0,o.alwaysValidSchema)(p,c)){let C=l.name("valid");h.removeAdditional==="failing"?(k(x,C,!1),l.if((0,n.not)(C),()=>{a.reset(),_(x)})):(k(x,C),!m&&l.if((0,n.not)(C),()=>l.break()))}}function k(x,C,T){let I={keyword:"additionalProperties",dataProp:x,dataPropType:o.Type.Str};T===!1&&Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(I,C)}}};t.default=s}),Q2n=je(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Yue(),n=Qv(),r=Jo(),o=yAt(),i={keyword:"properties",type:"object",schemaType:"object",code(s){let{gen:a,schema:l,parentSchema:c,data:u,it:d}=s;d.opts.removeAdditional==="all"&&c.additionalProperties===void 0&&o.default.code(new e.KeywordCxt(d,o.default,"additionalProperties"));let f=(0,n.allSchemaProperties)(l);for(let w of f)d.definedProperties.add(w);d.opts.unevaluated&&f.length&&d.props!==!0&&(d.props=r.mergeEvaluated.props(a,(0,r.toHash)(f),d.props));let p=f.filter(w=>!(0,r.alwaysValidSchema)(d,l[w]));if(p.length===0)return;let m=a.name("valid");for(let w of p)h(w)?g(w):(a.if((0,n.propertyInData)(a,u,w,d.opts.ownProperties)),g(w),!d.allErrors&&a.else().var(m,!0),a.endIf()),s.
`).filter(i=>i),r=Math.min(...n.map(i=>i.length-i.trimStart().length)),o=n.map(i=>i.slice(r)).map(i=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,n=this?.args,r=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...n,r.join(`
`))}},WEt={major:4,minor:0,patch:0},Ir=ke("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=WEt;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let i of o._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,s,a)=>{let l=jU(i),c;for(let u of s){if(u._zod.when){if(!u._zod.when(i))continue}else if(l)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new WP;if(c||f instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(l||(l=jU(i,d)))});else{if(i.issues.length===d)continue;l||(l=jU(i,d))}}return c?c.then(()=>i):i};t._zod.run=(i,s)=>{let a=t._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new WP;return a.then(l=>o(l,r,s))}return o(a,r,s)}}t["~standard"]={validate:o=>{try{let i=ODe(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return NDe(t,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),bZ=ke("$ZodString",(t,e)=>{Ir.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??gEt(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),ks=ke("$ZodStringFormat",(t,e)=>{vZ.init(t,e),bZ.init(t,e)}),VEt=ke("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=tEt),ks.init(t,e)}),qEt=ke("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=YU(n))}else e.pattern??(e.pattern=YU());ks.init(t,e)}),KEt=ke("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=nEt),ks.init(t,e)}),GEt=ke("$ZodURL",(t,e)=>{ks.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),i=o.href;e.hostname&&(e.hostname.lastIndex=0,!e.hostname.test(o.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:cEt.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,!e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&i.endsWith("/")?n.value=i.slice(0,-1):n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),ZEt=ke("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=rEt()),ks.init(t,e)}),YEt=ke("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=QAt),ks.init(t,e)}),JEt=ke("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=GAt),ks.init(t,e)}),XEt=ke("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ZAt),ks.init(t,e)}),QEt=ke("$ZodULID",(t,e)=>{e.pattern??(e.pattern=YAt),ks.init(t,e)}),eMt=ke("$ZodXID",(t,e)=>{e.pattern??(e.pattern=JAt),ks.init(t,e)}),tMt=ke("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=XAt),ks.init(t,e)}),nMt=ke("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=hEt(e)),ks.init(t,e)}),rMt=ke("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=fEt),ks.init(t,e)}),oMt=ke("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=mEt(e)),ks.init(t,e)}),iMt=ke("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=eEt),ks.init(t,e)}),sMt=ke("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=oEt),ks.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),aMt=ke("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=iEt),ks.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),lMt=ke("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=sEt),ks.init(t,e)}),cMt=ke("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=aEt),ks.init(t,e),t._zod.check=n=>{let[r,o]=n.value.split("/");try{if(!o)throw Error();let i=Number(o);if(`${i}`!==o||i<0||i>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_form
})));`),d.write(`newResult[${$U(w)}] = ${y}.value`)}d.write("payload.value = newResult;"),d.write("return payload;");let g=d.compile();return(w,y)=>g(u,w,y)},o,i=V8,s=!jce.jitless,a=s&&FAt.value,l=e.catchall,c;t._zod.parse=(u,d)=>{c??(c=n.value);let f=u.value;if(!i(f))return u.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),u;let p=[];if(s&&a&&d?.async===!1&&d.jitless!==!0)o||(o=r(e.shape)),u=o(u,d);else{u.value={};let y=c.shape;for(let v of c.keys){let _=y[v],S=_._zod.run({value:f[v],issues:[]},d),k=_._zod.optin==="optional"&&_._zod.optout==="optional";S instanceof Promise?p.push(S.then(x=>k?cIt(x,u,v,f):mce(x,u,v))):k?cIt(S,u,v,f):mce(S,u,v)}}if(!l)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=c.keySet,g=l._zod,w=g.def.type;for(let y of Object.keys(f)){if(h.has(y))continue;if(w==="never"){m.push(y);continue}let v=g.run({value:f[y],issues:[]},d);v instanceof Promise?p.push(v.then(_=>mce(_,u,y))):mce(v,u,y)}return m.length&&u.issues.push({code:"unrecognized_keys",keys:m,input:f,inst:t}),p.length?Promise.all(p).then(()=>u):u}});VDe=ke("$ZodUnion",(t,e)=>{Ir.init(t,e),Li(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Li(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Li(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Li(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>ide(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,i=[];for(let s of e.options){let a=s._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>uIt(s,n,t,r)):uIt(i,n,t,r)}}),TMt=ke("$ZodDiscriminatedUnion",(t,e)=>{VDe.init(t,e);let n=t._zod.parse;Li(t._zod,"propValues",()=>{let o={};for(let i of e.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){o[a]||(o[a]=new Set);for(let c of l)o[a].add(c)}}return o});let r=ode(()=>{let o=e.options,i=new Map;for(let s of o){let a=s._zod.propValues[e.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});t._zod.parse=(o,i)=>{let s=o.value;if(!V8(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),o;let a=r.value.get(s?.[e.discriminator]);return a?a._zod.run(o,i):e.unionFallback?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[e.discriminator],inst:t}),o)}}),IMt=ke("$ZodIntersection",(t,e)=>{Ir.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,i=e.left._zod.run({value:o,issues:[]},r),s=e.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([a,l])=>dIt(n,a,l)):dIt(n,i,s)}});lde=ke("$ZodTuple",(t,e)=>{Ir.init(t,e);let n=e.items,r=n.length-[...n].reverse().findIndex(o=>o._zod.optin!=="optional");t._zod.parse=(o,i)=>{let s=o.value;if(!Array.isArray(s))return o.issues.push({input:s,inst:t,expected:"tuple",code:"invalid_type"}),o;o.value=[];let a=[];if(!e.rest){let c=s.length>n.length,u=s.length<r-1;if(c||u)return o.issues.push({input:s,inst:t,origin:"array",...c?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),o}let l=-1;for(let c of n){if(l++,l>=s.length&&l>=r)continue;let u=c._zod.run({value:s[l],issues:[]},i);u instanceof Promise?a.push(u.then(d=>hce(d,o,l))):hce(u,o,l)}if(e.rest){let c=s.slice(n.length);for(let u of c){l++;let d=e.rest._zod.run({value:u,issues:[]},i);d instanceof Promise?a.push(d.then(f=>hce(f,o,l))):hce(d,o,l)}}return a.length?Promise.all(a).then(()=>o):o}});PMt=ke("$ZodRecord",(t,e)=>{Ir.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!q8(o))return n.issues.push({expect
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);r.cycles==="ref"&&s(u);continue}if(d.count>1&&r.reused==="ref"){s(u);continue}}let a=(u,d)=>{let f=this.seen.get(u),p=f.def??f.schema,m={...p};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),Object.assign(p,m))}f.isParent||this.override({zodSchema:u,jsonSchema:p,path:f.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let l={};this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),Object.assign(l,o.def);let c=r.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(c[d.defId]=d.def)}!r.external&&Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw Error("Error converting schema to JSON.")}}};I4n={},E$e={};px(E$e,{time:()=>UOt,duration:()=>BOt,datetime:()=>FOt,date:()=>zOt,ZodISOTime:()=>R$e,ZodISODuration:()=>N$e,ZodISODateTime:()=>M$e,ZodISODate:()=>O$e});M$e=ke("ZodISODateTime",(t,e)=>{nMt.init(t,e),qs.init(t,e)});O$e=ke("ZodISODate",(t,e)=>{rMt.init(t,e),qs.init(t,e)});R$e=ke("ZodISOTime",(t,e)=>{oMt.init(t,e),qs.init(t,e)});N$e=ke("ZodISODuration",(t,e)=>{iMt.init(t,e),qs.init(t,e)});jOt=(t,e)=>{TDe.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>PDe(t,n)},flatten:{value:n=>IDe(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},P4n=ke("ZodError",jOt),_Z=ke("ZodError",jOt,{Parent:Error}),HOt=ADe(_Z),WOt=EDe(_Z),VOt=MDe(_Z),qOt=RDe(_Z),so=ke("ZodType",(t,e)=>(Ir.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>eb(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>HOt(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>VOt(t,n,r),t.parseAsync=async(n,r)=>WOt(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>qOt(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(IRt(n,r)),t.superRefine=n=>t.check(PRt(n)),t.overwrite=n=>t.check(NN(n)),t.optional=()=>Ws(t),t.nullable=()=>Xce(t),t.nullish=()=>Ws(Xce(t)),t.nonoptional=n=>mRt(t,n),t.array=()=>Co(t),t.or=n=>us([t,n]),t.and=n=>wde(t,n),t.transform=n=>Qce(t,sFe(n)),t.default=n=>dRt(t,n),t.prefault=n=>pRt(t,n),t.catch=n=>yRt(t,n),t.pipe=n=>Qce(t,n),t.readonly=()=>bRt(t),t.describe=n=>{let r=t.clone();return gN.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return gN.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return gN.get(t);let r=t.clone();return gN.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),L$e=ke("_ZodString",(t,e)=>{bZ.init(t,e),so.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(w$e(...r)),t.includes=(...r)=>t.check(_$e(...r)),t.startsWith=(...r)=>t.check(x$e(...r)),t.endsWith=(...r)=>t.check(S$e(...r)),t.min=(...r)=>t.check(JU(...r)),t.max=(...r)=>t.check(ude(...r)),t.length=(...r)=>t.check(dde(...r)),t.nonempty=(...r)=>t.check(JU(1,...r)),t.lowercase=r=>t.check(v$e(r)),t.uppercase=r=>t.check(b$e(r)),t.trim=()=>t.check(T$e()),t.normalize=(...r)=>t.check(k$e(...r)),t.toLowerCase=()=>t.check(I$e()),t.toUpperCase=()=>t.check(P$e())}),fde=ke("ZodString",(t,e)=>{bZ.init(t,e),L$e.init(t,e),t.email=n=>t.check(YDe(D$e,n)),t.url=n=>t.check(t$e($$e,n)),t.jwt=n=>t.check(g$e(X$e,n)),t.emoji=n=>t.check(n$e(F$e,n)),t.guid=n=>t.check(Gce(Jce,n)),t.uuid=n=>t.check(JDe($0,n)),t.uuidv4=n=>t.check(XDe($0,n)),t.uuidv6=n=>t.check(QDe($0,n)),t.uuidv7=n=>t.check(e$e($0,n)),t.nanoid=n=>t.check(r$e(z$e,n)),t.guid
`,"\r"]);SN.NEWLINE_REGEXP=/\r\n|[\n\r]/g;CN=class t{constructor(e,n,r){this.iterator=e,f8.set(this,void 0),this.controller=n,Ut(this,f8,r,"f")}static fromSSEResponse(e,n,r){let o=!1,i=r?Pu(r):console;async function*s(){if(o)throw new Hn("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of SWn(e,n)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="span.model_request_start"||l.event==="span.model_request_end")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){let c=NRt(l.data)??l.data,u=c?.error?.type;throw new xp(void 0,c,void 0,e.headers,u)}}a=!0}catch(l){if(X8(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new SN,l=pFe(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new Hn("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(X8(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}[(f8=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller,Ie(this,f8,"f")),new t(()=>o(n),this.controller,Ie(this,f8,"f"))]}toReadableStream(){let e=this,n;return LRt({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:o,done:i}=await n.next();if(i)return r.close();let s=hFe(JSON.stringify(o)+`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=kWn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}};fue=class t extends Promise{constructor(e,n,r=qRt){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,R8.set(this,void 0),Ut(this,R8,e,"f")}_thenUnwrap(e){return new t(Ie(this,R8,"f"),this.responsePromise,async(n,r)=>KRt(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Ie(this,R8,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};R8=new WeakMap;pue=class{constructor(e,n,r,o){yce.set(this,void 0),Ut(this,yce,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Hn("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Ie(this,yce,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(yce=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},bLe=class extends fue{constructor(e,n,r){super(e,n,async(o,i)=>new r(o,i.response,await qRt(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},kN=class extends pue{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let n=this.first_id;return n?{...this.options,query:{...yLe(this.options.query),before_id:n}}:null}let e=this.last_id;return e?{...this.options,query:{...yLe(this.options.query),after_id:e}}:null}},wf=class extends pue{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...yLe(this.options.query),page:e}}:null}},GRt=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};ZRt=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",yFe=async(t,e,n=!0)=>({...t,body:await IWn(t.body,e,n)}),RIt=new WeakMap;IWn=async(t,e,n=!0)=>{if(!await TWn(e))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([o,i])=>_Le(r,o,i,n))),r},PWn=t=>t instanceof Blob&&"name"in t,_Le=async(t,e,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response){let o={},i=n.headers.get("Content-Type");i&&(o={type:i}),t.append(e,HU([await n.blob()],Rce(n,r),o))}else if(ZRt(n))t.append(e,HU([await new Response(DRt(n)).blob()],Rce(n,r)));else if(PWn(n))t.append(e,HU([n],Rce(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(o=>_Le(t,e+"[]",o,r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([o,i])=>_Le(t,`${e}[${
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`;Cue=class{constructor(e,n,r){v8.add(this),this.client=e,EU.set(this,!1),fN.set(this,!1),Uc.set(this,void 0),Im.set(this,void 0),Uh.set(this,void 0),D0.set(this,void 0),OP.set(this,void 0),b8.set(this,0),Ut(this,Uc,{params:{...n,messages:structuredClone(n.messages)}},"f");let o=["BetaToolRunner",...QRt(n.tools,n.messages)].join(", ");Ut(this,Im,{...r,headers:lt([{"x-stainless-helper":o},r?.headers])},"f"),Ut(this,OP,BIt(),"f"),n.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(EU=new WeakMap,fN=new WeakMap,Uc=new WeakMap,Im=new WeakMap,Uh=new WeakMap,D0=new WeakMap,OP=new WeakMap,b8=new WeakMap,v8=new WeakSet,UIt=async function(){let e=Ie(this,Uc,"f").params.compactionControl;if(!e||!e.enabled)return!1;let n=0;if(Ie(this,Uh,"f")!==void 0)try{let l=await Ie(this,Uh,"f");n=l.usage.input_tokens+(l.usage.cache_creation_input_tokens??0)+(l.usage.cache_read_input_tokens??0)+l.usage.output_tokens}catch{return!1}let r=e.contextTokenThreshold??UWn;if(n<r)return!1;let o=e.model??Ie(this,Uc,"f").params.model,i=e.summaryPrompt??BWn,s=Ie(this,Uc,"f").params.messages;if(s[s.length-1].role==="assistant"){let l=s[s.length-1];if(Array.isArray(l.content)){let c=l.content.filter(u=>u.type!=="tool_use");c.length===0?s.pop():l.content=c}}let a=await this.client.beta.messages.create({model:o,messages:[...s,{role:"user",content:[{type:"text",text:i}]}],max_tokens:Ie(this,Uc,"f").params.max_tokens},{signal:Ie(this,Im,"f").signal,headers:lt([Ie(this,Im,"f").headers,{"x-stainless-helper":"compaction"}])});if(a.content[0]?.type!=="text")throw new Hn("Expected text response for compaction");return Ie(this,Uc,"f").params.messages=[{role:"user",content:a.content}],!0},Symbol.asyncIterator)](){var e;if(Ie(this,EU,"f"))throw new Hn("Cannot iterate over a consumed stream");Ut(this,EU,!0,"f"),Ut(this,fN,!0,"f"),Ut(this,D0,void 0,"f");try{for(;;){let n;try{if(Ie(this,Uc,"f").params.max_iterations&&Ie(this,b8,"f")>=Ie(this,Uc,"f").params.max_iterations)break;Ut(this,fN,!1,"f"),Ut(this,D0,void 0,"f"),Ut(this,b8,(e=Ie(this,b8,"f"),e++,e),"f"),Ut(this,Uh,void 0,"f");let{max_iterations:r,compactionControl:o,...i}=Ie(this,Uc,"f").params;if(i.stream?(n=this.client.beta.messages.stream({...i},Ie(this,Im,"f")),Ut(this,Uh,n.finalMessage(),"f"),Ie(this,Uh,"f").catch(()=>{}),yield n):(Ut(this,Uh,this.client.beta.messages.create({...i,stream:!1},Ie(this,Im,"f")),"f"),yield Ie(this,Uh,"f")),!await Ie(this,v8,"m",UIt).call(this)){if(!Ie(this,fN,"f")){let{role:a,content:l}=await Ie(this,Uh,"f");Ie(this,Uc,"f").params.messages.push({role:a,content:l})}let s=await Ie(this,v8,"m",CLe).call(this,Ie(this,Uc,"f").params.messages.at(-1));if(s)Ie(this,Uc,"f").params.messages.push(s);else if(!Ie(this,fN,"f"))break}}finally{n&&n.abort()}}if(!Ie(this,Uh,"f"))throw new Hn("ToolRunner concluded without a message from the server");Ie(this,OP,"f").resolve(await Ie(this,Uh,"f"))}catch(n){throw Ut(this,EU,!1,"f"),Ie(this,OP,"f").promise.catch(()=>{}),Ie(this,OP,"f").reject(n),Ut(this,OP,BIt(),"f"),n}}setMessagesParams(e){typeof e=="function"?Ie(this,Uc,"f").params=e(Ie(this,Uc,"f").params):Ie(this,Uc,"f").params=e,Ut(this,fN,!0,"f"),Ut(this,D0,void 0,"f")}setRequestOptions(e){typeof e=="function"?Ut(this,Im,e(Ie(this,Im,"f")),"f"):Ut(this,Im,{...Ie(this,Im,"f"),...e},"f")}async generateToolResponse(e=Ie(this,Im,"f").signal){let n=await Ie(this,Uh,"f")??this.params.messages.at(-1);return n?Ie(this,v8,"m",CLe).call(this,n,e):null}done(){return Ie(this,OP,"f").promise}async runUntilDone(){if(!Ie(this,EU,"f"))for await(let e of this);return this.done()}get params(){return Ie(this,Uc,"f").params}pushMessages(...e){this.setMessagesParams(n=>({...n,messages:[...n.messages,...e]}))}then(e,n){return this.runUntilDone().then(e,n)}};CLe=async function(t,e=Ie(
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),HWn.includes(i.model)&&i.thinking&&i.thinking.type==="enabled"&&console.warn(`Using Claude with ${i.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let s=this._client._options.timeout;if(!i.stream&&s==null){let l=tNt[i.model]??void 0;s=this._client.calculateNonstreamingTimeout(i.max_tokens,l)}let a=eNt(i.tools,i.messages);return this._client.post("/v1/messages?beta=true",{body:i,timeout:s??6e5,...n,headers:lt([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},a,n?.headers]),stream:r.stream??!1})}parse(e,n){return n={...n,headers:lt([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},n?.headers])},this.create(e,n).then(r=>rNt(r,e,{logger:this._client.logger??console}))}stream(e,n){return SLe.createMessage(this,e,n)}countTokens(e,n){let r=HIt(e),{betas:o,...i}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...n,headers:lt([{"anthropic-beta":[...o??[],"token-counting-2024-11-01"].toString()},n?.headers])})}toolRunner(e,n){return new Cue(this._client,e,n)}};TN.Batches=xue;TN.BetaToolRunner=Cue;TN.ToolError=Sue;kue=class extends Vs{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(gn`/v1/sessions/${e}/events?beta=true`,wf,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,n,r){let{betas:o,...i}=n;return this._client.post(gn`/v1/sessions/${e}/events?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,n={},r){let{betas:o}=n??{};return this._client.get(gn`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}},Tue=class extends Vs{retrieve(e,n,r){let{session_id:o,betas:i}=n;return this._client.get(gn`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.post(gn`/v1/sessions/${o}/resources/${e}?beta=true`,{body:s,...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(gn`/v1/sessions/${e}/resources?beta=true`,wf,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{session_id:o,betas:i}=n;return this._client.delete(gn`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,n,r){let{betas:o,...i}=n;return this._client.post(gn`/v1/sessions/${e}/resources?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}},eB=class extends Vs{constructor(){super(...arguments),this.events=new kue(this._client),this.resources=new Tue(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/sessions?beta=true",{body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(gn`/v1/sessions/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(gn`/v1/sessions/${e}?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",wf,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}de
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),VWn.includes(e.model)&&e.thinking&&e.thinking.type==="enabled"&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){let i=tNt[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}let o=eNt(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...n,headers:lt([o,n?.headers]),stream:e.stream??!1})}parse(e,n){return this.create(e,n).then(r=>sNt(r,e,{logger:this._client.logger??console}))}stream(e,n){return kLe.createMessage(this,e,n,{logger:this._client.logger??console})}countTokens(e,n){return this._client.post("/v1/messages/count_tokens",{body:e,...n})}},ZIt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"},VWn=["claude-mythos-preview","claude-opus-4-6"];nZ.Batches=Eue;Mue=class extends Vs{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(gn`/v1/models/${e}`,{...r,headers:lt([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models",kN,{query:o,...n,headers:lt([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}},qWn="\\n\\nHuman:",KWn="\\n\\nAssistant:",rl=class{get credentials(){return this._authState.provider}constructor({baseURL:e=as("ANTHROPIC_BASE_URL"),apiKey:n,authToken:r,...o}={}){if(TLe.add(this),this._requestAuthFlags=new WeakMap,Lce.set(this,void 0),n===void 0&&(n=o.profile!=null?null:as("ANTHROPIC_API_KEY")??null),r===void 0&&(r=o.profile!=null?null:as("ANTHROPIC_AUTH_TOKEN")??null),o.profile!=null&&(o.credentials!=null||o.config!=null))throw TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let i={apiKey:n,authToken:r,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&KHn())throw new Hn(`It looks like you're running in a browser-like environment.
`);this.baseURL=i.baseURL,this._baseURLIsExplicit=o.__baseURLIsExplicit??!!e,this.timeout=i.timeout??wFe.DEFAULT_TIMEOUT,this.logger=i.logger??console;let s="warn";this.logLevel=s,this.logLevel=EIt(i.logLevel,"ClientOptions.logLevel",this)??EIt(as("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??JHn(),Ut(this,Lce,QHn,"f");let a=as("ANTHROPIC_CUSTOM_HEADERS");if(a){let c={};for(let u of a.split(`
`)){let d=u.indexOf(":");d>=0&&(c[u.substring(0,d).trim()]=u.substring(d+1).trim())}i.defaultHeaders={...c,...i.defaultHeaders}}let l=o.__auth;if(delete i.__auth,delete i.__baseURLIsExplicit,this._options=i,this.apiKey=typeof n=="string"?n:null,this.authToken=r,l)this._authState=l,!this._baseURLIsExplicit&&l.baseURL&&(this.baseURL=l.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let c=i.credentials??null;if(c)this._authState.provider=c,this._authState.tokenCache=this._makeTokenCache(c);else if(i.config!=null){let u=VRt(i.config,this._credentialResolverOptions());this._authState.provider=u.provider,this._authState.tokenCache=this._makeTokenCache(u.provider),this._authState.extraHeaders=u.extraHeaders,this._applyCredentialBaseURL(u.baseURL)}else i.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(i.profile):this._authState.resolution=this._resolveDefaultCredentials()}}_applyCredentialBaseURL(e){if(!e)return;let n=e.replace(/\/+$/,"");this._authState.baseURL=n,!this._baseURLIsExplicit&&(this.baseURL=n)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this.fetch,userAgent:this.getUserAgent(),onCacheWriteError:e=>{Pu(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{Pu(this).warn(e)}}}_makeTokenCache(e){return new wLe(e,n=>{Pu(this).debug("advisory token refresh failed; serving cached token",n)})}withOptions(e){let n="credentials"in e||"config"in e||"profile"in e,r="apiKey"in e||"authToken"in e||n,o={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,credentials:this.credentials,...n?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:r?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(o)}async _resolveDefaultCredentials(e){try{let n=await yWn(this._credentialResolverOptions(),e);if(n)this._authState.provider=n.provider,this._authState.tokenCache=this._makeTokenCache(n.provider),this._authState.extraHeaders=n.extraHeaders,this._applyCredentialBaseURL(n.baseURL);else if(e!=null)throw new Hn(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(n){this._authState.error=n}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.get("x-api-key")||e.get("authorization"))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}}_authFlags(e){let n=this._requestAuthFlags.get(e);return n||(n={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,n)),n}async authHeaders(e){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){let n=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,lt([{Authorization:`Bearer ${n}`}])}return lt([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return lt([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return lt([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return eWn(e)}getUserAgent(){return`${this.constructor.name}/JS ${zP}`}defaultIdempotencyKey(){return`stainless-node-retry-${RRt()}`}makeStatusError(e,n,r,o){return xp.generate(e,n,r,o)}buildURL(e,n,r){let o=!Ie(this,TLe,"m",aNt).call(this)&&r||this.baseURL,i=HHn(e)?new URL(e):new URL(o+(o.e
`))}catch(i){nl(`[Query.handleControlRequest] Error-response write failed: ${Dce(i)}`,{level:"error"})}}finally{this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let n=this.cancelControllers.get(e.request_id);n&&(n.abort(),this.cancelControllers.delete(e.request_id))}async processControlRequest(e,n){if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let r=await this.canUseTool(e.request.tool_name,e.request.input,{signal:n,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,decisionReason:e.request.decision_reason,title:e.request.title,displayName:e.request.display_name,description:e.request.description,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,requestId:e.request_id});return r===null?oLe:{...r,toolUseID:e.request.tool_use_id}}else{if(e.request.subtype==="hook_callback")return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,n);if(e.request.subtype==="mcp_message"){let r=e.request,o=this.sdkMcpTransports.get(r.server_name);if(!o)throw Error(`SDK MCP server not found: ${r.server_name}`);return"method"in r.message&&"id"in r.message&&r.message.id!==null?{mcp_response:await this.handleMcpControlRequest(r.server_name,r,o)}:(o.onmessage&&o.onmessage(r.message),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}else if(e.request.subtype==="elicitation"){let r=e.request;return this.onElicitation?await this.onElicitation({serverName:r.mcp_server_name,message:r.message,mode:r.mode,url:r.url,elicitationId:r.elicitation_id,requestedSchema:r.requested_schema,title:r.title,displayName:r.display_name,description:r.description},{signal:n}):{action:"decline"}}else{if(e.request.subtype==="request_user_dialog")return this.onUserDialog?await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:n}):(nl(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) — staying silent so a capable client (or the worker's park deadline) settles it`),PFe("tengu_request_user_dialog_response_ignored",{shape:vFe("auto_cancel")}),oLe);if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");return{accessToken:await this.getOAuthToken({signal:n})??null}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");return{authToken:await this.getHostAuthToken({signal:n})??null}}}}throw Error("Unsupported control request subtype: "+e.request.subtype)}async*readSdkMessages(){try{for await(let e of this.inputStream)yield e}finally{await this.cleanup()}}async initialize(){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[r,o]of Object.entries(this.hooks))o.length>0&&(this.initHooksPayload[r]=o.map(i=>{let s=[];for(let a of i.hooks){let l=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(l,a),s.push(l)}return{matcher:i.matcher,hookCallbackIds:s,timeout:i.timeout}}))}let e=this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,n={subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt=="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,su
`)).catch(a=>{this.pendingControlResponses.delete(n),s(a)})})}initializationResult(){return this.initialization}reinitialize(){return zy("sdk_reinitialize",()=>this.initialize())}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(e){await this.request({subtype:"mcp_reconnect",serverName:e})}async toggleMcpServer(e,n){return zy("sdk_mcp_toggle_server",async()=>{await this.request({subtype:"mcp_toggle",serverName:e,enabled:n})})}async enableChannel(e){return zy("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:e})})}async mcpAuthenticate(e,n){return(await this.request({subtype:"mcp_authenticate",serverName:e,redirectUri:n})).response}async mcpClearAuth(e){return(await this.request({subtype:"mcp_clear_auth",serverName:e})).response}async mcpSubmitOAuthCallbackUrl(e,n){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:e,callbackUrl:n})).response}async claudeAuthenticate(e){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:e})).response}async claudeOAuthCallback(e,n){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:e,state:n})).response}async claudeOAuthWaitForCompletion(){return(await this.request({subtype:"claude_oauth_wait_for_completion"})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async getContextUsage(){return(await this.request({subtype:"get_context_usage"})).response}async usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(){return(await this.request({subtype:"get_usage"})).response}async readFile(e,n){try{return(await this.request({subtype:"read_file",path:e,max_bytes:n?.maxBytes,encoding:n?.encoding})).response}catch{return null}}async reloadPlugins(){return zy("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins"})).response)}async reloadSkills(){return zy("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async setMcpServers(e){return zy("sdk_mcp_set_servers",async()=>{let n={},r={};for(let[a,l]of Object.entries(e))l.type==="sdk"&&"instance"in l?n[a]=l.instance:r[a]=l;let o=new Set(this.sdkMcpServerInstances.keys()),i=new Set(Object.keys(n));for(let a of o)i.has(a)||await this.disconnectSdkMcpServer(a);for(let[a,l]of Object.entries(n))o.has(a)||this.connectSdkMcpServer(a,l);let s={};for(let a of Object.keys(n))s[a]={type:"sdk",name:a};return(await this.request({subtype:"mcp_set_servers",servers:{...r,...s}})).response})}async accountInfo(){return(await this.initialization).account}async streamInput(e){nl("[Query.streamInput] Starting to process input stream");try{let n=0;for await(let r of e){if(n++,nl(`[Query.streamInput] Processing message ${n}: ${r.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(vp(r)+`
`))}nl(`[Query.streamInput] Finished processing ${n} messages from input stream`),n>0&&this.hasBidirectionalNeeds()&&(nl("[Query.streamInput] Has bidirectional needs, waiting for first result"),await this.waitForFirstResult()),nl("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(n){if(!(n instanceof L0))throw n}}waitForFirstResult(){return this.firstResultReceived?(nl("[Query.waitForFirstResult] Result already received, returning immediately"),Promise.resolve()):new Promise(e=>{if(this.abortController?.signal.aborted){e();return}this.abortController?.signal.addEventListener("abort",()=>e(),{once:!0}),this.firstResultReceivedResolve=e})}handleHookCallbacks(e,n,r,o){let i=this.hookCallbacks.get(e);if(!i)throw Error(`No hook callback found for ID: ${e}`);return i(n,r,{signal:o})}connectSdkMcpServer(e,n){let r=new jLe(o=>this.sendMcpServerMessageToCli(e,o));this.sdkMcpTransports.set(e,r),this.sdkMcpServerInstances.set(e,n),n.connect(r).catch(o=>{this.sdkMcpTransports.get(e)===r&&this.sdkMcpTransports.delete(e),this.sdkMcpServerInstances.get(e)===n&&this.sdkMcpServerInstances.delete(e),nl(`[Query.connectSdkMcpServer] Failed to connect MCP server '${e}': ${o}`,{level:"error"})})}async disconnectSdkMcpServer(e){let n=this.sdkMcpTransports.get(e);n&&(await n.close(),this.sdkMcpTransports.delete(e)),this.sdkMcpServerInstances.delete(e)}sendMcpServerMessageToCli(e,n){if("id"in n&&n.id!==null&&n.id!==void 0){let o=`${e}:${n.id}`,i=this.pendingMcpResponses.get(o);if(i){i.resolve(n),this.pendingMcpResponses.delete(o);return}}let r={type:"control_request",request_id:(0,Rue.randomUUID)(),request:{subtype:"mcp_message",server_name:e,message:n}};Promise.resolve(this.transport.write(vp(r)+`
`)).catch(o=>{nl(`[Query.sendMcpServerMessageToCli] Transport write failed: ${o}`,{level:"error"})})}handleMcpControlRequest(e,n,r){let o="id"in n.message?n.message.id:null,i=`${e}:${o}`;return new Promise((s,a)=>{let l=()=>{this.pendingMcpResponses.delete(i)},c=d=>{l(),s(d)},u=d=>{l(),a(d)};if(this.pendingMcpResponses.set(i,{resolve:c,reject:u}),r.onmessage)r.onmessage(n.message);else{l(),a(Error("No message handler registered"));return}})}};A(Vue,"UNMATCHED_CONTROL_RESPONSES_MAX",1024);HLe=Vue,FNt=500,zNt=1048576,n5n=[200,800],WLe=class{constructor(e,n=6e4,r,o=FNt,i=zNt,s=n5n){A(this,"send");A(this,"sendTimeoutMs");A(this,"onError");A(this,"maxPendingEntries");A(this,"maxPendingBytes");A(this,"backoffMs");A(this,"pending",[]);A(this,"pendingEntries",0);A(this,"pendingBytes",0);A(this,"flushPromise",null);this.send=e,this.sendTimeoutMs=n,this.onError=r,this.maxPendingEntries=o,this.maxPendingBytes=i,this.backoffMs=s}enqueue(e,n){let r=vp(n).length;this.pending.push({filePath:e,entries:n,bytes:r}),this.pendingEntries+=n.length,this.pendingBytes+=r,(this.pendingEntries>this.maxPendingEntries||this.pendingBytes>this.maxPendingBytes)&&(this.flushPromise=this.drain(),this.flushPromise.catch(()=>{}))}async flush(){let e=this.drain();this.flushPromise=e,await e,this.flushPromise===e&&(this.flushPromise=null)}async drain(){let e=this.flushPromise,n=this.pending.splice(0);this.pendingEntries=0,this.pendingBytes=0,e&&await e,n.length!==0&&await this.doFlush(n)}async doFlush(e){let n=new Map;for(let o of e){let i=n.get(o.filePath);i?i.push(...o.entries):n.set(o.filePath,o.entries.slice())}let r=this.backoffMs.length+1;for(let[o,i]of n){let s=`SessionStore.append() timed out after ${this.sendTimeoutMs}ms for ${o}`,a,l=1;for(;l<=r;l++)try{await U8(this.send(o,i),this.sendTimeoutMs,s),a=void 0;break}catch(c){if(a=bde(c),a.message===s)break;let u=this.backoffMs[l-1];if(u===void 0)break;await Xue(u)}if(a){nl(`[TranscriptMirrorBatcher] flush failed for ${o} after ${l} attempt(s): ${a}`,{level:"error"});try{this.onError?.(o,a)}catch(c){nl(`[TranscriptMirrorBatcher] onError callback threw: ${c}`,{level:"error"})}}}}},_Pt=dDe(x2n(),1),Jio=(0,jNt.promisify)(BNt.execFile);c5n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;SPt=200;Xio=Buffer.from('{"type":"attribution-snapshot"'),Qio=Buffer.from('{"type":"system"'),m5n=10,eso=Buffer.from([m5n]);x5n="user:inference",ZNt="user:profile",S5n="org:create_api_key",C5n=[S5n,ZNt],k5n=[ZNt,x5n,"user:sessions:claude_code","user:mcp_servers","user:file_upload"],nso=b5n([...C5n,...k5n]),CPt={BASE_API_URL:"https://api.anthropic.com",CONSOLE_AUTHORIZE_URL:"https://platform.claude.com/oauth/authorize",CLAUDE_AI_AUTHORIZE_URL:"https://claude.com/cai/oauth/authorize",CLAUDE_AI_ORIGIN:"https://claude.ai",TOKEN_URL:"https://platform.claude.com/v1/oauth/token",API_KEY_URL:"https://api.anthropic.com/api/oauth/claude_cli/create_api_key",ROLES_URL:"https://api.anthropic.com/api/oauth/claude_cli/roles",CONSOLE_SUCCESS_URL:"https://platform.claude.com/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code",CLAUDEAI_SUCCESS_URL:"https://platform.claude.com/oauth/code/success?app=claude-code",MANUAL_REDIRECT_URL:"https://platform.claude.com/oauth/code/callback",CLIENT_ID:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",DESIGN_CLIENT_ID:"59637612-477b-4836-a601-b0589eda7704",OAUTH_FILE_SUFFIX:"",MCP_PROXY_URL:"https://mcp-proxy.anthropic.com",MCP_PROXY_PATH:"/v1/mcp/{server_id}"},T5n=void 0;P5n=["https://beacon.claude-ai.staging.ant.dev","https://claude.fedstart.com","https://claude-staging.fedstart.com"];E5n="-credentials";O5n=/^[a-zA-Z0-9._-]+$/;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw Error()}t.assertNever=n,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.
`+" ".repeat(e))}};(function(t){t.DEFAULT={allowTrailingComma:!1}})(OPt||(OPt={}));(function(t){t[t.None=0]="None",t[t.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",t[t.UnexpectedEndOfString=2]="UnexpectedEndOfString",t[t.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",t[t.InvalidUnicode=4]="InvalidUnicode",t[t.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",t[t.InvalidCharacter=6]="InvalidCharacter"})(RPt||(RPt={}));(function(t){t[t.OpenBraceToken=1]="OpenBraceToken",t[t.CloseBraceToken=2]="CloseBraceToken",t[t.OpenBracketToken=3]="OpenBracketToken",t[t.CloseBracketToken=4]="CloseBracketToken",t[t.CommaToken=5]="CommaToken",t[t.ColonToken=6]="ColonToken",t[t.NullKeyword=7]="NullKeyword",t[t.TrueKeyword=8]="TrueKeyword",t[t.FalseKeyword=9]="FalseKeyword",t[t.StringLiteral=10]="StringLiteral",t[t.NumericLiteral=11]="NumericLiteral",t[t.LineCommentTrivia=12]="LineCommentTrivia",t[t.BlockCommentTrivia=13]="BlockCommentTrivia",t[t.LineBreakTrivia=14]="LineBreakTrivia",t[t.Trivia=15]="Trivia",t[t.Unknown=16]="Unknown",t[t.EOF=17]="EOF"})(NPt||(NPt={}));(function(t){t[t.InvalidSymbol=1]="InvalidSymbol",t[t.InvalidNumberFormat=2]="InvalidNumberFormat",t[t.PropertyNameExpected=3]="PropertyNameExpected",t[t.ValueExpected=4]="ValueExpected",t[t.ColonExpected=5]="ColonExpected",t[t.CommaExpected=6]="CommaExpected",t[t.CloseBraceExpected=7]="CloseBraceExpected",t[t.CloseBracketExpected=8]="CloseBracketExpected",t[t.EndOfFileExpected=9]="EndOfFileExpected",t[t.InvalidCommentToken=10]="InvalidCommentToken",t[t.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",t[t.UnexpectedEndOfString=12]="UnexpectedEndOfString",t[t.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",t[t.InvalidUnicode=14]="InvalidUnicode",t[t.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",t[t.InvalidCharacter=16]="InvalidCharacter"})(LPt||(LPt={}));UP=DFe.default.homedir(),$Fe=DFe.default.tmpdir(),{env:BU}=Uue.default,t9n=t=>{let e=da.default.join(UP,"Library");return{data:da.default.join(e,"Application Support",t),config:da.default.join(e,"Preferences",t),cache:da.default.join(e,"Caches",t),log:da.default.join(e,"Logs",t),temp:da.default.join($Fe,t)}},n9n=t=>{let e=BU.APPDATA||da.default.join(UP,"AppData","Roaming"),n=BU.LOCALAPPDATA||da.default.join(UP,"AppData","Local");return{data:da.default.join(n,t,"Data"),config:da.default.join(e,t,"Config"),cache:da.default.join(n,t,"Cache"),log:da.default.join(n,t,"Log"),temp:da.default.join($Fe,t)}},r9n=t=>{let e=da.default.basename(UP);return{data:da.default.join(BU.XDG_DATA_HOME||da.default.join(UP,".local","share"),t),config:da.default.join(BU.XDG_CONFIG_HOME||da.default.join(UP,".config"),t),cache:da.default.join(BU.XDG_CACHE_HOME||da.default.join(UP,".cache"),t),log:da.default.join(BU.XDG_STATE_HOME||da.default.join(UP,".local","state"),t),temp:da.default.join($Fe,e,t)}};lao=o9n("claude-cli");a9n=100,sLe=[];c9n=[],DPt=null,cao=ol(()=>process.argv.includes("--hard-fail"));LU=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,C1t=new Set,XLe=typeof process=="object"&&process?process:{},k1t=(t,e,n,r)=>{typeof XLe.emitWarning=="function"?XLe.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},Bue=globalThis.AbortController,$Pt=globalThis.AbortSignal;if(typeof Bue>"u"){$Pt=class{constructor(){A(this,"onabort");A(this,"_onabort",[]);A(this,"reason");A(this,"aborted",!1)}addEventListener(n,r){this._onabort.push(r)}},Bue=class{constructor(){A(this,"signal",new $Pt);e()}abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let r of this.signal._onabort)r(n);this.signal.onabort?.(n)}}};let t=XLe.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,k1t("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE
`).trim()}function k7n(t){if(typeof t!="string")return null;let e=new Date(t);return Number.isNaN(e.getTime())?null:Ta(e)}var wLt=b(()=>{xt();vt();ZFe()});function TB(t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(0,t)}function IB(t,e=Date.now()){return t.length===0?{kind:"unavailable"}:{kind:"usage",planUsage:{windows:t,updatedAt:e}}}function ZP(t,e=Date.now()){let n=t.windows.filter(r=>r.resetsAt===void 0||r.resetsAt>e);return n.length===0?null:n.length===t.windows.length?t:{...t,windows:n}}var DN=b(()=>{});function P7n(t){if(typeof t!="string")return;let e=Date.parse(t);return Number.isFinite(e)?e:void 0}function vLt(t,e,n){if(!n)return null;let r=TB(n.utilization);return r===null?null:{id:t,label:e,percent:r,resetsAt:P7n(n.resets_at)}}function A7n(t,e=Date.now()){if(t?.rate_limits_available===!1)return{kind:"none"};let n=t?.rate_limits;if(!n)return{kind:"unavailable"};let r=[];for(let[o,i]of I7n){let s=vLt(o,i,n[o]);s&&r.push(s)}for(let o of n.model_scoped??[]){let i=typeof o?.display_name=="string"?o.display_name.trim():"";if(!i)continue;let s=vLt(`model_scoped:${i}`,`Weekly (${i})`,o);s&&r.push(s)}return IB(r,e)}async function bLt(t){let e=t?.[T7n];if(typeof e!="function")return H("[AgentMode] Claude SDK exposes no usage API; plan caps unavailable"),{kind:"unavailable"};try{let n=await e.call(t),r=A7n(n);return H(r.kind==="usage"?`[AgentMode] read ${r.planUsage.windows.length} plan cap window(s)`:`[AgentMode] usage read reported ${r.kind==="none"?"no plan caps":"nothing usable"}`),r}catch(n){return H("[AgentMode] Claude SDK usage read failed; plan caps unavailable",n),{kind:"unavailable"}}}var T7n,I7n,_Lt=b(()=>{DN();ge();T7n="usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET",I7n=[["five_hour","5h"],["seven_day","Weekly"],["seven_day_oauth_apps","Weekly (OAuth apps)"],["seven_day_opus","Weekly (Opus)"],["seven_day_sonnet","Weekly (Sonnet)"]]});function xLt(t){return E7n.includes(t)?t:null}function EZ(){return{pendingCreatesByToolUseId:new Map,tasksById:new Map,nextOrder:0,lastSignature:null}}function kLt(t,e,n,r){let o=AZ(r)?r:null;switch(n){case"TodoWrite":{let i=o?.todos;if(!Array.isArray(i))return null;let s=[];for(let a of i){if(!AZ(a))continue;let l=xLt(a.status);typeof a.content!="string"||a.content.length===0||!l||s.push({content:a.content,status:l,priority:"medium"})}return s.length===0&&i.length>0?null:Ode(t,s)}case"TaskCreate":{let i=typeof o?.subject=="string"?o.subject.trim():"";return i&&t.pendingCreatesByToolUseId.set(e,{subject:i}),null}case"TaskUpdate":{let i=typeof o?.taskId=="string"?o.taskId:"";if(!i)return null;if(o?.status==="deleted")return t.tasksById.delete(i)?Ode(t,JFe(t)):null;let s=xLt(o?.status),a=t.tasksById.get(i);return!a||!s||a.status===s?null:(a.status=s,Ode(t,JFe(t)))}default:return null}}function TLt(t,e,n){let r=t.pendingCreatesByToolUseId.get(e);if(!r)return null;t.pendingCreatesByToolUseId.delete(e);let o=O7n(n);return o?(M7n(t)&&(t.tasksById.clear(),t.nextOrder=0),t.tasksById.set(o.id,{subject:o.subject??r.subject,status:"pending",order:t.nextOrder++}),Ode(t,JFe(t))):null}function M7n(t){if(t.tasksById.size===0)return!1;for(let e of t.tasksById.values())if(e.status!=="completed")return!1;return!0}function JFe(t){return Array.from(t.tasksById.values()).sort((e,n)=>e.order-n.order).map(e=>({content:e.subject,status:e.status,priority:"medium"}))}function Ode(t,e){let n=JSON.stringify(e);return n===t.lastSignature?null:(t.lastSignature=n,{sessionUpdate:"plan",entries:e})}function O7n(t){let e=YFe(t);if(e)return e;if(typeof t=="string")return YFe(CLt(t))??SLt(t);if(Array.isArray(t))for(let n of t){if(!AZ(n)||n.type!=="text"||typeof n.text!="string")continue;let r=YFe(CLt(n.text))??SLt(n.text);if(r)return r}return null}function SLt(t){let e=R7n.exec(t.trim());return e?{id:e[1]}:null}function YFe(t){if(!AZ(t)||!AZ(t.task))return null;let{id:e,subject:n}=t.task;return typeof e!="string"||e.length===0?null:{id:e,subject:typeof n=="string"?n:void 0}}function CLt(t){try{return JSON.parse(t)}catch{return null}}function AZ(t){return typeof t=="object"&&t!==null}v
Earlier in this conversation you ran the following multi-agent turn(s). Each shows the user's question and the summary that was already shown to the user. Treat these as conversation history for continuity; do not redo or re-answer them.
${n}`}function Q7n(t){if(!t)return 0;let e=0;for(let n of t){if(typeof n!="object"||n===null)continue;let r=n.type;(r==="image"||r==="image_url")&&(e+=1)}return e}function eYn(t){if(!t)return[];let e=[];for(let r of t.selectedTextContexts??[]){let o=MB(r)?r.noteTitle:EB(r)?r.title||r.url:"selection",i=o2e(r.content.trim(),X7n,QLt);e.push(`[selected from ${o}]
`);i.length>e&&(i=o2e(i,e,QLt),o=!0);let s="Earlier in this conversation the following was said. Treat this as read-only context to inform your answer; do NOT redo or re-answer these earlier turns. Answer only the current question that follows.";return o&&(i=`${J7n}
${i}`),`<conversation_history>
${s}
${i}
</conversation_history>`}function zde(t){let e=[],n=[];for(let r of Object.keys(t.answers)){let o=t.answers[r],i=o.text.trim();o.status==="done"&&i.length>0?e.push({backendId:r,text:i}):n.push(r)}return{succeeded:e,failed:n}}function tDt(t,e,n){if(e.succeeded.length===0)return null;let r=e.succeeded.map(({backendId:i,text:s})=>`### ${n(i)}
`):t}var r2e,VLt,qLt,KLt,GLt,Z7n,Y7n,YLt,ylo,XLt,J7n,QLt,X7n,rYn,oYn,HLt,iYn,sYn,aYn,lYn,nDt,rDt,Ude,oDt,cYn,iDt,sDt,aDt,B0=b(()=>{xt();NZ();LZ();r2e="You are answering a read-only question. Do NOT modify any files, run any commands that change state, or execute write/shell tools — answer only. You may freely read, search, grep, and fetch to inform your answer. Respond with your analysis directly.";VLt=5*60*1e3,qLt="Timed out waiting for this agent to answer.",KLt=3*1e3,GLt=500,Z7n=new Set(["edit","delete","move"]);Y7n=`You are a neutral synthesizer. The labeled blocks below are what SEVERAL DIFFERENT AI agents each produced in response to the user's request. Write a synthesis for the user ABOUT their outputs — you are reporting on what the agents produced, not doing the task yourself.
- Third person, attributing each point to the agent by name (convert the agents' "I/my" into "<agent> …"). NEVER write in the first person or as if the request were made of you; no sentence may begin with "I".
- Use ONLY the outputs shown; ignore any environment scaffolding (tool lists, available skills/agents, boilerplate). Do not mention how many agents there were, who did not respond, or anything missing.
FORMAT (always): clean, scannable Markdown, and be concise. Lead with the bottom line in one or two sentences, THEN the sections below as \`###\` subheadings — each on its own line, preceded by a blank line, with one or two short paragraphs under it. Do NOT pack points into dense bullet lists; prefer short paragraphs and whitespace, and use a bullet list only for 3+ genuinely parallel items, one line each, never nested.
FIRST pick the MODE from the request and the outputs:
- ANSWER mode — the agents answered a question or analyzed something (facts, explanation, a recommendation, identity); there is a best answer to converge on.
- DELIVERABLE mode — the agents each produced an ALTERNATIVE ARTIFACT the user will choose from or use (a rewrite, draft, message, translation, code, plan, design); these are options, not competing claims.
TWO OR MORE in DELIVERABLE mode — lead with the bottom line, then help the user CHOOSE or MERGE (NOT agreements/disagreements), as \`###\` sections:
### Options
A short attributed paragraph per agent on what is DISTINCTIVE about its take — the angle, tone, structure, or tradeoff that would make someone pick it, and who it suits.
### Recommendation
Name the best option for the likely goal and why; if a combination is clearly better, say which parts of which to merge.
Do NOT reproduce the artifacts (the user already has each in its own tab); describe the approach only.
Do NOT modify any files or run write/shell tools.`,YLt="All agents failed to answer; no summary could be generated.",ylo=Object.freeze([]);XLt=48e3,J7n="[earlier conversation truncated]",QLt="[turn truncated]",X7n=2e3;rYn=12e3,oYn="[answer truncated]";HLt=24e3,iYn="[answer truncated]",sYn=1,aYn=`<!--copilot:multi-agent v=${sYn}-->`,lYn=/<!--copilot:multi-agent v=\d+-->/,nDt="<!--copilot:multi-agent-end-->",rDt="<!--copilot:summary-->",Ude="",oDt=`${Ude}0`,cYn=`${Ude}1`,iDt="<!--copilot:",sDt=`<!--copilot${cYn}`;aDt="did not answer"});function cDt(t){lDt=t}function xYn(t,e){let n=IYn(t),r=e.join(e.tmpdir(),...gYn,n);return{dirPath:r,logPath:e.join(r,pYn),rotatedPath:e.join(r,mYn)}}function SYn(){try{let t=Te("fs/promises"),e=Te("os"),n=Te("path"),r=require("electron"),o=r.shell??r.remote?.shell;return{tmpdir:()=>e.tmpdir(),join:(...i)=>n.join(...i),dirname:i=>n.dirname(i),mkdir:async(i,s)=>{await t.mkdir(i,s)},appendFile:t.appendFile,writeFile:t.writeFile,rm:t.rm,stat:t.stat,rename:t.rename,chmod:t.chmod,lstat:async i=>{let s=await t.lstat(i);return{uid:s.uid,mode:s.mode,isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink()}},getuid:process.getuid?()=>process.getuid():void 0,openPath:o?.openPath?.bind(o),showItemInFolder:o?.showItemInFolder?.bind(o)}}catch{return null}}async function CYn(t,e){try{await t.lstat(e)}catch(n){if(!p2e(n))throw n;await t.writeFile(e,"",{encoding:"utf8",mode:f2e})}}function d2e(t){if(process.platform==="win32")return null;let e=t.getuid?.();if(e===void 0)throw new Error("Cannot verify frame-log directory ownership on this platform.");return e}async function kYn(t){if(process.platform==="win32")return;let e=t.tmpdir(),n=await t.lstat(e);if(n.isSymbolicLink||!n.isDirectory)throw new Error("Frame log temp root must be a real directory.");let r=d2e(t);if(r!==null&&n.uid!==r&&n.uid!==0)throw new Error("Frame log temp root is owned by another user.");if((n.mode&18)!==0&&(n.mode&512)===0)throw new Error("Frame log temp root is group/world-writable without a sticky bit.")}async function TYn(t,e,n){let r;try{r=await t.lstat(e)}catch(o){if(!p2e(o))throw o;r=null}if(r?.isSymbolicLink&&(await t.rm(e,{force:!0}),r=null),r&&!r.isDirectory)throw new Error("Frame log path is occupied by a file.");if(!r&&(await t.mkdir(e,{recursive:!0,mode:s2e}),r=await t.lstat(e),r.isSymbolicLink||!r.isDirectory))throw new Error("Frame log path could not be made a real directory.");if(n!==null){if(r.uid!==n)throw new Error("Frame log directory is owned by another user.");(r.mode&4095)!==s2e&&await t.chmod(e,s2e)}}async function l2e(t,e,n){let r;try{r=await t.lstat(e)}catch(o){if(p2e(o))return;throw o}if(r.isSymbolicLink){await t.rm(e,{force:!0});return}if(r.isDirectory)throw new Error("Frame log file path is a directory.");if(n!==null){if(r.uid!==n)throw new Error("Frame log file is owned by another user.");await t.chmod(e,f2e)}}function p2e(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT"}async function c2e(t,e){try{await t.rm(e,{force:!0})}catch{}}function IYn(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}function PYn(t){if(!t||typeof t!="object")return String(t);let e=t,n=e.update,r=[];return typeof e.method=="string"&&r.push(`method=${e.method}`),n&&typeof n.sessionUpdate=="string"&&(r.push(`sessionUpdate=${n.sessionUpdate}`),typeof n.toolCallId=="string"&&r.push(`toolCallId=${n.toolCallId}`)),r.join(" ")||"<no summary>"}function zN(t){if(t===void 0)return"";let e;try{e=JSON.stringify(t)}catch{e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?String(t):Object.prototype.toString.call(t)}return e.length<=a2e?e:e.slice(0,a2e)+`…(+${e.length-a2e})`}var pYn,mYn,hYn,gYn,s2e,f2e,yYn,wYn,vYn,bYn,_Yn,a2e,lDt,u2e,XP,$Z=b(()=>{tn();pYn="acp-frames.ndjson",mYn="acp-frames.old.ndjson",hYn="(Agent Mode frame logs are desktop-only)",gYn=["obsidian-copilot","acp-frames"],s2e=448,f2e=384,yYn=50*1024*1024,wYn=64*1024,vYn=32,bYn=8*1024*1024,_Yn=25,a2e=400,lDt=null;u2e=class{constructor(e={}){this.options=e;this
`)}let n=[];for(let r of t.prompt)if(r.type==="text")r.text.length>0&&n.push({type:"text",text:r.text});else if(r.type==="image"){let o=UYn(r.mimeType);if(!o){V(`[AgentMode] unsupported image media type for Claude SDK: ${r.mimeType}`),n.push({type:"text",text:`[Unsupported image attachment omitted: ${r.mimeType}]`});continue}n.push({type:"image",source:{type:"base64",media_type:o,data:r.data}})}else n.push({type:"text",text:`[Attached resource: ${r.name??r.uri}]`});return n}function jYn(t){return typeof t=="string"?t:t.map(e=>e.type==="image"?{type:"image",media_type:e.source.media_type,dataLength:e.source.data.length}:e)}async function*HYn(t,e){yield{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:e}}function WYn(t){switch(t){case"default":case"acceptEdits":case"auto":case"bypassPermissions":case"plan":return t;default:return null}}var $Yn,FYn,zYn,w2e,Gde,Kde,yDt=b(()=>{ge();vt();VFe();ed();LN();wLt();_Lt();DN();l0();tn();XFe();e2e();BLt();fDt();y2e();m2e();gDt();$Yn=new Set(["Agent","Task","Bash"]),FYn="Remote-isolated agents require background execution, which is temporarily unavailable in Copilot v4.",zYn=async t=>{if(t.hook_event_name!=="PreToolUse"||!$Yn.has(t.tool_name))return{};let e=typeof t.tool_input=="object"&&t.tool_input!==null&&!Array.isArray(t.tool_input)?t.tool_input:{};return(t.tool_name==="Agent"||t.tool_name==="Task")&&e.isolation==="remote"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:FYn}}:{hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...e,run_in_background:!1}}}},w2e={currentModeId:"default",availableModes:[{id:"default",name:"Default"},{id:"plan",name:"Plan"},{id:"acceptEdits",name:"Accept Edits"},{id:"auto",name:"Auto"},{id:"bypassPermissions",name:"Bypass Permissions"}]},Gde=class Gde{constructor(e){this.opts=e;this.sessionHandlers=new Map;this.pendingUpdates=new Map;this.lastPlanUsage=null;this.sessions=new Map;this.permissionPrompter=null;this.askUserQuestionPrompter=null;this.isReadOnlySession=null;this.exitListeners=new Set;this.shuttingDown=!1;this.cachedModels=null;this.cachedModelsProbe=null;this.authConfirmed=!1;this.compatibilityConfirmed=!1;this.compatibilityProbe=null;this.resolvedConfigDir=null;H(`[AgentMode] ClaudeSdkBackendProcess constructed (claude=${e.pathToClaudeCodeExecutable})`)}isRunning(){return!this.shuttingDown}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}setPermissionPrompter(e){this.permissionPrompter=e}setReadOnlySessionPredicate(e){this.isReadOnlySession=e}setAskUserQuestionPrompter(e){this.askUserQuestionPrompter=e}resolveSystemPromptAppend(){return this.opts.getSystemPromptAppend?.()??""}registerSessionHandler(e,n){this.sessionHandlers.set(e,n);let r=this.pendingUpdates.get(e);if(r){this.pendingUpdates.delete(e);for(let o of r)try{n(o)}catch(i){V(`[AgentMode] replay of buffered SDK event threw for ${e}`,i)}}if(this.lastPlanUsage=this.lastPlanUsage&&ZP(this.lastPlanUsage),this.lastPlanUsage)try{n({sessionId:e,update:{sessionUpdate:"plan_usage_update",planUsage:this.lastPlanUsage}})}catch(o){V(`[AgentMode] replay of plan usage threw for ${e}`,o)}return()=>{this.sessionHandlers.get(e)===n&&this.sessionHandlers.delete(e)}}async newSession(e){Jh("newSession",{cwd:e.cwd,projectId:e.projectId??null}),await this.ensureCompatible();let n=zr(),r=e.cwd??null,o=await this.ensureModelCatalog(),i=this.opts.getDefaultModelId?.(),s=g2e(o,i);this.sessions.set(n,{cwd:r,projectId:e.projectId,firstPromptStarted:!1,model:s,additionalDirectories:e.additionalDirectories,systemPromptAppend:this.resolveSystemPromptAppend(),claudeTaskPlan:EZ(),backgroundTasks:new $N});let a=this.computeState(n);return Hde("newSession",{sessionId:n,currentModelId:s??null,hasEffort:a.model!==null},n),{sessionId:n,state:a}}async prompt(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`Unknown session ${e.sessionId}`);if(this.opts.checkAuth&&!this.authConfirmed)if(await this.opts.checkAuth())this.authConfirmed=!0;else throw new Rse("You're not signed in to Claude. Use
`,f=s.then(async()=>{let p=t.getWriter();try{await p.write(n.encode(d))}finally{p.releaseLock()}});return s=f.catch(()=>{}),f},l=new ReadableStream({async start(u){let d=new Mfe,f=async m=>{let h=r.decode(m).trim();if(!h)return;let g;try{g=JSON.parse(h)}catch{await a(VB(Ts.parseError()));return}iA(g)||Array.isArray(g)?u.enqueue(g):await a(VB(Ts.invalidRequest(g)))},p=e.getReader();i=p;try{for(;;){let{value:h,done:g}=await p.read();if(o)return;if(g)break;if(h){for(let w of d.push(h))if(await f(w),o)return}}if(o)return;let m=d.flush();m&&await f(m)}catch(m){if(o)return;u.error(m);return}finally{i===p&&(i=void 0),p.releaseLock()}o||u.close()},cancel(u){return o=!0,i?.cancel(u)}}),c=new WritableStream({write(u){return a(u)}});return{readable:l,writable:c}}var vFt=b(()=>{Efe();yFt()});var Wdo,Vdo,qdo,Kdo,Gdo,Zdo,Ydo,Jdo,Xdo,Qdo,efo,tfo,bFt=b(()=>{Xy();jze();Wdo=sze.and(J({mode:xe("form")})).and(J({message:j()})),Vdo=aze.and(J({mode:xe("url")})).and(J({message:j()})),qdo=an([GZ,ZZ]).and(J({message:j()})),Kdo=eze.and(J({type:xe("string")})),Gdo=tze.and(J({type:xe("number")})),Zdo=nze.and(J({type:xe("integer")})),Ydo=rze.and(J({type:xe("boolean")})),Jdo=ize.and(J({type:xe("array")})),Xdo=oze.and(J({type:xe("string")})),Qdo=Rze.and(J({action:xe("accept")})),efo=J({action:xe("decline")}),tfo=J({action:xe("cancel")})});function CFt(t,e){return wFt(t,e)}function Qy(t){return t??{}}function kFt(t){return typeof t=="object"&&t!==null&&"readable"in t&&"writable"in t}function TFt(){let t=new TransformStream,e=new TransformStream;return[{readable:e.readable,writable:t.writable},{readable:t.readable,writable:e.writable}]}function PFt(t,e=[]){return new Zze(t,e)}function AFt(t,e=[]){return new Yze(t,e)}function _Ft(t){return{...t,additionalDirectories:t.additionalDirectories?[...t.additionalDirectories]:void 0,mcpServers:[...t.mcpServers]}}function EFt(t,e){return t?typeof t=="function"?t(e):t.parse(e):e}function Xi(t,e,n){return{method:t,params:e,mapResponse:n}}function vx(t,e){return{method:t,params:e}}function MFt(t,e,n,r){t.onReceiveRequest(e.method,o=>EFt(e.params,o),async(o,i,s)=>{let a=await r(n(o,s,i.signal,i.id));await i.respond(e.mapResponse?e.mapResponse(a):a)})}function OFt(t,e,n,r){t.onReceiveNotification(e.method,o=>EFt(e.params,o),(o,i)=>r(n(o,i,i.signal)))}function zfe(t){let e={};for(let n of Object.values(t))e[n.method]=n;return e}function etr(t,e,n,r){return{params:t,requestId:r,signal:n,client:e}}function ttr(t,e,n){return{params:t,signal:n,client:e}}function ntr(t,e,n,r){return{params:t,requestId:r,signal:n,agent:e}}function rtr(t,e,n){return{params:t,signal:n,agent:e}}function LFt(t){let e=xFt.get(t);return e||(e=new Qze,xFt.set(t,e)),e}function Ufe(t,e){for(let n of e){let r;try{r=n(t)}catch(o){throw t.close(o),o}Promise.resolve(r).catch(o=>{t.close(o)})}}function DFt(t){return new eUe(t)}var cfo,IFt,Nfe,JZ,XZ,Lfe,Zze,Yze,Jze,Dfe,Xze,Ger,Zer,Yer,Jer,RFt,Xer,NFt,Qer,Qze,xFt,$fe,Ofe,Rfe,Ffe,SFt,eUe,ufo,dfo,ffo,pfo,tUe=b(()=>{H2e();jze();vFt();bFt();H2e();Efe();Efe();cfo={agent:{initialize:bt.initialize,authenticate:bt.authenticate,logout:bt.logout,providers:{list:bt.providers_list,set:bt.providers_set,disable:bt.providers_disable},session:{new:bt.session_new,load:bt.session_load,list:bt.session_list,delete:bt.session_delete,fork:bt.session_fork,resume:bt.session_resume,close:bt.session_close,setMode:bt.session_set_mode,setConfigOption:bt.session_set_config_option,prompt:bt.session_prompt,cancel:bt.session_cancel},nes:{start:bt.nes_start,suggest:bt.nes_suggest,accept:bt.nes_accept,reject:bt.nes_reject,close:bt.nes_close},document:{didOpen:bt.document_did_open,didChange:bt.document_did_change,didClose:bt.document_did_close,didSave:bt.document_did_save,didFocus:bt.document_did_focus}},client:{session:{requestPermission:To.session_request_permission,update:To.session_update},fs:{writeTextFile:To.fs_write_text_file,readTextFile:To.fs_read_text_file},terminal:{create:To.terminal_create,output:To.terminal_output,release:To.terminal_release,waitForExit:To.terminal_wait_for_exit,kill:To.terminal_kill},elicitation:{create:To.el
`))!==-1;){let r=this.buffer.slice(0,n).trim();this.buffer=this.buffer.slice(n+1),r&&this.emit(r)}}flush(){let e=this.buffer.trim();this.buffer="",e&&this.emit(e)}emit(e){try{this.onLine(e)}catch{}}}});function atr(t){let e=t.getReader(),n=new TextEncoder,r=0,o;return new ReadableStream({start(i){o=new GB(s=>{let a=s.replace(str,"").trim();a&&(i.enqueue(n.encode(`${a}
${i}`)}catch{return!1}}async function cnr(){if(process.arch!=="x64")return!1;let t=Te("fs"),{execFile:e}=Te("child_process"),{promisify:n}=Te("util"),r=n(e);try{if(process.platform==="darwin"){let{stdout:o}=await r("sysctl",["-n","hw.optional.avx2_0"]);return o.trim()==="1"}if(process.platform==="linux"){let o=await t.promises.readFile("/proc/cpuinfo","utf-8");return/\bavx2\b/.test(o)}if(process.platform==="win32"){let{stdout:o}=await r("powershell.exe",["-NoProfile","-Command","[System.Runtime.Intrinsics.X86.Avx2]::IsSupported"]);return/true/i.test(o)}}catch{}return!0}async function Czt(){let t=IUe(process.platform),e=PUe(process.arch);if(!t||!e)throw new Error(`Unsupported platform/arch: ${process.platform}/${process.arch}. Agent Mode requires darwin/linux/windows on x64/arm64.`);let[n,r]=await Promise.all([t==="linux"?lnr():Promise.resolve(!1),e==="x64"?cnr():Promise.resolve(void 0)]),s={platform:t,arch:e,libc:t==="linux"?n?"musl":"glibc":void 0,hasAvx2:e==="x64"?r:void 0};return{target:s,candidates:anr(s)}}function kzt(t){return t==="windows"?"opencode.exe":"opencode"}var AUe=b(()=>{tn()});function Qh(){return Te("fs")}function Eu(){return Te("path")}async function Ezt(t,e,n){let{execFile:r}=Te("child_process"),{promisify:o}=Te("util"),{stdout:i}=await o(r)(t,e,n);return{stdout:i}}function dnr(t,e){let n=[".zip",".tar.gz",".tar.xz",".tgz"],r=i=>{for(let s of n)if(i.endsWith(s))return i.slice(0,-s.length);return i},o=new Map;for(let i of t.assets)o.set(r(i.name),i);for(let i of e){let s=o.get(i);if(s)return s}throw new Error(`No matching opencode release asset found. Tried: ${e.join(", ")}. Available: ${t.assets.map(i=>i.name).join(", ")}`)}function ij(t,e=n=>Qh().existsSync(n)){let n=t??{};return n.binaryPath&&e(n.binaryPath)?{kind:"installed",version:n.binaryVersion??"",path:n.binaryPath,source:n.binarySource??"managed"}:{kind:"absent"}}function rj(){return le().agentMode?.backends?.opencode??{}}function fnr(t){return t?GN({kind:"installed",version:t,source:"managed"},G0,"opencode").kind!=="ready":!1}function ape(t){return GN(t,G0,"opencode")}function EUe(t){Xt(e=>({agentMode:{...e.agentMode,backends:{...e.agentMode.backends,opencode:{...e.agentMode.backends?.opencode??{},...t}}}}))}function pnr(){EUe({binaryVersion:void 0,binaryPath:void 0,binarySource:void 0})}function mnr(t){return Eu().join(dP(t),"opencode")}function hnr(t,e,n){return Eu().join(t,e,"plugins",n,"data","opencode")}function l7(t){return t.match(/\d+\.\d+\.\d+(?:[-+][\w.]+)?/)?.[0]}async function Pzt(t){try{return await Qh().promises.access(t),!0}catch{return!1}}async function gnr(t){try{let e=await Qh().promises.readFile(t,"utf-8");return JSON.parse(e)}catch{return null}}async function Azt(t){await Qh().promises.rm(t,{recursive:!0,force:!0})}function ynr(t,e,n=5){let r=Te("https");return new Promise((o,i)=>{let s=(a,l)=>{let c=null,u=()=>{c&&e?.removeEventListener("abort",c),c=null},d=r.get(a,f=>{let p=f.statusCode??0;if(p>=300&&p<400&&f.headers.location){if(u(),l<=0){f.resume(),i(new Error(`Too many redirects fetching ${t}`));return}f.resume();let m=new URL(f.headers.location,a).toString();s(m,l-1);return}if(p!==200){u(),f.resume(),i(new Error(`HTTP ${p} fetching ${a}`));return}f.on("close",u),o(f)});d.on("error",f=>{u(),i(f)}),e&&(e.aborted?d.destroy(new uA):(c=()=>{d.destroy(new uA)},e.addEventListener("abort",c,{once:!0})))};s(t,n)})}async function wnr(t,e,n,r){let o=Eu().basename(e),i=await ynr(t,r.signal),s=n??(i.headers["content-length"]?Number(i.headers["content-length"]):void 0),a=0,l=!1,c=null,u=Qh().createWriteStream(e);await new Promise((d,f)=>{let p=()=>{c&&(window.clearTimeout(c),c=null)},m=()=>{p(),c=window.setTimeout(()=>{l=!0,i.destroy(new Error(`Download stalled — no bytes received for ${Math.round(Tzt/1e3)}s. Check your network and retry.`))},Tzt)};m(),i.on("data",g=>{a+=g.length,m(),r.onProgress?.({phase:"download",received:a,total:s,assetName:o})});let h=g=>{p(),f(g)};i.on("error",h),u.on("error",h),u.on("finish",()=>{p(),!l&&d()}),i.pipe(u)})}async function vnr(t,e){let n=[t];for(;n.length>0;){let r=n.shift(),o=await Qh().p
`)}};Cx.defaultYaml={explicit:!1,version:"1.2"};Cx.defaultTags={"!!":"tag:yaml.org,2002:"}});function hpe(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function $Ue(t){let e=new Set;return Sx(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function FUe(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function jzt(t,e){let n=[],r=new Map,o=null;return{onAnchor:i=>{n.push(i),o??(o=$Ue(t));let s=FUe(e,o);return o.add(s),s},setAnchors:()=>{for(let i of n){let s=r.get(i);if(typeof s=="object"&&s.anchor&&(Nr(s.node)||_i(s.node)))s.node.anchor=s.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:r}}var gpe=b(()=>{zo();d7()});function dA(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,i=r.length;o<i;++o){let s=r[o],a=dA(t,r,String(o),s);a===void 0?delete r[o]:a!==s&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let i=r.get(o),s=dA(t,r,o,i);s===void 0?r.delete(o):s!==i&&r.set(o,s)}else if(r instanceof Set)for(let o of Array.from(r)){let i=dA(t,r,o,o);i===void 0?r.delete(o):i!==o&&(r.delete(o),r.add(i))}else for(let[o,i]of Object.entries(r)){let s=dA(t,r,o,i);s===void 0?delete r[o]:s!==i&&(r[o]=s)}return t.call(e,n,r)}var zUe=b(()=>{});function Gc(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Gc(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!ppe(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=i=>{r.res=i,delete n.onCreate};let o=t.toJSON(e,n);return n.onCreate&&n.onCreate(o),o}return typeof t=="bigint"&&!n?.keep?Number(t):t}var fA=b(()=>{zo()});var pA,ype=b(()=>{zUe();zo();fA();pA=class{constructor(e){Object.defineProperty(this,Ip,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:i}={}){if(!_x(e))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Gc(this,"",s);if(typeof o=="function")for(let{count:l,res:c}of s.anchors.values())o(c,l);return typeof i=="function"?dA(i,{"":a},"",a):a}}});function wpe(t,e,n){if(ib(e)){let r=e.resolve(t),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(_i(e)){let r=0;for(let o of e.items){let i=wpe(t,o,n);i>r&&(r=i)}return r}else if(Po(e)){let r=wpe(t,e.key,n),o=wpe(t,e.value,n);return Math.max(r,o)}return 1}var Y0,f7=b(()=>{gpe();d7();zo();ype();fA();Y0=class extends pA{constructor(e){super(dpe),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Sx(e,{Node:(i,s)=>{(ib(s)||ppe(s))&&r.push(s)}}),n&&(n.aliasResolveCache=r));let o;for(let i of r){if(i===this)break;i.anchor===this.source&&(o=i)}return o}toJSON(e,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:i}=n,s=this.resolve(o,n);if(!s){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=r.get(s);if(a||(Gc(s,null,n),a=r.get(s)),a?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=wpe(o,s,r)),a.count*a.aliasCount>i)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,n,r){let o=`*${this.source}`;if(e){if(hpe(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${o} `}return o}}});var vpe,ln,Jl=b(()=>{zo();ype();fA();vpe=t=>!t||typeof t!="function"&&typeof t!="object",ln=class extends pA{c
|$)`,"g")}catch{jUe=/\n+(?!\n|$)/g}});function kpe(t,e){let n=Object.assign({blockQuote:!0,commentString:Hzt,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function Mnr(t,e){if(e.tag){let o=t.filter(i=>i.tag===e.tag);if(o.length>0)return o.find(i=>i.format===e.format)??o[0]}let n,r;if(Nr(e)){r=e.value;let o=t.filter(i=>i.identify?.(r));if(o.length>1){let i=o.filter(s=>s.test);i.length>0&&(o=i)}n=o.find(i=>i.format===e.format)??o.find(i=>!i.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){let o=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${o} value`)}return n}function Onr(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],i=(Nr(t)||_i(t))&&t.anchor;i&&hpe(i)&&(n.add(i),o.push(`&${i}`));let s=t.tag??(e.default?null:e.tag);return s&&o.push(r.directives.tagString(s)),o.join(" ")}function X0(t,e,n,r){if(Po(t))return t.toString(e,n,r);if(ib(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let o,i=Oo(t)?t:e.doc.createNode(t,{onTagObj:l=>o=l});o??(o=Mnr(e.doc.schema.tags,i));let s=Onr(i,o,e);s.length>0&&(e.indentAtStart=(e.indentAtStart??0)+s.length+1);let a=typeof o.stringify=="function"?o.stringify(i,e,n,r):Nr(i)?QN(i,e,n,r):i.toString(e,n,r);return s?Nr(i)||a[0]==="{"||a[0]==="["?`${s} ${a}`:`${s}
${e.indent}${a}`:a}var b7=b(()=>{gpe();zo();h7();v7()});function qzt({key:t,value:e},n,r,o){let{allNullValues:i,doc:s,indent:a,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=n,f=Oo(t)&&t.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(_i(t)||!Oo(t)&&typeof t=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!t||f&&e==null&&!n.inFlow||_i(t)||(Nr(t)?t.type===ln.BLOCK_FOLDED||t.type===ln.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!i),indent:a+l});let m=!1,h=!1,g=X0(t,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(i||e==null)return m&&r&&r(),g===""?"?":p?`? ${g}`:g}else if(i&&!d||e==null&&p)return g=`? ${g}`,f&&!m?g+=kx(g,n.indent,c(f)):h&&o&&o(),g;m&&(f=null),p?(f&&(g+=kx(g,n.indent,c(f))),g=`? ${g}
`)),m<t.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=d.reduce((y,v)=>y+v.length+2,2)+(w.length+2)>e.options.lineWidth)),c&&(w+=",")),g&&(w+=kx(w,r,a(g))),d.push(w),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!c){let m=d.reduce((h,g)=>h+g.length+2,2);c=e.options.lineWidth>0&&m>e.options.lineWidth}if(c){let m=f;for(let h of d)m+=h?`
${i}${o}${h}`:`
`;return`${m}
${o}${p}`}else return`${f}${s}${d.join(" ")}${s}${p}`}function Ape({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let i=nw(e(r),t);n.push(i.trimStart())}}var GUe=b(()=>{zo();b7();h7()});function hA(t,e){let n=Nr(e)?e.value:e;for(let r of t)if(Po(r)&&(r.key===e||r.key===n||Nr(r.key)&&r.key.value===n))return r}var $a,gA=b(()=>{GUe();KUe();bpe();zo();mA();Jl();$a=class extends lj{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(ob,e),this.items=[]}static from(e,n,r){let{keepUndefined:o,replacer:i}=r,s=new this(e),a=(l,c)=>{if(typeof i=="function")c=i.call(n,l,c);else if(Array.isArray(i)&&!i.includes(l))return;(c!==void 0||o)&&s.items.push(dj(l,c,r))};if(n instanceof Map)for(let[l,c]of n)a(l,c);else if(n&&typeof n=="object")for(let l of Object.keys(n))a(l,n[l]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,n){let r;Po(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new sl(e,e?.value):r=new sl(e.key,e.value);let o=hA(this.items,r.key),i=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);Nr(o.value)&&vpe(r.value)?o.value.value=r.value:o.value=r.value}else if(i){let s=this.items.findIndex(a=>i(r,a)<0);s===-1?this.items.push(r):this.items.splice(s,0,r)}else this.items.push(r)}delete(e){let n=hA(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=hA(this.items,e)?.value;return(!n&&Nr(o)?o.value:o)??void 0}has(e){return!!hA(this.items,e)}set(e,n){this.add(new sl(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let i of this.items)Ppe(n,o,i);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(let o of this.items)if(!Po(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Epe(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}}});var lb,fj=b(()=>{zo();gA();lb={collection:"map",default:!0,nodeClass:$a,tag:"tag:yaml.org,2002:map",resolve(t,e){return bf(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>$a.from(t,e,n)}});function Mpe(t){let e=Nr(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var _f,yA=b(()=>{p7();GUe();bpe();zo();Jl();fA();_f=class extends lj{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Z0,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Mpe(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Mpe(e);if(typeof r!="number")return;let o=this.items[r];return!n&&Nr(o)?o.value:o}has(e){let n=Mpe(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Mpe(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];Nr(o)&&vpe(n)?o.value=n:this.items[r]=n}toJSON(e,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let i of this.items)r.push(Gc(i,String(o++),n));return r}toString(e,n,r){return e?Epe(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(e,n,r){let{replacer:o}=r,i=new this(e);if(n&&Symbol.iterator in Object(n)){let s=0;for(let a of n){if(typeof o=="function"){let l=n instanceof Set?a:String(s++);a=o.call(n,l,a)}i.items.push(J0(a,void 0,r))}}return i}}});var cb,pj=b(()=>{zo();yA();cb={collection:"seq",default:!0,nodeClass:_f,tag:"tag:yaml.org,2002:seq",resolve(t,e){return sb(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>_f.from(t,e,n)}});var wA,_7=b(()=>{v7();wA={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),QN(t,e,n,r)}}});var e1,Ope=b(()=>{Jl();e1={identify:t=>t==null,createNode:()=>new ln(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ln(null),stringify:({source:t},e)=>typeof
`:" ")}return QN({comment:t,type:e,value:a},r,o,i)}}});function eBe(t,e){if(sb(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!Po(r)){if(bf(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let o=r.items[0]||new sl(new ln(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}
`}}});function Tx(t,{flow:e,indicator:n,next:r,offset:o,onError:i,parentIndent:s,startOnNewline:a}){let l=!1,c=a,u=a,d="",f="",p=!1,m=!1,h=null,g=null,w=null,y=null,v=null,_=null,S=null;for(let C of t)switch(m&&(C.type!=="space"&&C.type!=="newline"&&C.type!=="comma"&&i(C.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(c&&C.type!=="comment"&&C.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),C.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&C.source.includes(" ")&&(h=C),u=!0;break;case"comment":{u||i(C,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=C.source.substring(1)||" ";d?d+=f+T:d=T,f="",c=!1;break}case"newline":c?d?d+=C.source:(!_||n!=="seq-item-ind")&&(l=!0):f+=C.source,c=!0,p=!0,(g||w)&&(y=C),u=!0;break;case"anchor":g&&i(C,"MULTIPLE_ANCHORS","A node can have at most one anchor"),C.source.endsWith(":")&&i(C.offset+C.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=C,S??(S=C.offset),c=!1,u=!1,m=!0;break;case"tag":{w&&i(C,"MULTIPLE_TAGS","A node can have at most one tag"),w=C,S??(S=C.offset),c=!1,u=!1,m=!0;break}case n:(g||w)&&i(C,"BAD_PROP_ORDER",`Anchors and tags must be after the ${C.source} indicator`),_&&i(C,"UNEXPECTED_TOKEN",`Unexpected ${C.source} in ${e??"collection"}`),_=C,c=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(e){v&&i(C,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),v=C,c=!1,u=!1;break}default:i(C,"UNEXPECTED_TOKEN",`Unexpected ${C.type} token`),c=!1,u=!1}let k=t[t.length-1],x=k?k.offset+k.source.length:o;return m&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&i(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(c&&h.indent<=s||r?.type==="block-map"||r?.type==="block-seq")&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:_,spaceBefore:l,comment:d,hasNewline:p,anchor:g,tag:w,newlineAfterProp:y,end:x,start:S??x}}var R7=b(()=>{});function bA(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(bA(e.key)||bA(e.value))return!0}return!1;default:return!0}}var qpe=b(()=>{});function N7(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&bA(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}var fBe=b(()=>{qpe()});function Kpe(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(i,s)=>i===s||Nr(i)&&Nr(s)&&i.value===s.value;return e.some(i=>o(i.key,n))}var pBe=b(()=>{zo()});function xUt({composeNode:t,composeEmptyNode:e},n,r,o,i){let s=i?.nodeClass??$a,a=new s(n.schema);n.atRoot&&(n.atRoot=!1);let l=r.offset,c=null;for(let u of r.items){let{start:d,key:f,sep:p,value:m}=u,h=Tx(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!0}),g=!h.found;if(g){if(f&&(f.type==="block-seq"?o(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&o(l,"BAD_INDENT",_Ut)),!h.anchor&&!h.tag&&!p){c=h.end,h.comment&&(a.comment?a.comment+=`
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||bA(f))&&o(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&o(l,"BAD_INDENT",_Ut);n.atKey=!0;let w=h.end,y=f?t(n,f,h,o):e(n,w,d,null,h,o);n.schema.compat&&N7(r.indent,f,o),n.atKey=!1,Kpe(n,a.items,y)&&o(w,"DUPLICATE_KEY","Map keys must be unique");let v=Tx(p??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=v.end,v.found){g&&(m?.type==="block-map"&&!v.hasNewline&&o(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start<v.found.offset-1024&&o(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=m?t(n,m,v,o):e(n,l,p,null,v,o);n.schema.compat&&N7(r.indent,m,o),l=_.range[2];let S=new sl(y,_);n.options.keepSourceTokens&&(S.srcToken=u),a.items.push(S)}else{g&&o(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),v.comment&&(y.comment?y.comment+=`
`+v.comment:y.comment=v.comment);let _=new sl(y);n.options.keepSourceTokens&&(_.srcToken=u),a.items.push(_)}}return c&&c<l&&o(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,l,c??l],a}var _Ut,SUt=b(()=>{mA();gA();R7();qpe();fBe();pBe();_Ut="All mapping items must start at the same column"});function CUt({composeNode:t,composeEmptyNode:e},n,r,o,i){let s=i?.nodeClass??_f,a=new s(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset,c=null;for(let{start:u,value:d}of r.items){let f=Tx(u,{indicator:"seq-item-ind",next:d,offset:l,onError:o,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?o(f.end,"BAD_INDENT","All sequence items must start at the same column"):o(l,"MISSING_CHAR","Sequence item without - indicator");else{c=f.end,f.comment&&(a.comment=f.comment);continue}let p=d?t(n,d,f,o):e(n,f.end,u,null,f,o);n.schema.compat&&N7(r.indent,d,o),l=p.range[2],a.items.push(p)}return a.range=[r.offset,l,c??l],a}var kUt=b(()=>{yA();R7();fBe()});function Ix(t,e,n,r){let o="";if(t){let i=!1,s="";for(let a of t){let{source:l,type:c}=a;switch(c){case"space":i=!0;break;case"comment":{n&&!i&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=l.substring(1)||" ";o?o+=s+u:o=u,s="";break}case"newline":o&&(s+=l),i=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:o,offset:e}}var vj=b(()=>{});function TUt({composeNode:t,composeEmptyNode:e},n,r,o,i){let s=r.start.source==="{",a=s?"flow map":"flow sequence",l=i?.nodeClass??(s?$a:_f),c=new l(n.schema);c.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset+r.start.source.length;for(let g=0;g<r.items.length;++g){let w=r.items[g],{start:y,key:v,sep:_,value:S}=w,k=Tx(y,{flow:a,indicator:"explicit-key-ind",next:v??_?.[0],offset:d,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!k.found){if(!k.anchor&&!k.tag&&!_&&!S){g===0&&k.comma?o(k.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):g<r.items.length-1&&o(k.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),k.comment&&(c.comment?c.comment+=`
`+k.comment:c.comment=k.comment),d=k.end;continue}!s&&n.options.strict&&bA(v)&&o(v,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)k.comma&&o(k.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(k.comma||o(k.start,"MISSING_CHAR",`Missing , between ${a} items`),k.comment){let x="";e:for(let C of y)switch(C.type){case"comma":case"space":break;case"comment":x=C.source.substring(1);break e;default:break e}if(x){let C=c.items[c.items.length-1];Po(C)&&(C=C.value??C.key),C.comment?C.comment+=`
`+x:C.comment=x,k.comment=k.comment.substring(x.length+1)}}if(!s&&!_&&!k.found){let x=S?t(n,S,k,o):e(n,k.end,_,null,k,o);c.items.push(x),d=x.range[2],hBe(S)&&o(x.range,"BLOCK_IN_FLOW",mBe)}else{n.atKey=!0;let x=k.end,C=v?t(n,v,k,o):e(n,x,y,null,k,o);hBe(v)&&o(C.range,"BLOCK_IN_FLOW",mBe),n.atKey=!1;let T=Tx(_??[],{flow:a,indicator:"map-value-ind",next:S,offset:C.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(T.found){if(!s&&!k.found&&n.options.strict){if(_)for(let O of _){if(O===T.found)break;if(O.type==="newline"){o(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}k.start<T.found.offset-1024&&o(T.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?o(S,"MISSING_CHAR",`Missing space after : in ${a}`):o(T.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let I=S?t(n,S,T,o):T.found?e(n,T.end,_,null,T,o):null;I?hBe(S)&&o(I.range,"BLOCK_IN_FLOW",mBe):T.comment&&(C.comment?C.comment+=`
`+T.comment:C.comment=T.comment);let M=new sl(C,I);if(n.options.keepSourceTokens&&(M.srcToken=w),s){let O=c;Kpe(n,O.items,C)&&o(x,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(M)}else{let O=new $a(n.schema);O.flow=!0,O.items.push(M);let D=(I??C).range;O.range=[C.range[0],D[1],D[2]],c.items.push(O)}d=I?I.range[2]:T.end}}let f=s?"}":"]",[p,...m]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let g=a[0].toUpperCase()+a.substring(1),w=u?`${g} must end with a ${f}`:`${g} in block collection must be sufficiently indented and end with a ${f}`;o(d,u?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let g=Ix(m,h,n.options.strict,o);g.comment&&(c.comment?c.comment+=`
`+g.comment:c.comment=g.comment),c.range=[r.offset,h,g.offset]}else c.range=[r.offset,h,h];return c}var mBe,hBe,IUt=b(()=>{zo();mA();gA();yA();vj();R7();qpe();pBe();mBe="Block collections are not allowed within flow collections",hBe=t=>t&&(t.type==="block-map"||t.type==="block-seq")});function gBe(t,e,n,r,o,i){let s=n.type==="block-map"?xUt(t,e,n,r,i):n.type==="block-seq"?CUt(t,e,n,r,i):TUt(t,e,n,r,i),a=s.constructor;return o==="!"||o===a.tagName?(s.tag=a.tagName,s):(o&&(s.tag=o),s)}function PUt(t,e,n,r,o){let i=r.tag,s=i?e.directives.tagName(i.source,f=>o(i,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,m=f&&i?f.offset>i.offset?f:i:f??i;m&&(!p||p.offset<m.offset)&&o(m,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!i||!s||s==="!"||s===$a.tagName&&a==="map"||s===_f.tagName&&a==="seq")return gBe(t,e,n,o,s);let l=e.schema.tags.find(f=>f.tag===s&&f.collection===a);if(!l){let f=e.schema.knownTags[s];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?o(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):o(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),gBe(t,e,n,o,s)}let c=gBe(t,e,n,o,s,l),u=l.resolve?.(c,f=>o(i,"TAG_RESOLVE_FAILED",f),e.options)??c,d=Oo(u)?u:new ln(u);return d.range=c.range,d.tag=s,l?.format&&(d.format=l.format),d}var AUt=b(()=>{zo();Jl();gA();yA();SUt();kUt();IUt()});function yBe(t,e,n){let r=e.offset,o=znr(e,t.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let i=o.mode===">"?ln.BLOCK_FOLDED:ln.BLOCK_LITERAL,s=e.source?Unr(e.source):[],a=s.length;for(let h=s.length-1;h>=0;--h){let g=s[h][1];if(g===""||g==="\r")a=h;else break}if(a===0){let h=o.chomp==="+"&&s.length>0?`
`.repeat(Math.max(1,s.length-1)):"",g=r+o.length;return e.source&&(g+=e.source.length),{value:h,type:i,comment:o.comment,range:[r,g,g]}}let l=e.indent+o.indent,c=e.offset+o.length,u=0;for(let h=0;h<a;++h){let[g,w]=s[h];if(w===""||w==="\r")o.indent===0&&g.length>l&&(l=g.length);else{g.length<l&&n(c+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(l=g.length),u=h,l===0&&!t.atRoot&&n(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=g.length+w.length+1}for(let h=s.length-1;h>=a;--h)s[h][0].length>l&&(a=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=s[h][0].slice(l)+`
`;for(let h=u;h<a;++h){let[g,w]=s[h];c+=g.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&g.length<l){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(c-w.length-(y?2:1),"BAD_INDENT",_),g=""}i===ln.BLOCK_LITERAL?(d+=f+g.slice(l)+w,f=`
`}let m=r+o.length+e.source.length;return{value:d,type:i,comment:o.comment,range:[r,m,m]}}function znr({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=e[0],i=o[0],s=0,a="",l=-1;for(let f=1;f<o.length;++f){let p=o[f];if(!a&&(p==="-"||p==="+"))a=p;else{let m=Number(p);!s&&m?s=m:l===-1&&(l=t+f)}}l!==-1&&r(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let c=!1,u="",d=o.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":c=!0;case"newline":d+=p.source.length;break;case"comment":n&&!c&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:i,indent:s,chomp:a,comment:u,length:d}}function Unr(t){let e=t.split(/\n( *)/),n=e[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let s=1;s<e.length;s+=2)i.push([e[s],e[s+1]]);return i}var wBe=b(()=>{Jl()});function vBe(t,e,n){let{offset:r,type:o,source:i,end:s}=t,a,l,c=(f,p,m)=>n(r+f,p,m);switch(o){case"scalar":a=ln.PLAIN,l=Bnr(i,c);break;case"single-quoted-scalar":a=ln.QUOTE_SINGLE,l=jnr(i,c);break;case"double-quoted-scalar":a=ln.QUOTE_DOUBLE,l=Hnr(i,c);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+i.length,r+i.length]}}let u=r+i.length,d=Ix(s,u,e,n);return{value:l,type:a,comment:d.comment,range:[r,u,d.offset]}}function Bnr(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),EUt(t)}function jnr(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),EUt(t.slice(1,-1)).replace(/''/g,"'")}function EUt(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
`,r:"\r",t:" ",v:"\v",N:" ",_:"",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "}});function _Be(t,e,n,r){let{value:o,type:i,comment:s,range:a}=e.type==="block-scalar"?yBe(t,e,r):vBe(e,t.options.strict,r),l=n?t.directives.tagName(n.source,d=>r(n,"TAG_RESOLVE_FAILED",d)):null,c;t.options.stringKeys&&t.atKey?c=t.schema[tg]:l?c=Knr(t.schema,o,l,n,r):e.type==="scalar"?c=Gnr(t,o,e,r):c=t.schema[tg];let u;try{let d=c.resolve(o,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);u=Nr(d)?d:new ln(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(n??e,"TAG_RESOLVE_FAILED",f),u=new ln(o)}return u.range=a,u.source=o,i&&(u.type=i),l&&(u.tag=l),c.format&&(u.format=c.format),s&&(u.comment=s),u}function Knr(t,e,n,r,o){if(n==="!")return t[tg];let i=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(e))return a;let s=t.knownTags[n];return s&&!s.collection?(t.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(o(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[tg])}function Gnr({atKey:t,directives:e,schema:n},r,o,i){let s=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(r))||n[tg];if(n.compat){let a=n.compat.find(l=>l.default&&l.test?.test(r))??n[tg];if(s.tag!==a.tag){let l=e.tagString(s.tag),c=e.tagString(a.tag),u=`Value may be parsed as either ${l} or ${c}`;i(o,"TAG_RESOLVE_FAILED",u,!0)}}return s}var MUt=b(()=>{zo();Jl();wBe();bBe()});function OUt(t,e,n){if(e){n??(n=e.length);for(let r=n-1;r>=0;--r){let o=e[r];switch(o.type){case"space":case"comment":case"newline":t-=o.source.length;continue}for(o=e[++r];o?.type==="space";)t+=o.source.length,o=e[++r];break}}return t}var RUt=b(()=>{});function xBe(t,e,n,r){let o=t.atKey,{spaceBefore:i,comment:s,anchor:a,tag:l}=n,c,u=!0;switch(e.type){case"alias":c=Ynr(t,e,r),(a||l)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=_Be(t,e,l,r),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=PUt(Znr,t,e,n,r),a&&(c.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=Gpe(t,e.offset,void 0,null,n,r)),a&&c.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&t.options.stringKeys&&(!Nr(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&r(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(c.spaceBefore=!0),s&&(e.type==="scalar"&&e.source===""?c.comment=s:c.commentBefore=s),t.options.keepSourceTokens&&u&&(c.srcToken=e),c}function Gpe(t,e,n,r,{spaceBefore:o,comment:i,anchor:s,tag:a,end:l},c){let u={type:"scalar",offset:OUt(e,n,r),indent:-1,source:""},d=_Be(t,u,a,c);return s&&(d.anchor=s.source.substring(1),d.anchor===""&&c(s,"BAD_ALIAS","Anchor cannot be an empty string")),o&&(d.spaceBefore=!0),i&&(d.comment=i,d.range[2]=l),d}function Ynr({options:t},{offset:e,source:n,end:r},o){let i=new Y0(n.substring(1));i.source===""&&o(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&o(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let s=e+n.length,a=Ix(r,s,t.strict,o);return i.range=[e,s,a.offset],a.comment&&(i.comment=a.comment),i}var Znr,NUt=b(()=>{f7();zo();AUt();MUt();vj();RUt();Znr={composeNode:xBe,composeEmptyNode:Gpe}});function LUt(t,e,{offset:n,start:r,value:o,end:i},s){let a=Object.assign({_directives:e},t),l=new vA(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=Tx(r,{indicator:"doc-start",next:o??i?.[0],offset:n,onError:s,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!u.hasNewline&&s(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=o?xBe(c,o,u,s)
\r `),PBe=t=>!t||err.has(t),$7=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`
`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Xpe(e),r=bj(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Xpe(e),r=bj(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}});function trr(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new F7||null,prettyErrors:e}}function U7(t,e={}){let{lineCounter:n,prettyErrors:r}=trr(e),o=new z7(n?.addNewLine),i=new D7(e),s=null;for(let a of i.compose(o.parse(t),!0,t.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new ub(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(s.errors.forEach(dBe(t,n)),s.warnings.forEach(dBe(t,n))),s}var GUt=b(()=>{SBe();A7();O7();WUe();zo();EBe();MBe()});var OBe=b(()=>{SBe();A7();uBe();O7();f7();zo();mA();Jl();gA();yA();Ype();ABe();EBe();MBe();GUt();d7()});var RBe=b(()=>{OBe();OBe()});function orr(t){let e=rrr.exec(t);if(!e)throw new Fa("SKILL.md must begin with a YAML frontmatter block delimited by ---");return{yaml:e[1]??"",body:e[2]??""}}function irr(t,e){let n=e.linePos?.[0]?.line,r=n===void 0?void 0:t.split(/\r?\n/)[n-1];if(e.code==="BLOCK_AS_IMPLICIT_KEY"){let o=/^(description[ \t]*:[ \t]*([^'"\r\n]*: [^\r\n]*))$/.exec(r??"");if(o?.[1]!==void 0&&o[2]!==void 0)return new Fa('The description contains ": " and must be quoted.',o[1])}return new Fa(`SKILL.md frontmatter YAML is invalid: ${e.message}`,r)}function eme(t,e,n){if(!bf(t.contents))return;let o=t.contents.items.find(l=>Nr(l.key)&&l.key.value===n)?.key?.range?.[0];if(o===void 0)return;let i=e.lastIndexOf(`
`,o-1)+1,s=e.indexOf(`
`,o),a=s===-1?e.length:s;return e.slice(i,a).replace(/\r$/,"")}function _j(t,e){let n=t.get(e);return typeof n=="string"?n:void 0}function YUt(t,e){let n=t.get(e);return typeof n=="boolean"?n:void 0}function srr(t){let e=t.get("metadata");if(!bf(e))return[];let n=e.get("copilot-enabled-agents");return typeof n!="string"||n.trim().length===0?[]:n.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function Fm(t,e){let{yaml:n,body:r}=orr(t),o=U7(n,{keepSourceTokens:!0});if(o.errors.length>0)throw irr(n,o.errors[0]);if(!bf(o.contents))throw new Fa("SKILL.md frontmatter must be a YAML mapping");let i=_j(o,"name");if(i===void 0)throw o.has("name")?new Fa("Skill `name` must be a string",eme(o,n,"name")):new Fa("SKILL.md frontmatter is missing required field `name`");tme(i,e,eme(o,n,"name"));let s=_j(o,"description");if(s===void 0)throw o.has("description")?new Fa("Skill `description` must be a string",eme(o,n,"description")):new Fa("SKILL.md frontmatter is missing required field `description`");return JUt(s,eme(o,n,"description")),{frontmatter:{name:i,description:s,license:_j(o,"license"),compatibility:_j(o,"compatibility"),allowedTools:_j(o,"allowed-tools"),model:_j(o,"model"),disableModelInvocation:YUt(o,"disable-model-invocation"),userInvocable:YUt(o,"user-invocable"),enabledAgents:srr(o)},body:r,doc:o}}function tme(t,e,n){if(typeof t!="string"||t.length===0)throw new Fa("Skill `name` must be a non-empty string",n);if(t.length>n1)throw new Fa(`Skill \`name\` must be at most ${n1} characters (got ${t.length})`,n);if(!B7.test(t))throw new Fa(ZUt,n);if(t!==e)throw new Fa(ZUt,n)}function JUt(t,e){if(typeof t!="string"||t.length===0)throw new Fa("Skill `description` must be a non-empty string",e);if(t.length>r1)throw new Fa(`Skill \`description\` must be at most ${r1} characters (got ${t.length})`,e)}function xA(t,e,n){n===void 0?t.has(e)&&t.delete(e):t.set(e,n)}function SA(t,e={}){let{doc:n,body:r}=t;return"name"in e&&xA(n,"name",e.name),"description"in e&&xA(n,"description",e.description),"license"in e&&xA(n,"license",e.license),"compatibility"in e&&xA(n,"compatibility",e.compatibility),"allowedTools"in e&&xA(n,"allowed-tools",e.allowedTools),"model"in e&&xA(n,"model",e.model),"disableModelInvocation"in e&&xA(n,"disable-model-invocation",e.disableModelInvocation),"userInvocable"in e&&xA(n,"user-invocable",e.userInvocable),e.enabledAgents!==void 0&&arr(n,e.enabledAgents),`---
${n.toString().replace(/\n+$/,"")}
---
${r}`}function arr(t,e){let n=t.get("metadata");bf(n)||(n=new $a,t.set("metadata",n));let r=n,o=e.join(","),i=new ln(o),s=r.get("copilot-enabled-agents",!0);Nr(s)?i.type=s.type??i.type:o.length===0&&(i.type="QUOTE_DOUBLE"),r.set("copilot-enabled-agents",i)}var rrr,B7,n1,r1,ZUt,Fa,Q0=b(()=>{RBe();rrr=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/,B7=/^[a-z0-9]+(-[a-z0-9]+)*$/,n1=64,r1=1024,ZUt="Use the same lowercase, hyphenated name in the file and folder.";Fa=class extends Error{constructor(n,r){super(n);this.offendingText=r;this.name="SkillFormatError"}}});function nme(t){XUt.set(QUt,t)}function eBt(){return or(QUt,{store:XUt})}var XUt,QUt,NBe=b(()=>{gs();XUt=nm(),QUt=Kr(0)});function rme(t,e){let n=t.replace(/[/\\]+$/,""),r=e.replace(/^[/\\]+/,"");return`${n}/${r}`}var LBe=b(()=>{xt()});function xj(t){let e=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(t);if(!e)return null;let n=U7(e[1]);if(n.errors.length>0)return null;let r=n.getIn(["metadata","copilot-builtin-version"]);if(typeof r!="string"&&typeof r!="number"||!/^\d+$/.test(String(r)))return null;let o=Number(r);return Number.isSafeInteger(o)?o:null}var DBe=b(()=>{RBe()});async function j7(t,e,n){let r=new Array(t.length),o=0,i=Math.min(e,t.length);return await Promise.all(Array.from({length:i},async()=>{for(;o<t.length;){let s=o;o+=1,r[s]=await n(t[s],s)}})),r}var $Be=b(()=>{});async function FBe(t){let{skillsFolderRelPath:e,skillsFolderAbsPath:n,adapter:r}=t;if(!await r.exists(e))return{accepted:[],rejected:[]};let o=await r.list(e),i=await j7([...o.folders].sort(),lrr,async l=>{let c=Nse(l),u=Cr(l,"SKILL.md"),d=n!==null?Cr(n,c):l,f=Cr(d,"SKILL.md"),p;try{p=await r.read(u)}catch{return null}let m;try{m=Fm(p,c)}catch(g){let w=g instanceof Error?g.message:String(g);return V(`[skills] Skipping ${u}: ${w}`),g instanceof Fa?{name:c,filePath:f,dirPath:d,reason:w,offendingText:g.offendingText}:null}let h=m.frontmatter;return{builtin:crr.has(h.name)&&xj(p)!==null,name:h.name,description:h.description,filePath:f,dirPath:d,body:m.body,license:h.license,compatibility:h.compatibility,allowedTools:h.allowedTools,model:h.model,disableModelInvocation:h.disableModelInvocation,userInvocable:h.userInvocable,enabledAgents:h.enabledAgents,location:{kind:"canonical"}}}),s=[],a=[];for(let l of i)l!==null&&("reason"in l?a.push(l):s.push(l));return{accepted:s,rejected:a}}var lrr,crr,zBe=b(()=>{ge();ff();DBe();uI();$Be();Q0();lrr=16,crr=new Set([..._h,...qre].map(t=>t.name))});function tBt(t,e){let n=e>>>0;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return n>>>0}async function UBe(t,e){let n=await nBt(t,"",e);n.sort((i,s)=>i.relPath<s.relPath?-1:i.relPath>s.relPath?1:0);let r=2166136261,o=2216829733;for(let i of n){let s=`${i.relPath}-${i.content}`;r=tBt(s,r),o=tBt(s,o)}return r.toString(16).padStart(8,"0")+o.toString(16).padStart(8,"0")}async function nBt(t,e,n){let r;try{r=await n.list(t)}catch{return[]}let o=[];for(let i of r){let s=Cr(t,i),a=e.length===0?i:Cr(e,i),l=!1;try{l=await n.isSymlink(s)}catch{continue}if(l)continue;let c=!1;try{c=await n.isDirectory(s)}catch{c=!1}if(c){let d=await nBt(s,a,n);o.push(...d);continue}let u;try{u=await n.readFile(s)}catch{u="unreadable"}o.push({relPath:a,content:u})}return o}var BBe=b(()=>{ff()});async function jBe(t){let{vaultRootAbsPath:e,agentDirsProjectRel:n,fs:r}=t,o=[],i=[];return await Promise.all(Object.entries(n).map(async([s,a])=>{let l=Cr(e,a);if(!await rBt(r,l)||!await oBt(r,l))return;let c;try{c=await r.list(l)}catch(d){V(`[skills] Could not list ${l}: ${d instanceof Error?d.message:String(d)}`);return}let u=await Promise.all(c.sort().map(async d=>{let f=Cr(l,d),p=!1;try{p=await r.isSymlink(f)}catch{}if(p||!await oBt(r,f))return null;let m=Cr(f,"SKILL.md");if(!await rBt(r,m))return null;let h;try{h=await r.readFile(m)}catch{return null}let g;try{g=Fm(h,d)}catch(v){let _=v instanceof Error?v.message:String(v);return V(`[skills] Skipping ${m}: ${_}`),v instanceof Fa?{name:d,filePath:m,dirPath:f,reason:_,offendingText:v.offendingText}:null}let w=await UBe(f,r);return{agent:s,name:d,filePath:m,dirPath:f,co
To enable it for ${e}, Copilot needs to move it to a shared location
so both agents stay in sync.`;case"project-mirrored":return`The same skill is currently duplicated in ${Orr(t.sourceDuplicatePaths.length)}:`;case"disable-last-agent":return"This skill currently lives only in:";case"proactive-consolidate":return"The same skill is currently duplicated in:"}}function Arr(t){let e=t.targetAgentDisplayName??"this agent";switch(t.variant){case"project-single":return`You can still edit the skill exactly as before — there's just one copy now,
so changes are visible to both agents immediately.`;case"project-mirrored":return`After this, edits to the skill are visible to all ${t.actionLines.filter(n=>n.verb==="Create").length} agents.`;case"disable-last-agent":return`If you disable ${e}, the file has nowhere to live in its project folder.
Copilot can preserve it by moving the skill to your shared skills folder with
no agents enabled — you can toggle agents back on any time, or delete it later
from the Skills tab.`;case"proactive-consolidate":return`Editing, renaming, or deleting one copy would silently diverge from the others.
Copilot can consolidate them into a single shared location, with a shortcut in
each agent folder so all agents still see the skill.
After this, your edits stay in sync across all agents automatically.`}}function Err(t){let e=t.targetAgentDisplayName??"agent";switch(t.variant){case"project-single":case"project-mirrored":return`Move and enable ${e}`;case"disable-last-agent":return`Move and disable ${e}`;case"proactive-consolidate":return"Consolidate"}}function Mrr(t){if(t.skill.location.kind!=="project")return"agent";let[e]=t.skill.location.agentDirs;return e??"agent"}function Orr(t){return t===2?"two project folders":t===3?"three project folders":`${t} project folders`}var ABt,Tj,pje=b(()=>{ge();ABt=require("obsidian"),Tj=class extends ABt.Modal{constructor(n,r){super(n);this.confirmed=!1;this.suppressFuture=!1;this.args=r,this.setTitle(Irr(r))}onOpen(){let{contentEl:n}=this;if(n.empty(),n.addClass("tw-flex","tw-flex-col","tw-gap-3"),n.createEl("p",{cls:"tw-m-0 tw-text-ui-smaller tw-text-normal tw-whitespace-pre-line",text:Prr(this.args)}).setAttr("data-test-id","migrate-confirm-body"),this.args.sourceDuplicatePaths.length>0){let f=n.createEl("ul",{cls:"tw-m-0 tw-list-none tw-space-y-1 tw-pl-0 tw-font-mono tw-text-ui-smaller tw-text-normal"});for(let p of this.args.sourceDuplicatePaths){let m=f.createEl("li",{cls:"tw-flex tw-items-baseline tw-gap-2"});m.createSpan({cls:"tw-text-faint",text:"•"}),m.createSpan({cls:"tw-flex-1",text:p})}}this.args.resolvedCanonicalName!==this.args.skill.name&&n.createEl("p",{cls:"tw-m-0 tw-text-ui-smaller tw-text-warning",text:`The name "${this.args.skill.name}" is already taken in your shared folder. The migrated skill will be named "${this.args.resolvedCanonicalName}".`}),n.createDiv({cls:"tw-text-ui-smaller tw-text-muted",text:"Copilot will:"}).setAttr("data-test-id","migrate-confirm-will-header");let i=n.createEl("ul",{cls:"tw-m-0 tw-list-none tw-space-y-1 tw-pl-0 tw-font-mono tw-text-ui-smaller tw-text-normal"});for(let f of this.args.actionLines){let p=i.createEl("li",{cls:"tw-flex tw-items-baseline tw-gap-2"});p.createSpan({cls:"tw-text-faint",text:"•"});let m=p.createSpan({cls:"tw-flex-1"});m.createSpan({cls:"tw-inline-block tw-min-w-[64px] tw-text-muted",text:f.verb}),m.createSpan({text:` ${f.detail}`}),f.note!==void 0&&f.note.length>0&&m.createSpan({cls:"tw-ml-1.5 tw-font-sans tw-text-smallest tw-text-faint",text:f.note})}let s=Arr(this.args);s!==null&&n.createEl("p",{cls:"tw-m-0 tw-text-ui-smaller tw-text-muted tw-whitespace-pre-line",text:s});let a=n.createEl("label",{cls:"tw-flex tw-items-center tw-gap-2 tw-text-ui-smaller tw-text-normal tw-cursor-pointer"}),l=a.createEl("input",{cls:"tw-size-checkbox",attr:{type:"checkbox"}});l.addEventListener("change",()=>{this.suppressFuture=l.checked}),a.createSpan({text:"Don't ask again for future migrations"});let c=n.createDiv({cls:"tw-flex tw-justify-end tw-gap-2 tw-pt-2"});c.createEl("button",{cls:"mod-secondary",text:"Cancel"}).addEventListener("click",()=>{this.close()}),c.createEl("button",{cls:"mod-cta",text:Err(this.args)}).addEventListener("click",()=>{this.confirmed=!0;let f=this.args.onConfirm(this.suppressFuture);f instanceof Promise&&f.catch(p=>W("MigrateSkillConfirmModal onConfirm failed",p)),this.close()})}onClose(){this.confirmed||this.args.onCancel?.(),this.contentEl.empty()}}});function Drr(t){return{name:t.name,description:t.description,allowedTools:t.allowedTools??"",model:t.model??"",disableAutoInvocation:t.disableModelInvocation===!0,hideFromSlashMenu:t.userInvocable===!1}}function $rr(t){return t.length===0?"Name is required.":t.length>n1?`Name must be at most ${n1} characters.`:B7.test(t)?null:"Lowercase a–z, 0–9, and hyphens only — no leading, trailing, or consecutive hyphens."}function Frr(t){return t.trim().length===0?"Description is required.":t.length>r1?`Description must be at most ${r1} characters.`:null}var EBt,Jn,Rrr,Z7,lme,cme,Nrr,mje,hje,Lrr,gje=b(()=>{ot();EP();Vl();tA();De();ge();Qa();EBt=require("obsidian"),Jn=R(U());Q0();Rrr=({skill:t,skillsFolderRel:e,collisionError:n,saving:r,onCancel:o,onSave:i})=>{let[s,a]=Jn.default.useState(()=>Drr(t)),l=e.replace(/\/+$/,""),c=$rr(s.name),u=Frr(s.description),f=!(c!==null||u!==nu
${m4t}`,Jme.length);if(e<0)return null;let n=t.slice(Jme.length,e).trim();try{let r=JSON.parse(n);if(r.schemaVersion!==Xme)return null;let o=!!(r.sourceUrl??r.sourcePath);return!r.sourceType||!o||!r.fetchedAt||!r.fingerprint?null:r}catch{return null}}function p4t(t,e){let n=new Set,r=[];for(let o of t){let i=e(o);n.has(i)||(n.add(i),r.push(o))}return r}var Kor,Jme,m4t,Xme,Yor,Jor,jj=b(()=>{GF();ge();xy();Kor=["web","youtube","file"],Jme="<!-- copilot-context-cache",m4t="-->",Xme=1;Yor=Kor.join("|"),Jor=new RegExp(`^failed-(${Yor})-[0-9a-f]+\\.json$`)});function b4t(t){let e=new Map(t.materialized.filter(f=>!!f.snapshotAbsPath).map(f=>[`${f.type}:${f.source}`,f.snapshotAbsPath])),n=(f,p)=>{let m=e.get(`${f}:${p}`);return m?`${p} → \`${m}\``:p},r=f=>`\`${f.absPath??f.vaultPath}\``,o=[...t.folders.map(f=>ck("Included folders",r(f))),...t.properties.map(f=>ck("Included properties",f)),...t.notes.map(f=>ck("Included notes",r(f))),...t.extensions.map(f=>ck("Included file types",`\`${f}\``)),...t.tags.map(f=>ck("Included tags",f)),...t.webUrls.map(f=>ck("Included URLs",n("web",f))),...t.youtubeUrls.map(f=>ck("Included YouTube",n("youtube",f)))],i=[...t.materialized.filter(f=>f.type==="file").map(f=>ck("Materialized files",n(f.type,f.source))),...t.propertyNotes.map(f=>ck("Notes matching an included property",r(f)))],s=[...o,...i],a=s.length,l=s.slice(0,Xor),c=a-l.length,u=["<project_context>","Context sources for this project, with absolute paths. Folders and tags are","listed as sources, not expanded into member files — use your own search","(grep/glob/read) to enumerate them. Properties are listed as source labels and",'also expanded into the notes they match, under "Notes matching an included','property" (the label is listed first so it survives the entry cap).',"Materialized snapshots of URLs, YouTube transcripts, and PDFs/images are shown","inline as an absolute path after the source, formatted `<source> → <absolute path>`","— read that path directly. A source with no path isn't cached (not yet converted","or conversion failed); use the source itself."],d="";for(let f of l)f.section!==d&&(d=f.section,u.push("",`## ${d}`)),u.push(`- ${f.text}`);return c>0&&u.push("",`> Only the first ${l.length} of ${a} sources are listed; ${c} more are omitted. Use the declared context sources above with grep/glob/read to find the rest.`),u.push("</project_context>"),u.join(`
`)}function ck(t,e){return{section:t,text:e}}var Xor,_4t=b(()=>{Xor=100});function x4t(t){return t.absPath??t.vaultPath}function tir(t){let e=k4t.get(t);return e||(e=new Zme,k4t.set(t,e)),e}function P4t(t,e){return tir(t).runExclusive(e)}function Hj(t,e){let n=T4t(t).replace(/\/+$/,""),r=T4t(e).replace(/\/+$/,"");if(r===n)return"";let o=`${n}/`;if(!r.startsWith(o))throw new Error(`context-cache directory escapes root: ${e}`);return r.slice(o.length)}function T4t(t){return t.replace(/\\/g,"/")}async function i4e(t,e,n,r,o,i){let s=o??!1,a=ao(e),l=a?lk(a):void 0,c=i??l,u=Qme.get(e);if(u&&u.revision===c&&(!s||u.forceRetryFailed))return u.promise;let d=u?.promise,f=(async()=>(d&&await d.catch(()=>{}),nir(t,e,n,r,s)))().finally(()=>{Qme.get(e)?.promise===f&&Qme.delete(e)});return Qme.set(e,{promise:f,forceRetryFailed:s,revision:c}),f}async function nir(t,e,n,r,o){try{let i=ao(e);if(!i)return S4t;let s=lk(i),a=i.project.contextSource;if(!a)return{additionalDirectories:vY,projectContextBlock:C4t,contextSignature:s};let l=I4t(a.webUrls),c=I4t(a.youtubeUrls),u=[...l.map(ne=>({type:"web",url:ne})),...c.map(ne=>({type:"youtube",url:ne}))],{inclusions:d,exclusions:f}=Ua({inclusions:a.inclusions,exclusions:a.exclusions,isProject:!0}),p=d?.folderPatterns??[],m=d?.notePatterns??[],h=d?.extensionPatterns??[],g=d?.tagPatterns??[],w=d?.propertyPatterns??[],y=oir(t),{entries:v,additionalDirectories:_}=iir(t,p,n,y),S=sir(t,m,y),k=new Set(S.map(x4t)),x=air(t,w,f,y).filter(ne=>!k.has(x4t(ne))),C=d?Fj(t,a).map(ne=>({vaultPath:ne.path,ext:ne.extension.toLowerCase(),mtime:ne.stat.mtime,size:ne.stat.size,read:()=>t.vault.readBinary(ne)})):[];if(!(u.length>0||C.length>0||p.length>0||m.length>0||h.length>0||g.length>0||w.length>0||_.length>0))return{additionalDirectories:vY,projectContextBlock:C4t,contextSignature:s};r?.({phase:"resolve",resolved:C.length});let I=rk(t),M=zj(I),O=Hj(I,nY(t)),D=Hj(I,rY(t)),F=Hj(I,Ej(t,e)),{entries:q,wantedMarkerNames:Z,failures:re}=await t4e({remotesDir:O,filesDir:D,markerDir:F,fs:M,converters:A4t(),remotes:u,files:C,nowMs:Date.now(),forceRetryFailed:o,onProgress:r,withSourceLock:P4t});r?.({phase:"failures",failures:re});let ce=q.map(ne=>({...ne,snapshotAbsPath:Lje(t,ne.type,ne.cacheFileName)})),oe=b4t({folders:v,notes:S,extensions:h,tags:g,properties:w,propertyNotes:x,webUrls:l,youtubeUrls:c,materialized:ce});return await h4t(M,F,Z),H(`[project-context] materialized ${q.length} source(s) for ${e}; add-dir=${_.length}, failures=${re.length}`),{additionalDirectories:_.length>0?_:vY,projectContextBlock:oe,contextSignature:s}}catch(i){let s=Dt(i);return V(`[project-context] materialize failed for ${e}; continuing`,i),r?.({phase:"failures",failures:[{source:"Project context",kind:"file",error:s,usedStaleSnapshot:!1}]}),S4t}}function A4t(){return{fetchRemote:async t=>{let e=ua.getInstance(),n=t.type==="youtube"?(await e.youtube4llm(t.url)).response?.transcript??"":(await e.url4llm(t.url)).response??"";if(!n.trim())throw new Error(`empty content for ${t.url}`);return n},parseFile:async(t,e)=>{let{response:n}=await ua.getInstance().docs4llm(t,e),r=rir(n);if(!r.trim())throw new Error(`empty parse result for .${e}`);return r}}}async function E4t(t,e,n){if(!ao(e))return[{source:n.source,kind:n.kind,error:"Project not found",usedStaleSnapshot:!1}];let o=[],i=[];if(n.kind==="file"){let s=t.vault.getAbstractFileByPath(n.source);if(!(s instanceof Wj.TFile))return[{source:n.source,kind:"file",error:"File not found in vault",usedStaleSnapshot:!1}];i=[{vaultPath:s.path,ext:s.extension.toLowerCase(),mtime:s.stat.mtime,size:s.stat.size,read:()=>t.vault.readBinary(s)}]}else o=[{type:n.kind,url:n.source}];try{let s=rk(t),a=zj(s),{failures:l}=await t4e({remotesDir:Hj(s,nY(t)),filesDir:Hj(s,rY(t)),markerDir:Hj(s,Ej(t,e)),fs:a,converters:A4t(),remotes:o,files:i,nowMs:Date.now(),forceRetryFailed:!0,withSourceLock:P4t});return l}catch(s){return[{source:n.source,kind:n.kind,error:Dt(s),usedStaleSnapshot:!1}]}}function rir(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch(e){return V(`[project-context] could not strin
`).map(e=>e.trim()).filter(e=>e.length>0):[]}var Wj,vY,Qor,eir,o4e,S4t,C4t,Qme,k4t,M4t=b(()=>{Ov();GF();ge();Cd();jme();Id();Gme();u4t();Wj=require("obsidian");Uj();l1();jj();_4t();vY=Object.freeze([]),Qor=Object.freeze([]);eir=["<project_context>","This session runs in a project workspace: the working directory is the project's","folder. This project's context sources could not be loaded for this session.","</project_context>"].join(`
`),o4e=Object.freeze({additionalDirectories:vY,projectContextBlock:eir}),S4t=o4e,C4t=["<project_context>","This session runs in a project workspace: the working directory is the project's","folder. No context sources are configured for this project.","</project_context>"].join(`
`,l}async processContextNotes(e,n,r,o,i,s,a){let l="",c=async(d,f=Fq)=>{try{if(e.has(d.path)){H(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(!n.supportsExtension(d.extension)){V(`Unsupported file type: ${d.extension}`);return}if(!nd(a)&&!Ooe(d)){V(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new SY.Notice(zre.NON_MARKDOWN_FILES_RESTRICTED);return}let p=d.extension==="md"?await this.buildMarkdownContextContent(d,r,n,a):await n.parseFile(d,r),m=await r.adapter.stat(d.path),h=m?new Date(m.ctime).toISOString():"Unknown",g=m?new Date(m.mtime).toISOString():"Unknown";l+=`
</${f}_error>`}},u=new Set;i&&s&&(await c(s,"active_note"),u.add(s.path));for(let d of o)u.has(d.path)||(await c(d),u.add(d.path));return l}processSelectedTextContexts(e){if(!e||e.length===0)return"";let n="";for(let r of e)r.sourceType==="web"?n+=`
<error>${bi(y.error)}</error>`);let _=y.transcript||"No transcript available for this video";return v.push(`
<content>
${bi(_)}
</content>`),v.push(`
</${rIe}>`),v.join("")},l=null,c=[],u=new Set,d=new Set,f=Ep(this.app),p=y=>{let v=f.getYouTubeVideoId(y);return v?d.has(v)?!0:(d.add(v),!1):u.has(y)?!0:(u.add(y),!1)};for(let y of e){let v=Of(y.url);v&&y.isActive&&!l&&(l={...y,url:v},p(v))}for(let y of e){let v=Of(y.url);!v||p(v)||c.push({...y,url:v})}if(!l&&c.length===0)return"";let m=f.getAvailability();if(!m.supported||!m.available){let y=m.reason??(m.supported?"Web Viewer is not available.":"Web Viewer is not supported on this platform."),v=[];l&&v.push(s(Rre,{title:l.title||"Unknown",url:l.url,error:y}));for(let _ of c)v.push(s(nIe,{title:_.title||"Unknown",url:_.url,error:y}));return v.join("")}let h=async(y,v)=>{try{let _=y.url,S=f.getYouTubeVideoId(_);if(S)return await g(y,S,v===Rre);let k=f.findLeafByUrl(_,{title:y.title});if(!k)return s(v,{title:y.title||"Unknown",url:_,error:"Web tab not found or closed"});let x=f.getPageInfo(k),C=k.view;if(!(C.webviewMounted===void 0||C.webviewFirstLoadFinished===void 0?!0:!!(C.webviewMounted&&C.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(k,n),x=f.getPageInfo(k)}catch(O){return V(`Web tab content not loaded yet for ${_}:`,O),s(v,{title:x.title||y.title||"Untitled",url:x.url||_,mode:x.mode,error:"Web tab content not loaded yet"})}let I=new AbortController,M=window.setTimeout(()=>{I.abort()},r);try{let O=await f.getReaderModeMarkdown(k,{signal:I.signal});return x=f.getPageInfo(k),s(v,{title:x.title||y.title||"Untitled",url:x.url||_,mode:x.mode,content:O})}finally{window.clearTimeout(M)}}catch(_){return W(`Error processing web tab ${y.url}:`,_),s(v,{title:y.title||"Unknown",url:y.url,error:_ instanceof zA?"Web tab content extraction timed out":"Could not process web tab"})}},g=async(y,v,_)=>{try{let S=null,k=y.url;for(let M of f.getLeaves()){let O=f.getPageInfo(M).url;if(f.getYouTubeVideoId(O)===v){S=M,k=O;break}}if(!S)return a({title:y.title||"YouTube Video",url:y.url,videoId:v,isActive:_,error:"Web tab not found or closed"});let x=S.view;if(!(x.webviewMounted===void 0||x.webviewFirstLoadFinished===void 0?!0:!!(x.webviewMounted&&x.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(S,n)}catch(M){return V(`YouTube tab content not loaded yet for ${k}:`,M),a({title:y.title||"YouTube Video",url:k,videoId:v,isActive:_,error:"Web tab content not loaded yet"})}let T=await f.getYouTubeTranscript(S,{timeoutMs:o}),I=T.transcript.length>0?T.transcript.map(M=>`${M.timestamp}: ${M.text}`).join(`
`):void 0;return a({title:T.title||y.title||"YouTube Video",url:k,videoId:T.videoId,channel:T.channel,description:T.description,uploadDate:T.uploadDate,duration:T.duration,genre:T.genre,transcript:I,isActive:_})}catch(S){return V(`YouTube transcript extraction failed for ${y.url}:`,S),a({title:y.title||"YouTube Video",url:y.url,videoId:v,isActive:_,error:S instanceof Error?S.message:"Failed to extract video info"})}},w=[];if(l){let y=await h(l,Rre);w.push(y)}for(let y=0;y<c.length;y+=i){let v=c.slice(y,y+i),_=await Promise.all(v.map(S=>h(S,nIe)));w.push(..._)}return w.join("")}}});function S4e(t){let{mentionedAgentIds:e,installedAgentIds:n}=t,r=[],o=new Set;for(let i of e)o.has(i)||n.has(i)&&(o.add(i),r.push(i));return r.length>0?r:bHt}function CY(t,e){return!(t.length===0||t.length===1&&t[0]===e)}var bHt,C4e=b(()=>{bHt=Object.freeze([])});function xHt(t,e){return!t||!t.model||!e||!t.model.availableModels.find(r=>r.baseModelId===e.baseModelId)||t.model.current.baseModelId===e.baseModelId?t:{...t,model:{...t.model,current:{...t.model.current,baseModelId:e.baseModelId}}}}function Zir(t,e){return`${t} finished the turn without returning any assistant text or tool activity (stop reason: ${e}). Try again, or switch models if this repeats.`}function Yir(t){let e=Dt(t),n=Jir(t);return!n||e.includes(n)?e:`${e}
`)}function rsr(t){if(!t)return null;let e=(t.notes??[]).map(o=>o.path).filter(Boolean),n=(t.selectedTextContexts??[]).filter(MB);if(e.length===0&&n.length===0)return null;let r=["<copilot-context>","The user attached the following vault items. The vault is your current working directory; use the Read tool to inspect them when relevant."];if(e.length>0){r.push("","Notes:");for(let o of e)r.push(`- ${o}`)}if(n.length>0){r.push("","Selected excerpts (already inlined; no need to re-read):");for(let o of n){r.push(`- ${o.notePath} (lines ${o.startLine}-${o.endLine}):`);for(let i of o.content.split(`
`)}async function A1(t,e,n,r){try{let o=(0,jm.normalizePath)(`${r}/${Ef}`);await Fo(t,o);let i=Lx(e.id||"unknown")||"unknown",s=`Project Migration Failed - ${i}`,a=`${o}/${s}.md`,l=2;for(;await t.adapter.exists(a);){if(l===2)try{let d=(await t.adapter.read(a)).match(/```json\s*\n([\s\S]*?)\n```/);if(d){let f=JSON.parse(d[1]);if(JSON.stringify(f)===JSON.stringify(e))return!1}}catch{}if(a=`${o}/${s} - ${l}.md`,l++,l>20)return V(`[Projects] Too many backup collisions for safeId="${i}", giving up`),!1}let c=[`> Projects migration failed: ${n}`,">","> This file is an automatic backup (unsupported/), for manual recovery.","> You can recreate the project from the JSON below, or fix and re-migrate.","","```json",JSON.stringify(e,null,2),"```",""].join(`
`);return await t.create(a,c),!0}catch(o){return W(`[Projects] Failed to save unsupported backup for project id=${e.id||"unknown"}`,o),!1}}async function ZHt(t,e,n){let r=t.vault;try{let o=r.getAbstractFileByPath(e);o instanceof jm.TFile?await bd(t,o):await r.adapter.exists(e)&&await r.adapter.remove(e);let i=r.getAbstractFileByPath(n);if(i instanceof jm.TFolder&&i.children.length===0)await bd(t,i);else if(await r.adapter.exists(n)){let s=await r.adapter.list(n);s.files.length===0&&s.folders.length===0&&await r.adapter.rmdir(n,!1)}}catch(o){W(`[Projects] Migration rollback failed for ${e}`,o)}}async function Isr(t,e,n,r){let o=t.vault;await Fo(o,r),await Fo(o,`${r}/${n}`);let i=FA(n,r),s=`${r}/${n}`;Tf(i);try{let a=await o.create(i,e.systemPrompt||""),l=Date.now(),c=Number.isFinite(e.created)&&e.created>0?e.created:l,u=Number.isFinite(e.UsageTimestamps)&&e.UsageTimestamps>0?e.UsageTimestamps:0;try{await PY(t,a,e,n,{createdMs:c,lastUsedMs:u})}catch(d){throw await ZHt(t,i,s),d}return a}finally{Sd(i)}}async function KHt(t,e,n){try{let r=e instanceof jm.TFile?await t.read(e):await t.adapter.read(e),o=uy(r,{trimStart:!1}),i=qHt(o).replace(/^\n+/,""),s=qHt(n||"").replace(/^\n+/,"");return i!==s?(V(`[Projects] Migration verify failed: content mismatch. Expected ${s.length} chars, got ${i.length} chars`),!1):!0}catch(r){return W("[Projects] Migration verify failed: unable to read back file",r),!1}}function GHt(t,e){return Kjt(t,e)}async function Psr(t){let e=kd(),n=t.vault,o=le().projectList||[];if(o.length===0)return H("[Projects] No legacy projects to migrate"),null;H(`[Projects] Migrating ${o.length} legacy projects to vault files...`);let i=[],s=new Set,a=new Map;for(let f of o){let p=(f.id||"").trim();if(!p){V("[Projects] Skip migrating project with empty id"),await A1(n,f,"empty project id",e);continue}if(s.has(p)){V(`[Projects] Skip migrating duplicate project id: ${p}`),await A1(n,f,`duplicate project id: ${p}`,e);continue}s.add(p);let m=GHt(p,f.name),h=m.toLowerCase(),g=a.get(h);if(g){V(`[Projects] Skip migrating project id="${p}": folder name "${m}" collides with id="${g}"`),await A1(n,f,`folder name collision: "${m}" already used by id="${g}"`,e);continue}a.set(h,p);let w=FA(m,e),y=n.getAbstractFileByPath(w);if(y instanceof jm.TFile||await n.adapter.exists(w)){let _="";if(y instanceof jm.TFile){let S=t.metadataCache.getFileCache(y);_=String(S?.frontmatter?.[Um]??"").trim(),_||(_=await Yje(n,y,Um))}else try{let k=(await n.adapter.read(w)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(k){let x=(0,jm.parseYaml)(k[1]);if(x&&typeof x=="object"){let C=x[Um];_=(typeof C=="string"?C:"").trim()}}}catch{_=""}if(_===p){if(await KHt(n,y instanceof jm.TFile?y:w,f.systemPrompt||"")){if(y instanceof jm.TFile)try{let k=GHt(p,f.name);await AY(t,y,{project:f,filePath:w,folderName:k})}catch(k){V(`[Projects] Failed to repair frontmatter for id=${p}, continuing`,k)}H(`[Projects] Migration skip: target file already exists for id=${p} at ${w}`),i.push(f);continue}V(`[Projects] Migration verify failed on existing file for id=${p} at ${w}`),await A1(n,f,`existing file content mismatch at ${w} (delete/rename the file and re-run migration)`,e);continue}V(`[Projects] Migration conflict: ${w} exists with id="${_}" but expected "${p}"`),await A1(n,f,`target file exists at ${w} with mismatched id="${_}"`,e);continue}try{let _=await Isr(t,f,m,e);if(await KHt(n,_,f.systemPrompt||""))i.push(f);else{let k=`${e}/${m}`;await ZHt(t,_.path,k),await A1(n,f,"content verification mismatch",e)}}catch(_){let S=_ instanceof Error?_.message:String(_);W(`[Projects] Failed to migrate project id=${p}`,_),await A1(n,f,S,e)}}Gt("projectList",[]);let l=i.length,c=o.length-l,u=kd(),d=Zje();return c===0?(H(`[Projects] Migration succeeded: all ${l} project(s) migrated to vault files`),{id:"projects",title:"Projects",status:"success",summary:`All ${l} project${l===1?" was":"s were"} migrated to note files.`,details:[`Stored in ${u}.`]}):l>0?(V(`[Projects] Migration partially succeeded: ${l} migrated, ${c} failed`),{id:"projects",title:"Projects",status:"ac
${(0,sg.stringifyYaml)(s)}---
${e.systemPrompt||""}`}async createProject(e){let n=(e.id||"").trim();if(!n)throw new Error("Project id cannot be empty");if(ao(n))throw new Error(`Project id already exists: ${n}`);let r=(e.name||"").trim();if(r&&Ap().some(d=>d.project.name.trim().toLowerCase()===r.toLowerCase()))throw new Error(`A project with the name "${r}" already exists`);let o=this.sanitizeFolderName(r||n),i=fY(o),s=FA(o),a=o.toLowerCase(),c=Ap().find(u=>u.folderName.toLowerCase()===a&&u.project.id!==n);if(c)throw new Error(`Folder name collision: project id "${n}" sanitizes to folder "${o}" which conflicts with existing project "${c.project.id}"`);try{if(Tf(s),await Fo(this.vault,kd()),await Fo(this.vault,i),await this.vault.adapter.exists(s))throw new Error(`Project file already exists at "${s}". This may be a folder name collision — project id "${n}" sanitizes to folder "${o}"`);let u=Date.now(),d=Number.isFinite(e.created)&&e.created>0?e.created:u,f=Number.isFinite(e.UsageTimestamps)&&e.UsageTimestamps>0?e.UsageTimestamps:0,p=await this.vault.create(s,e.systemPrompt||"");try{await PY(this.app,p,e,o,{createdMs:d,lastUsedMs:f})}catch(h){throw await this.rollbackCreatedFile(s,i),h}let m={project:{...e,id:n,created:d,UsageTimestamps:f},filePath:s,folderName:o};return f1(m),H(`[Projects] Created project: ${n} -> ${s}`),m}finally{Sd(s)}}async updateProject(e,n){let r=(e||"").trim();if(!r)throw new Error("Project id cannot be empty");if((n.id||"").trim()!==r)throw new Error("Project id mismatch: cannot change id via update");let o=ao(r);if(!o)throw new Error(`Project not found: ${r}`);let i=(n.name||"").trim();if(i&&Ap().some(p=>p.project.id!==r&&p.project.name.trim().toLowerCase()===i.toLowerCase()))throw new Error(`A project with the name "${i}" already exists`);let s=o.filePath,a=o.folderName,{projectsRoot:l}=Td(o.filePath),c=f=>(0,sg.normalizePath)(`${l}/${f}`),u=this.sanitizeFolderName(i||r),d=null;if(u!==o.folderName){let f=c(u),p=FA(u,l),m=u.toLowerCase(),h=Ap().find(w=>w.project.id!==r&&w.folderName.toLowerCase()===m);if(h)throw new Error(`Cannot rename project folder: "${u}" conflicts with project "${h.project.name}"`);if(!(f.toLowerCase()===c(o.folderName).toLowerCase())&&await this.vault.adapter.exists(f))throw new Error(`Cannot rename project folder: "${f}" already exists on disk`);d=s,Tf(d),Tf(p);try{let w=c(o.folderName),y=this.vault.getAbstractFileByPath(w);y instanceof sg.TFolder?await this.vault.rename(y,f):await this.vault.adapter.rename(w,f)}catch(w){throw Sd(d),Sd(p),w}s=p,a=u,H(`[Projects] Renamed project folder: "${o.folderName}" → "${u}" for project ${r}`)}try{d||Tf(s);let f=await ik(this.app,s),p=!1;if(!f){H(`[Projects] Materializing missing vault file for project: ${r}`);let _=c(a);await Fo(this.vault,l),await Fo(this.vault,_),f=await this.vault.create(s,n.systemPrompt||""),p=!0}let m=Number.isFinite(o.project.created)&&o.project.created>0?o.project.created:Date.now(),h=Number.isFinite(o.project.UsageTimestamps)&&o.project.UsageTimestamps>0?o.project.UsageTimestamps:0,g=this.projectLastUsedManager.getLastTouchedAt(r)??0,w=Math.max(h,g),y={...n,created:m,UsageTimestamps:w};if(Pp(this.app,s)){try{await PY(this.app,f,y,a,{createdMs:m,lastUsedMs:w})}catch(x){throw p&&await this.rollbackCreatedFile(s,c(a)),x}let _=await this.vault.read(f),S=this.getLeadingFrontmatterBlock(_);if(!S)throw new Error(`Expected frontmatter block after update: ${f.path}`);let k=S.endsWith(`
`)?"":`
`;await this.vault.modify(f,S+k+(n.systemPrompt||""))}else{let _=this.buildProjectFileContent(y,a,{createdMs:m,lastUsedMs:w});await this.vault.adapter.write(s,_)}let v={project:{...n,created:m,UsageTimestamps:w},filePath:s,folderName:a};return f1(v),H(`[Projects] Updated project: ${r} -> ${s}`),v}catch(f){if(d&&a!==o.folderName)try{let p=c(o.folderName),m=c(a),h=this.vault.getAbstractFileByPath(m);h instanceof sg.TFolder?await this.vault.rename(h,p):await this.vault.adapter.rename(m,p),V(`[Projects] Rolled back folder rename "${a}" → "${o.folderName}" after write failure`)}catch(p){W(`[Projects] Failed to rollback folder rename for ${r}`,p)}throw f}finally{Sd(s),d&&Sd(d)}}async deleteProject(e){let n=(e||"").trim(),r=ao(n);if(!r){V(`[Projects] deleteProject: not found: ${n}`);return}let{projectFolderPath:o}=Td(r.filePath);try{Tf(r.filePath);let i=this.vault.getAbstractFileByPath(r.filePath);i instanceof sg.TFile?await bd(this.app,i):await this.vault.adapter.exists(r.filePath)&&await this.vault.adapter.remove(r.filePath),Ojt(n),await zjt(this.app,o);try{let s=this.vault.getAbstractFileByPath(o);if(s instanceof sg.TFolder&&s.children.length===0)await bd(this.app,s);else if(await this.vault.adapter.exists(o)){let a=await this.vault.adapter.list(o);a.files.length===0&&a.folders.length===0&&await this.vault.adapter.rmdir(o,!1)}}catch(s){V(`[Projects] Failed to clean up empty project folder: ${o}`,s)}if(vn()){let{clearProjectMarkers:s}=await Promise.resolve().then(()=>(QHt(),XHt));await s(this.app,n).catch(a=>W("[Projects] Failed to clear off-vault failure markers on delete",a))}H(`[Projects] Deleted project: ${n} -> ${o}`),dk(this.app).catch(s=>W("[Projects] Rescan after delete failed",s))}finally{Sd(r.filePath)}}async touchProjectLastUsed(e){let n=(e||"").trim(),r=ao(n);if(r)try{this.projectLastUsedManager.touch(n);let o=this.projectLastUsedManager.shouldPersist(n,r.project.UsageTimestamps);if(o===null)return;let i=(0,sg.normalizePath)(r.filePath),s=await ik(this.app,i);if(!s)return;let a=hb(i),l=o;try{if(a||Tf(i),Pp(this.app,i))await this.app.fileManager.processFrontMatter(s,u=>{let d=Number(u[yb]),f=Number.isFinite(d)&&d>0?d:0;l=Math.max(f,o),f!==l&&(u[yb]=l)});else{let u=await kf(this.app,i),d=Number(u?.[yb]),f=Number.isFinite(d)&&d>0?d:0;l=Math.max(f,o),f!==l&&await Ex(this.app,i,{[yb]:l})}}finally{a||Sd(i)}this.projectLastUsedManager.markPersisted(n,l);let c=ao(n);c&&f1({...c,project:{...c.project,UsageTimestamps:l}})}catch(o){W(`[Projects] Failed to touch last-used for projectId=${e}`,o)}}}});async function Phe(t,e){let n=e.project.systemPrompt??"";if(n.trim())try{let r=Td(e.filePath).projectFolderPath;if(!await Dme(t,r))return;await dY(t,r,n),await ll.getInstance(t).updateProject(e.project.id,{...e.project,systemPrompt:""}),H(`[Projects] Moved project instructions into ${r}/AGENTS.md`)}catch(r){V(`[Projects] Failed to move project instructions for "${e.folderName}"`,r)}}var N4e=b(()=>{rw();ge();fk();ow()});function Osr(t,e,n){return new Promise(r=>{let o=window.setTimeout(()=>r(n),e);t.then(i=>{window.clearTimeout(o),r(i)},()=>{window.clearTimeout(o),r(n)})})}function Rsr(t,e){let n=r=>r.replace(/[/\\]+$/,"");return n(t)===n(e)}function $4e(t){return{path:t.source,type:t.kind==="file"?"nonMd":t.kind,error:t.error,usedStaleSnapshot:t.usedStaleSnapshot}}function $sr(t,e){return t.path!==e.source?!1:e.kind==="file"?t.type==="nonMd":t.type===e.kind}function Fsr(t,e){return t.some(n=>n.kind===e.kind&&n.source===e.source)?t:[...t,{kind:e.kind,source:e.source}]}function tWt(t,e){return t.filter(n=>!(n.kind===e.kind&&n.source===e.source))}function zsr(t,e){return[...t.filter(n=>!(n.path===e.path&&n.type===e.type)),e]}var Mp,eWt,Msr,Nsr,L4e,D4e,Lsr,Dsr,Ahe,nWt=b(()=>{Iv();ge();Mjt();Ma();Ee();M4t();vt();_Y();rg();Mp=require("obsidian");ed();P4e();kG();xt();xhe();u4e();l0();MHt();A4e();OHt();LN();Ox();NHt();Cd();jme();DHt();FHt();rw();N4e();ow();fk();eWt=500,Msr=1500;Nsr=Object.freeze([]),L4e=Object.freeze([]),D4e=new Set,Lsr=Object.freeze([]),Dsr=-1;Ahe=class{constructor(e,n,r){this.app=e;this.plugin=n;this.opts=r;this.back
`,hcr=D1?"":aye,nqt="֑-߿יִ-﷽ﹰ-ﻼ",rqt="A-Za-zÀ-ÖØ-öø-ʸ̀-ࠀ-Ⰰ-︀--",gcr=new RegExp("^[^"+rqt+"]*["+nqt+"]"),ycr=new RegExp("^[^"+nqt+"]*["+rqt+"]"),$f={bold:1,capitalize:1024,code:16,highlight:sye,italic:2,lowercase:256,strikethrough:iJ,subscript:32,superscript:64,underline:sJ,uppercase:512},wcr={directionless:1,unmergeable:2},c3t={center:vWe,end:SWe,justify:_We,left:wWe,right:bWe,start:xWe},vcr={[vWe]:"center",[SWe]:"end",[_We]:"justify",[wWe]:"left",[bWe]:"right",[xWe]:"start"},bcr={normal:0,segmented:2,token:1},_cr={[acr]:"normal",[ccr]:"segmented",[lcr]:"token"},xcr="$",u3t="$config";Scr=100,VHe=!1,CWe=0;qHe=class{constructor(e,n){this.key=e,this.parse=n.parse.bind(n),this.unparse=(n.unparse||Mcr).bind(n),this.isEqual=(n.isEqual||Object.is).bind(n),this.defaultValue=this.parse(void 0)}};KHe=class t{constructor(e,n,r=void 0,o=new Map,i=void 0){this.node=e,this.sharedNodeState=n,this.unknownState=r,this.knownState=o;let{sharedConfigMap:s}=this.sharedNodeState,a=i!==void 0?i:function(l,c,u){let d=u.size;if(c)for(let f in c){let p=l.get(f);p&&u.has(p)||d++}return d}(s,r,o);this.size=a}getValue(e){let n=this.knownState.get(e);if(n!==void 0)return n;this.sharedNodeState.sharedConfigMap.set(e.key,e);let r=e.defaultValue;if(this.unknownState&&e.key in this.unknownState){let o=this.unknownState[e.key];o!==void 0&&(r=e.parse(o)),this.updateFromKnown(e,r)}return r}getInternalState(){return[this.unknownState,this.knownState]}toJSON(){let e={...this.unknownState},n={};for(let[r,o]of this.knownState)r.isEqual(o,r.defaultValue)?delete e[r.key]:e[r.key]=r.unparse(o);for(let r of this.sharedNodeState.flatKeys)r in e&&(n[r]=e[r],delete e[r]);return d3t(e)&&(n.$=e),n}getWritable(e){if(this.node===e)return this;let{sharedNodeState:n,unknownState:r}=this,o=new Map(this.knownState);return new t(e,n,function(i,s,a){let l;if(a)for(let[c,u]of Object.entries(a)){let d=i.get(c);d?s.has(d)||s.set(d,d.parse(u)):(l=l||{},l[c]=u)}return l}(n.sharedConfigMap,o,r),o,this.size)}updateFromKnown(e,n){let r=e.key;this.sharedNodeState.sharedConfigMap.set(r,e);let{knownState:o,unknownState:i}=this;o.has(e)||i&&r in i||(i&&(delete i[r],this.unknownState=d3t(i)),this.size++),o.set(e,n)}updateFromUnknown(e,n){let r=this.sharedNodeState.sharedConfigMap.get(e);r?this.updateFromKnown(r,r.parse(n)):(this.unknownState=this.unknownState||{},e in this.unknownState||this.size++,this.unknownState[e]=n)}updateFromJSON(e){let{knownState:n}=this;for(let r of n.keys())n.set(r,r.defaultValue);if(this.size=n.size,this.unknownState=void 0,e)for(let[r,o]of Object.entries(e))this.updateFromUnknown(r,o)}};Qc="",Np="",Wx=null,Vx="",kk="",uqt=!1,cJ=!1,$ge=null;Ocr="40px";TWe=xr("SELECTION_CHANGE_COMMAND"),Lcr=xr("SELECTION_INSERT_CLIPBOARD_NODES_COMMAND"),gqt=xr("CLICK_COMMAND"),uJ=xr("DELETE_CHARACTER_COMMAND"),XY=xr("INSERT_LINE_BREAK_COMMAND"),eWe=xr("INSERT_PARAGRAPH_COMMAND"),P4=xr("CONTROLLED_TEXT_INSERTION_COMMAND"),IWe=xr("PASTE_COMMAND"),tWe=xr("REMOVE_TEXT_COMMAND"),dJ=xr("DELETE_WORD_COMMAND"),fJ=xr("DELETE_LINE_COMMAND"),ZA=xr("FORMAT_TEXT_COMMAND"),PWe=xr("UNDO_COMMAND"),AWe=xr("REDO_COMMAND"),yqt=xr("KEYDOWN_COMMAND"),wqt=xr("KEY_ARROW_RIGHT_COMMAND"),vqt=xr("MOVE_TO_END"),bqt=xr("KEY_ARROW_LEFT_COMMAND"),_qt=xr("MOVE_TO_START"),xqt=xr("KEY_ARROW_UP_COMMAND"),Sqt=xr("KEY_ARROW_DOWN_COMMAND"),Zge=xr("KEY_ENTER_COMMAND"),Cqt=xr("KEY_SPACE_COMMAND"),kqt=xr("KEY_BACKSPACE_COMMAND"),Tqt=xr("KEY_ESCAPE_COMMAND"),Iqt=xr("KEY_DELETE_COMMAND"),Pqt=xr("KEY_TAB_COMMAND"),Dcr=xr("INSERT_TAB_COMMAND"),$cr=xr("INDENT_CONTENT_COMMAND"),Fcr=xr("OUTDENT_CONTENT_COMMAND"),Aqt=xr("DROP_COMMAND"),zcr=xr("FORMAT_ELEMENT_COMMAND"),Eqt=xr("DRAGSTART_COMMAND"),Mqt=xr("DRAGOVER_COMMAND"),Oqt=xr("DRAGEND_COMMAND"),EWe=xr("COPY_COMMAND"),MWe=xr("CUT_COMMAND"),nWe=xr("SELECT_ALL_COMMAND"),Ucr=xr("CLEAR_EDITOR_COMMAND"),Bcr=xr("CLEAR_HISTORY_COMMAND"),jcr=xr("CAN_REDO_COMMAND"),Hcr=xr("CAN_UNDO_COMMAND"),Rqt=xr("FOCUS_COMMAND"),Nqt=xr("BLUR_COMMAND"),Lqt=xr("KEY_MODIFIER_COMMAND"),_k=Object.freeze({}),rWe=30,oWe=[["keydown",function(t,e){if(QY=t.timeSta
Return only the translated text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Create a bullet-point summary of {}. Each bullet point should capture a key point. Return only the bullet-point summary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify {} to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original key concepts. Return only the simplified text.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"Explain like I am 5",content:`Explain {} in simple terms that a 5-year-old would understand:
1. Use basic vocabulary
2. Include simple analogies
3. Break down complex concepts
Return only the simplified explanation.`,showInContextMenu:!0,showInSlashMenu:!0,order:1040,modelKey:"",lastUsedMs:0},{title:"Emojify",content:`Add relevant emojis to enhance {}. Follow these rules:
1. Insert emojis at natural breaks in the text
2. Never place two emojis next to each other
3. Keep all original text unchanged
4. Choose emojis that match the context and tone
Return only the emojified text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1050,modelKey:"",lastUsedMs:0},{title:"Make shorter",content:`Reduce {} to half its length while preserving these elements:
1. Main ideas and key points
2. Essential details
3. Original tone and style
Return only the shortened text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1060,modelKey:"",lastUsedMs:0},{title:"Make longer",content:`Expand {} to twice its length by:
1. Adding relevant details and examples
2. Elaborating on key points
3. Maintaining the original tone and style
Return only the expanded text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generate table of contents",content:"Generate a hierarchical table of contents for {}. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generate glossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term: Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"Remove URLs",content:"Remove all URLs from {}. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet",content:`Rewrite {} as a single tweet with these requirements:
1. Maximum 280 characters
2. Use concise, impactful language
3. Maintain the core message
Return only the tweet text.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet thread",content:`Convert {} into a Twitter thread following these rules:
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0},{title:"Clip YouTube Transcript",content:`
Based on the YouTube video information and transcript provided in the context, generate a complete Obsidian note in the following format.
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1130,modelKey:"",lastUsedMs:0},{title:"Clip Web Page",content:`
Based on the web page content provided in the context (from Obsidian Web Clipper or Web Viewer), generate a complete Obsidian note.
IMPORTANT: If no web page context is found, remind the user to:
1. Open a web page in Web Viewer (or use @ to select a web tab)
2. Or open a note clipped by Obsidian Web Clipper
3. Then use this command again
Generate the note with this exact structure:
---
title: "<page title>"
source: "<page url>"
description: "<brief description>"
tags:
- "clippings"
---
## Summary
<Brief 2-3 paragraph summary of the page content>
## Key Takeaways
<List 5-8 key takeaways as bullet points>
## Mindmap
CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
- Root node format: root(Topic Name) - use round brackets, NO double brackets
- Child nodes: just plain text, no brackets needed
- Do NOT use quotes, parentheses, brackets, or any special characters in text
- Keep all node text short and simple - max 3-4 words per node
\`\`\`mermaid
mindmap
root(Main Topic)
Theme One
Detail
Theme Two
Detail
\`\`\`
## Notable Quotes
<List 3-5 notable quotes from the content, if any>
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1140,modelKey:"",lastUsedMs:0}]});function ywe(t,e,n){let r=t.trim();return r?t!==r?"Command name cannot have leading or trailing spaces":n&&t===n?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(r)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===r.toLowerCase())?"A command with this name already exists":null:"Command name cannot be empty"}function rL(t){return encodeURIComponent(t.toLowerCase())}function gE(){return P2()}function pH(t){return`${gE()}/${t}.md`}function mH(t){if(!(t instanceof gwe.TFile)||t.extension!=="md")return!1;let e=gE();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function e8t(t,e){return t.metadataCache.getFileCache(e)?.frontmatter?.[rS]!=null}async function HJ(t,e){let n=await t.vault.read(e),r=uy(n),o=t.metadataCache.getFileCache(e),i=o?.frontmatter?.[Wk]??nS.showInContextMenu,s=o?.frontmatter?.[Vk]??nS.showInSlashMenu,a=o?.frontmatter?.[Kk]??nS.lastUsedMs,l=o?.frontmatter?.[rS]??nS.order,c=o?.frontmatter?.[qk]??nS.modelKey;return{title:e.basename,modelKey:c,content:r,showInContextMenu:i,showInSlashMenu:s,order:l,lastUsedMs:a}}async function _6e(t){let e=t.vault.getFiles().filter(n=>mH(n));return await Promise.all(e.map(n=>HJ(t,n)))}async function t8t(t){let e=await _6e(t);return fH(e),e}function WJ(t){return oy(t,"manual",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0,getManualOrder:e=>e.order})}function gpr(t){return oy(t,"recent",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:e=>e.lastUsedMs})}function ypr(t){return oy(t,"name",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0})}function wwe(t){switch(le().promptSortStrategy){case"timestamp":return gpr(t);case"alphabetical":return ypr(t);case"manual":return WJ(t);default:return t}}async function VJ(t,e,n,r=!1){let i=(await qJ(t,e,n,t.vault,t.workspace.getActiveFile())).processedPrompt;if(i.includes(`{${tm}}`)||r)return i;let s=i.indexOf(b6e);return s===-1?n.trim()?i+`
</${NO}>`,l.files.push(r))}else new gwe.Notice("No active note found.");else{if(c==="activewebtab")continue;if(a.startsWith("#")){let u=a.slice(1).split(",").map(p=>p.trim()),d=Moe(t,u),f=[];for(let p of d){let m=await S2(p,n);m&&(f.push(`<${NO}>
`)}else{let u=Lat(a),d=D5(n,u),f=[];for(let p of d){let m=await S2(p,n);m&&(f.push(`<${NO}>
<path>${p.path}</path>
## ${Roe(p)}
${m}
</${NO}>`),l.files.push(p))}l.content=f.join(`
`)}}l.content?(o.set(a,l.content),l.files.forEach(u=>i.add(u))):c!=="activenote"&&c!=="activewebtab"&&(a.startsWith('"')||V(`No notes found for variable: ${a}`))}return{variablesMap:o,includedFiles:i}}async function qJ(t,e,n,r,o,i=!1){let s=le(),a=new Set;if(!s.enableCustomPromptTemplating)return!i&&e.includes("{}")&&!n&&o&&a.add(o),{processedPrompt:e+`
`),o=["🌐 Web Search Results"],i=!1,s=[],a=[];for(let l of r){if(l.includes("Sources:")){i=!0;continue}i?a.push(l):l.includes("Here are the web search results")||s.push(l)}return s.length>0&&(o.push(""),o.push(...s.filter(l=>l.trim()))),a.length>0&&(o.push(""),o.push("Sources:"),a.forEach(l=>{l.trim()&&o.push(l)})),o.join(`
`),a=0;for(let l of s)if(l.trim()&&(l.match(/^\[(\d+:\d+)\]/)?(a>0&&o.push(""),o.push(`⏰ ${l}`)):o.push(` ${l.trim()}`),a++,a>50)){o.push(""),o.push("... (transcript truncated for display)");break}return r.elapsed_time_ms&&(o.push(""),o.push(`Processing time: ${(typeof r.elapsed_time_ms=="number"?r.elapsed_time_ms/1e3:0).toFixed(1)}s`)),o.join(`
\`\`\``:o.toLowerCase().includes("accepted")?"✅ Edit accepted":o.toLowerCase().includes("rejected")?"❌ Edit rejected":n&&typeof n.message=="string"?n.message:o}static formatReadNote(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}let r=Xpr(n);return r||(typeof e=="string"?e:JSON.stringify(e,null,2))}}});var As,Qpr,tX,emr,dZt,fZt=b(()=>{Xz();De();Dwe();Le();As=R(U()),Qpr="shimmer 2s ease-in-out infinite",tX=5e3,emr=(t,e)=>{if(!e)return null;if(e.length>tX)return`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`;try{let n=Zk.format(t,e);return n.length>tX?n.slice(0,tX)+`
… (truncated ${(n.length-tX).toLocaleString()} characters for display)`:n}catch{return e.length>tX?`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`:e}},dZt=({toolName:t,displayName:e,emoji:n,isExecuting:r,result:o,confirmationMessage:i,onAccept:s,onReject:a})=>{let[l,c]=(0,As.useState)(!1),u=(0,As.useMemo)(()=>emr(t,o),[t,o]),d=r&&!o,f=!d&&u!==null;return As.default.createElement(nx,{open:f?l:!1,onOpenChange:c,disabled:!f,"aria-disabled":!f,className:"tw-my-3 tw-w-full sm:tw-max-w-sm"},As.default.createElement("div",{className:X("tw-rounded-md tw-border tw-border-border tw-bg-secondary/50",d&&"tw-relative tw-overflow-hidden")},d&&As.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-[1] tw-overflow-hidden"},As.default.createElement("div",{className:"tw-absolute tw-inset-0 -tw-translate-x-full",style:{background:"linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%)",animation:Qpr}})),As.default.createElement(rx,{className:X("tw-flex tw-w-full tw-items-center tw-justify-between tw-px-3 tw-py-2.5 tw-text-sm sm:tw-px-4 sm:tw-py-3",f&&"hover:tw-bg-secondary/70",!f&&"tw-cursor-default")},As.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},As.default.createElement("span",{className:"tw-text-base"},n),As.default.createElement("span",{className:"tw-font-medium"},t==="readNote"?`${d?"Reading":"Read"} ${e}`:`${d?"Calling":"Called"} ${e}`,d&&t!=="readNote"&&"..."),d&&i&&As.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"• ",i,"...")),As.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!d&&s&&a&&As.default.createElement(As.default.Fragment,null,As.default.createElement("button",{type:"button",onClick:p=>{p.stopPropagation(),s()},className:"hover:tw-bg-green-rgb/20 tw-rounded tw-p-1",title:"Accept"},As.default.createElement(Ur,{className:"tw-size-4 tw-text-success"})),As.default.createElement("button",{type:"button",onClick:p=>{p.stopPropagation(),a()},className:"hover:tw-bg-red-rgb/20 tw-rounded tw-p-1",title:"Reject"},As.default.createElement(Cn,{className:"tw-size-4 tw-text-error"}))),f&&As.default.createElement(Ea,{className:X("tw-size-4 tw-text-muted tw-transition-transform",l&&"tw-rotate-90")}))),As.default.createElement(ox,null,As.default.createElement("div",{className:"tw-border-t tw-border-border tw-px-3 tw-py-2.5 sm:tw-px-4 sm:tw-py-3"},As.default.createElement("div",{className:"tw-text-sm tw-text-muted"},As.default.createElement("pre",{className:"tw-overflow-x-auto tw-whitespace-pre-wrap tw-font-mono tw-text-xs"},u??"No result available"))))))}});var z6e,pZt,vH,bH,U6e,B6e,mZt,SE,hZt,gZt,yZt,wZt,vZt,bZt,_Zt,xZt,SZt,CZt,kZt,TZt,IZt=b(()=>{z6e=R(U());lZt();fZt();ge();Qa();pZt=60*60*1e3,vH=()=>(window.__copilotToolCallRoots||(window.__copilotToolCallRoots=new Map),window.__copilotToolCallRoots),bH=()=>(window.__copilotErrorBlocks||(window.__copilotErrorBlocks=new Map),window.__copilotErrorBlocks),U6e=(t,e,n)=>{if(e.size>0)return;n.get(t)===e&&n.delete(t)},B6e=(t,e,n,r,o,i)=>{try{r.root.unmount()}catch(s){V(`Error unmounting tool call root during ${o}`,n,s)}r.isUnmounting=!1,e.get(n)===r&&e.delete(n),U6e(t,e,i)},mZt=(t,e,n,r,o,i)=>{e.delete(n),r.isUnmounting=!0,window.setTimeout(()=>{try{r.root.unmount()}catch(s){V(`Error unmounting tool call root during ${o}`,n,s)}r.isUnmounting=!1,U6e(t,e,i)},0)},SE=(t,e,n,r,o,i)=>{r.isUnmounting||(r.isUnmounting=!0,window.setTimeout(()=>{let s=i.get(t),a=s?.get(n);if(!s||a!==r){r.isUnmounting=!1,U6e(t,e,i);return}B6e(t,s,n,a,o,i)},0))},hZt=(t,e,n,r,o,i)=>{let s=n.get(r);return s?.isUnmounting&&(B6e(e,n,r,s,`${i} (finalizing stale root)`,vH()),s=void 0),s&&s.container&&s.container!==o&&(mZt(e,n,r,s,`${i} (container changed)`,vH()),s=void 0),s||(s={root:Or(o,t),isUnmounting:!1,container:o},n.set(r,s)),s},gZt=(t,e,n,r,o,i)=>{let s=n.get(r);return s?.isUnmounting&&(B6e(e,n,r,s,`${i} (finalizing stale error root)`,bH()),s=void 0),s&&s.container&&s.container!==o&&(mZt(e
When the retrieved documents contain relevant images (in formats like  or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`:`
<guidance>
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like  or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`}function NZt(t){return t?"REMINDER: End your response with an '#### Sources' section listing each cited source as [^n]: [[Title]], numbered sequentially from [^1].":null}function LZt(t,e,n=!0){if(!n||!e?.length||!t)return t||"";if(umr(t))return t;let r=e.slice(0,cmr).map((o,i)=>{let s=(o.title||o.path||"Untitled").replace(/^\[\[|\]\]$/g,"");return`[^${i+1}]: [[${s}]]`}).join(`
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. BE SELECTIVE: ONLY cite when introducing NEW factual claims, specific data, or direct quotes from sources
3. IMPORTANT: Do NOT cite every sentence or bullet point. This creates clutter and poor readability.
4. DO NOT cite for:
- General knowledge or common facts
- Your own analysis or synthesis
- Transitional or concluding statements
- Every single sentence (AVOID CITATION CLUTTER - aim for 1-3 citations per paragraph maximum)
5. Citations are for SOURCE ATTRIBUTION, not for proving every statement
6. GOOD: One citation per key concept. BAD: Citation after every sentence.
7. Place citations immediately after the specific claim: "The study found X [^1]" not "The study found X. [^1]"
8. Do not reuse any bracketed numbers that appear inside the source content itself
9. If multiple source chunks come from the same document, cite each relevant chunk separately (e.g., [^1] and [^2] can both be from the same document title)
10. End with '#### Sources' section containing: [^n]: [[Title]] (one per line, matching citation order)`,lmr=`WEB CITATION RULES:
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. Cite ONLY when introducing new factual claims, statistics, or direct quotes from the search results
3. After every cited claim, place the corresponding footnote immediately after the sentence ("The study found X [^1]")
4. End with '#### Sources' and provide definitions EXACTLY in this format: [^n]: [Short Title](URL)
IMPORTANT: Each source definition must follow this exact pattern:
- Start with [^n]: (where n is the citation number)
- Follow with [Title](URL) where Title is SHORT (2-5 words) and wrapped in square brackets
- Example: [^1]: [Paul Graham Essay](https://paulgraham.com/wealth.html)
${s}`:i.content,matched:i}}var X6e=b(()=>{});async function ZZt(t,e,n,r){let o=Wwe(t,e);return o.matched?{text:KZt(o.text,n,r),matched:o.matched}:o}var YZt=b(()=>{GZt();X6e()});function zmr(t){let e=Is().filter(n=>n.getInstallState(t).kind==="ready").map(n=>({id:n.id,displayName:n.displayName,Icon:n.Icon,needsSelfHostWarning:ok(n,t)}));return e.length>0?e:Fmr}function JZt(t){let e=pt(),n=sX.default.useCallback(i=>{let s=Is().map(a=>a.subscribeInstallState(t,i));return()=>s.forEach(a=>a())},[t]),r=sX.default.useCallback(()=>Is().filter(i=>i.getInstallState(e).kind==="ready").map(i=>i.id).join(","),[e]),o=sX.default.useSyncExternalStore(n,r,r);return sX.default.useMemo(()=>zmr(e),[e,o])}var sX,Fmr,XZt=b(()=>{sX=R(U());zm();Ee();C4e();Fmr=Object.freeze([])});function Vwe(t,e,n){let r=hHt(e);if(!n)return r;try{let s=Ep(t).getActiveWebTabState().activeWebTabForMentions,a=Gj(s?.url);if(!a)return r;let l=r.map(u=>{if(u.isActive){let{isActive:d,...f}=u;return f}return u}),c=l.findIndex(u=>Gj(u.url)===a);if(c>=0){let u=l[c];return l[c]={...u,url:Of(s?.url)??u.url,title:s?.title??u.title,faviconUrl:s?.faviconUrl??u.faviconUrl,isActive:!0},l}return[...l,{url:Of(s?.url)??a,title:s?.title,faviconUrl:s?.faviconUrl,isActive:!0}]}catch(o){return V("[ActiveWebTabSnapshot] Failed to resolve active web tab:",o),r}}var Q6e=b(()=>{ge();I1();T1()});var CE,QZt,e7t=b(()=>{ot();De();Le();CE=R(U()),QZt=({messages:t,onRemove:e})=>CE.default.createElement("div",{className:"tw-flex tw-max-h-24 tw-flex-col tw-gap-1 tw-overflow-y-auto tw-px-2 tw-pb-1"},t.map(n=>{let r=n.text||(n.promptContent?.some(o=>o.type==="image")?"Image attachment":"Empty message");return CE.default.createElement("div",{key:n.id,className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2 tw-rounded-md tw-bg-secondary-alt tw-px-2 tw-py-1 tw-text-ui-smaller",title:r},CE.default.createElement(qC,{className:X("tw-size-3 tw-shrink-0",n.queueReason==="context"?"tw-text-warning":"tw-text-muted")}),CE.default.createElement("span",{className:"tw-min-w-0 tw-flex-1 tw-truncate tw-whitespace-nowrap tw-text-normal"},n.queueReason==="context"&&CE.default.createElement("span",{className:"tw-font-semibold tw-text-warning"},"Waiting for context · "),r),CE.default.createElement(ie,{variant:"ghost2",size:"fit",className:"tw-shrink-0 tw-text-muted hover:tw-text-error",onClick:()=>e(n.id),"aria-label":"Remove queued message"},CE.default.createElement(Cn,{className:"tw-size-3"})))}))});async function Umr(t){try{let e=await t.arrayBuffer();return e.byteLength===0?null:{type:"image",mimeType:t.type||"image/png",data:vd(e)}}catch(e){return V("[AgentMode] failed to read attached image",e),null}}function Bmr(t,e){if(t.type!=="image")return null;let n=t.mimeType.split("/")[1]||"png";return new File([Tme(t.data)],`queued-image-${e+1}.${n}`,{type:t.mimeType})}var aX,Es,lX,n7t,t7t,r7t,o7t=b(()=>{Ox();YZt();J6e();Ma();Gk();dw();$6e();cE();nH();xt();Bl();no();ge();XZt();zm();Q6e();LZ();Ee();vt();u1();T1();e7t();aX=require("obsidian"),Es=R(U());ed();Dc();lX=(t,e)=>{let n=new Set,r=[];for(let o of t){let i=e(o);n.has(i)||(n.add(i),r.push(o))}return r},n7t=(t,e,n=[])=>{if(!(t.length===0&&e.length===0&&n.length===0))return{notes:t,urls:[],selectedTextContexts:e.length>0?[...e]:void 0,webTabs:n.length>0?[...n]:void 0}},t7t=t=>{if(t.length===1)return t[0];let e=t.flatMap(s=>s.context?.notes??[]),n=t.flatMap(s=>s.context?.selectedTextContexts??[]),r=t.flatMap(s=>s.context?.webTabs??[]),o=t.flatMap(s=>s.promptContent??[]),i=lX(t.flatMap(s=>s.mentionedAgents??[]),s=>s);return{id:`queued-combined-${zr()}`,text:t.map(s=>s.text).join(`
`),rawInput:t.map(s=>s.rawInput).join(`
`),context:n7t(lX(e,s=>s.path),lX(n,s=>s.id),Dx(r)),promptContent:o.length>0?o:void 0,mentionedAgents:i.length>0?i:void 0}};r7t=(0,Es.memo)(function({backend:e,plugin:n,chatInputId:r,draft:o,app:i,mainAgentId:s,updateUserMessageHistory:a,isStarting:l,isLoading:c,hasPendingPlanPermission:u,modelPickerOverride:d,modePickerOverride:f,onCycleMode:p,activeProjectId:m,contextLoadBlocking:h=!1,disabled:g=!1,contextStatusIndicator:w}){let y=(0,Es.useContext)(Xd),v=(0,Es.useRef)(null),_=h&&!!m&&m!==qn,[S]=wz(),{activeWebTabForMentions:k}=Jx(),x=(0,Es.useRef)(r),C=oge(),T=JZt(n),I=C?T:Yx,M=(0,Es.useMemo)(()=>new Set(T.map(me=>me.id)),[T]),O=(0,Es.useRef)([]),D=(0,Es.useCallback)(me=>{O.current=me},[]),{input:F,images:q,contextNotes:Z,includeActiveNote:re,includeActiveWebTab:ce,queue:oe,setInput:ne,setContextNotes:G,setSelectedImages:ue,addImages:B,setIncludeActiveNote:L,setIncludeActiveWebTab:z,setLoading:E,setQueue:N,resetCompose:Y}=o,$=d?.models.find(me=>Sr(me)===d.value),te=Array.isArray($?.capabilities)&&!Doe($)?$.displayName||$.name:null;(0,Es.useEffect)(()=>{x.current!==r&&(x.current=r,PG(),O.current=[])},[r]);let de=(0,Es.useCallback)(async()=>{if(N([]),oe.length>0){let me=t7t(oe);v.current?.prependContent(me.text,me.mentionedAgents??[],me.context?.webTabs??[]);let _e=me.context?.notes??[];_e.length>0&&G(Fe=>lX([..._e,...Fe],Ye=>Ye.path));let Pe=(me.promptContent??[]).map(Bmr).filter(Fe=>Fe!==null);Pe.length>0&&ue(Fe=>[...Pe,...Fe])}try{await e.cancel()}catch(me){W("[AgentMode] cancel failed",me)}},[e,oe,G,ue,N]),K=(0,Es.useCallback)(async me=>{E(!0);try{let{turn:_e}=e.sendMessage(me.text,me.context,me.promptContent,me.mentionedAgents);me.rawInput&&a(me.rawInput),await _e}catch(_e){W("Error sending agent message:",_e),new aX.Notice("Failed to send message. Please try again.")}finally{E(!1)}},[e,E,a]),ee=(0,Es.useCallback)(async me=>{if(g)return;let _e=F.trim();if(!_e&&q.length===0)return;let Pe=F,Fe=i.workspace.getActiveFile(),Ye=[];re&&Fe&&Ye.push(Fe),Ye.push(...Z);let Oe=lX(Ye,ii=>ii.path),Kt=S.find(MB),Ke=await ZZt(_e,zu(),Kt?.content??"",Fe);Ke.matched&&ja.getInstance().recordUsage(Ke.matched);let $e=Hwe(Ke.text,Fe),Be=!(S.length>0)&&(ce||$e.includes(xC)),Qe=Vwe(i,me??[],Be);if(q.length>0&&te){new aX.Notice(`${te} doesn't support images. Switch to a vision-capable model to send images.`);return}let dt;if(s){let ii=S4e({mentionedAgentIds:O.current,installedAgentIds:M});CY(ii,s)&&(dt=ii)}O.current=[],Y(),PG();let yt=[];for(let ii of q){let Vn=await Umr(ii);Vn&&yt.push(Vn)}if(q.length>0&&!$e&&yt.length===0){new aX.Notice("Could not read the attached images. Please attach them again.");return}let Dr={id:`queued-${zr()}`,text:$e,rawInput:Pe,context:n7t(Oe,S,Qe),promptContent:yt.length>0?yt:void 0,mentionedAgents:dt};if(c||l||_){N(ii=>[...ii,{...Dr,queueReason:_?"context":"busy"}]);return}await K(Dr)},[i,F,q,Z,re,ce,S,c,l,te,_,g,Y,K,N,s,M]);(0,Es.useEffect)(()=>{if(g||c||l||_||oe.length===0)return;let me=t7t(oe);if(me.promptContent?.some(_e=>_e.type==="image")&&te){new aX.Notice(`${te} doesn't support images. Switch to a vision-capable model to send images.`);return}N([]),K(me)},[g,c,l,_,oe,K,N,te]);let fe=(0,Es.useCallback)(me=>{N(_e=>_e.filter(Pe=>Pe.id!==me))},[N]);return(0,Es.useEffect)(()=>{let me=()=>{de()};return y?.addEventListener(rs.ABORT_STREAM,me),()=>{y?.removeEventListener(rs.ABORT_STREAM,me)}},[y,de]),Es.default.createElement(Es.default.Fragment,null,oe.length>0&&Es.default.createElement(QZt,{messages:oe,onRemove:fe}),Es.default.createElement("div",{className:u||g?"tw-pointer-events-none tw-opacity-50":void 0,"aria-disabled":u||g||void 0},Es.default.createElement(Rwe,{ref:v,key:r,isAgentMode:!0,placeholder:"Ask anything • @ to add context • / for commands",inputMessage:F,setInputMessage:ne,handleSendMessage:fn(me=>ee(me?.webTabs)),isGenerating:c,onStopGenerating:fn(de),onEscape:c?fn(de):void 0,onShiftTab:f?p:void 0,app:i,contextNotes:Z,setContextNotes:G,includeActiveNote:re,setIncludeActiveNote:L,includeActiveWebTab:ce,setIncludeActiveWebTab:z,activeWebTab:k,selectedImages:q,onAddImage:B,setSelectedImages:
`);for(let l of a){let c=l.trim();if(!c)continue;let u=g7t(s,c);n.has(u)||(n.add(u),r.push({id:u,url:c,type:s}))}};return o(t,"web"),o(e,"youtube"),r}function dX(t){let e=new Set,n=new Set,r=[],o=[];for(let i of t){let s=i.url.trim();if(s)if(i.type==="youtube"){if(n.has(s))continue;n.add(s),o.push(s)}else{if(e.has(s))continue;e.add(s),r.push(s)}}return{webUrls:r.join(`
`),youtubeUrls:o.join(`
`)}}function Ymr(t){let e=t.trim();if(!e)return!1;try{let n=new URL(e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username)return!1;let r=n.hostname.toLowerCase();return r?!!(r==="localhost"||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(r)||r.startsWith("[")&&r.endsWith("]")||r.includes(".")):!1}catch{return!1}}var Kmr,Gmr,w7t=b(()=>{she();Kmr={")":"(","]":"[","}":"{"},Gmr=/[.,;:!?,。!?;:、]/u});var iS=b(()=>{w7t()});function Qmr(t){let e=t.split(".").pop()?.toLowerCase()??"";return e==="pdf"?"pdf":Jmr.has(e)?"image":Xmr.has(e)?"audio":"other"}function ehr(t){return o3e(t)}function v7t(t,e){let n=t==="file"?Qmr(e):t==="youtube"?"youtube":ehr(e);return{id:e,name:thr(e),source:t==="file"?"file":"url",fileType:n,cacheKind:t}}function thr(t){if(t.startsWith("http://")||t.startsWith("https://"))try{let n=new URL(t),r=n.hostname.replace("www.",""),o=n.pathname+n.search;if(o&&o!=="/"){let s=o.length>30?o.slice(0,30)+"...":o;return r+s}return r}catch{return t.slice(0,50)}let e=t.split("/");return e[e.length-1]||t}var Jmr,Xmr,b7t=b(()=>{iS();Jmr=new Set(["jpg","jpeg","png","gif","bmp","webp","svg","tiff"]),Xmr=new Set(["mp3","wav","m4a","ogg","flac","aac","mp4","mpeg","mpga","webm"])});function Xwe(t,e){return[...t.map(n=>({kind:n.type,source:n.url})),...e.map(n=>({kind:"file",source:n.path,fingerprint:`${n.stat.mtime}:${n.stat.size}`}))]}async function nhr(t,e){let n=new Set,r=new Map,o=new Map,[i,s,a]=await Promise.all([a3e(t.remotes),a3e(t.files),a3e(t.markers)]);for(let l of i)l.endsWith(".md")&&n.add(l);for(let l of s)if(l.endsWith(".md")&&(n.add(l),e.has(l))){let c=await ohr(t.files,l);c&&o.set(l,c.fingerprint)}for(let l of a){if(!l.startsWith("failed-")||!l.endsWith(".json"))continue;let c=await rhr(t.markers,l);c&&r.set(l,c)}return{snapshotNames:n,markersByName:r,fingerprintsByName:o}}async function Qwe(t,e,n){if(vn())try{let{remotesDir:r,filesDir:o,markersDir:i}=await Promise.resolve().then(()=>(l1(),Sme)),{createNodeContextCacheFs:s}=await Promise.resolve().then(()=>(Uj(),Yme)),a=l=>{let c=s(l);return{list:()=>c.list(""),readText:u=>c.readText(u)}};return await nhr({remotes:a(r(t)),files:a(o(t)),markers:a(i(t,e))},n)}catch{return}}async function a3e(t){try{return await t.list()}catch{return[]}}async function rhr(t,e){try{return n4e(await t.readText(e))}catch{return null}}async function ohr(t,e){try{return r4e(await t.readText(e))}catch{return null}}function ihr(t,e){return e==="file"?t.type==="nonMd":t.type===e}function eve(t,e,n,r){let o=e!==void 0&&shr.has(e.phase),i=e?.failedSources??[],s=e?.retryingSources??qpt,a=e?.processingSources??Kpt;return t.map(({kind:l,source:c,fingerprint:u})=>{let d=`${l}:${c}`,f="pending",p,m=i.find(x=>x.path===c&&ihr(x,l)),h=wb(l,c),g=n?.snapshotNames.has(h)??!1,w=n?.markersByName.get(yY(l,c)),y=s.some(x=>x.kind===l&&x.source===c),v=a.some(x=>x.kind===l&&x.source===c),_=n?.fingerprintsByName.get(h),S=g&&(l!=="file"||_!==void 0&&_===u),k=w!==void 0&&(l!=="file"||w.fingerprint===u)?w:void 0;return(y||v)&&r.has(d)?f="processing":m&&!m.usedStaleSnapshot?(f="failed",p=m.error):m?.usedStaleSnapshot||S?f="ready":k?(f="failed",p=k.error):o&&r.has(d)&&(f="pending"),{...v7t(l,c),status:f,...p!==void 0?{error:p}:{}}})}var shr,l3e=b(()=>{Ma();b7t();jj();tn();shr=new Set(["resolve","prefetch","parse"])});function tve(t,e,n,r){let o=r?.enabled??!0,i=or(_y,{store:Sn}),s=o?i[e.id]:void 0,a=o?n?.inclusions:void 0,l=o?n?.exclusions:void 0,c=(0,sS.useMemo)(()=>o?l4t(t,{inclusions:a,exclusions:l}):{candidates:[],skippedMarkdownCount:0},[t,o,a,l]),u=c.candidates,d=(0,sS.useMemo)(()=>{if(!o)return[];let y=Db(n?.webUrls||"",n?.youtubeUrls||"");return Xwe(y,u)},[o,n?.webUrls,n?.youtubeUrls,u]),f=e.contextSource,p=(0,sS.useMemo)(()=>{let y=new Set;if(!o)return y;let v=Db(f?.webUrls||"",f?.youtubeUrls||"");for(let _ of v)y.add(_.id);for(let _ of Fj(t,f))y.add(`file:${_.path}`);return y},[t,o,f]),m=(0,sS.useMemo)(()=>new Set(u.map(y=>wb("file",y.path))),[u]),[h,g]=(0,sS.useState)(void 0);return(0,sS.useEffect)(()=>{if(!o){g(void 0);return}let
`,e),r=n>=e-1024&&n>0?n:e;return{text:t.slice(0,r),truncated:!0}}var x7t=b(()=>{});var yg,nve,S7t=b(()=>{ge();q5();x7t();yg=require("obsidian"),nve=class extends yg.Modal{constructor(n,r,o){super(n);this.title=r;this.content=o;this.component=new yg.Component}onOpen(){let{contentEl:n,modalEl:r}=this;r.addClass("!tw-w-[90vw]","!tw-max-w-[800px]"),n.empty(),n.addClass("tw-flex","tw-flex-col","tw-p-0"),this.component.load();let{text:o,truncated:i}=_7t(this.content),s=n.createDiv({cls:"tw-flex tw-items-center tw-justify-between tw-px-5 tw-py-3 tw-border-b tw-border-border"}),a=s.createDiv({cls:"tw-flex tw-items-center tw-gap-2 tw-min-w-0"}),l=a.createDiv({cls:"tw-text-muted tw-shrink-0"});(0,yg.setIcon)(l,"file-text"),a.createSpan({text:this.title,cls:"tw-font-semibold tw-text-normal tw-truncate"});let c=s.createEl("button",{cls:"tw-flex tw-items-center tw-gap-1 tw-px-2 tw-py-1 tw-rounded-md tw-bg-secondary tw-border-none tw-cursor-pointer tw-text-muted hover:tw-text-normal tw-shrink-0",attr:{"aria-label":"Copy content",title:"Copy content"}}),u=c.createSpan({cls:"tw-flex tw-items-center"});if((0,yg.setIcon)(u,"copy"),this.bindCopyFullContent(c,u),i){let m=Math.round(3e4/1e3);n.createDiv({text:`Preview shows the first ${m} KB for performance. Use Copy to get the full content.`,cls:"tw-px-5 tw-py-2 tw-text-sm tw-text-muted tw-border-b tw-border-border tw-bg-secondary"})}let d=n.createDiv({cls:i?"tw-h-[50vh] tw-overflow-auto tw-p-5":"tw-max-h-[50vh] tw-overflow-auto tw-p-5"}),f=d.createDiv({cls:"markdown-rendered tw-p-4 tw-bg-primary-alt tw-rounded-lg tw-border tw-border-border"});if(i){let m=d.createDiv({cls:"tw-flex tw-items-center tw-gap-3 tw-pt-6 tw-pb-1"});m.createDiv({cls:"tw-flex-grow tw-border-t tw-border-border"});let h=m.createEl("button",{cls:"tw-flex tw-shrink-0 tw-items-center tw-gap-2 tw-px-4 tw-py-1.5 tw-rounded-full tw-bg-secondary tw-border tw-border-border tw-cursor-pointer tw-text-xs tw-font-medium tw-uppercase tw-tracking-wide tw-text-muted hover:tw-text-accent hover:tw-border-accent",attr:{"aria-label":"Copy full content",title:"Copy full content"}}),g=h.createSpan({cls:"tw-flex tw-items-center"});(0,yg.setIcon)(g,"copy"),h.createSpan({text:"Copy full content"}),this.bindCopyFullContent(h,g),m.createDiv({cls:"tw-flex-grow tw-border-t tw-border-border"})}let p=()=>{EI(this.app,o,f,"",this.component).catch(m=>{V("[CachePreviewModal] markdown render failed",m)})};if(i){let m=this.contentEl.win??window;this.renderRafWin=m,this.renderRafId=m.requestAnimationFrame(()=>{this.renderRafId=m.requestAnimationFrame(()=>{this.renderRafId=void 0,p()})})}else p()}onClose(){this.renderRafId!==void 0&&((this.renderRafWin??window).cancelAnimationFrame(this.renderRafId),this.renderRafId=void 0),this.renderRafWin=void 0,this.component.unload(),this.contentEl.empty()}bindCopyFullContent(n,r){n.addEventListener("click",()=>{navigator.clipboard.writeText(this.content).then(()=>{(0,yg.setIcon)(r,"check"),n.addClass("tw-text-accent"),new yg.Notice("Copied to clipboard"),(n.win??window).setTimeout(()=>{(0,yg.setIcon)(r,"copy"),n.removeClass("tw-text-accent")},2e3)},()=>new yg.Notice("Failed to copy"))})}}});function C7t(t){if(Sj(t)==="ENOENT"||t instanceof Error&&t.name==="NotFoundError")return!0;let e=t instanceof Error?t.message:String(t);return/ENOENT|no such file|not found|does not exist/i.test(e)}var k7t=b(()=>{ime()});async function SH(t,e){if(!vn()){new fX.Notice("Converted previews are available on desktop only.");return}let n=wb(e.cacheKind,e.id);try{let{remotesDir:r,filesDir:o}=await Promise.resolve().then(()=>(l1(),Sme)),{createNodeContextCacheFs:i}=await Promise.resolve().then(()=>(Uj(),Yme)),s=e.cacheKind==="file"?o(t):r(t),a=await i(s).readText(n);if(!a.trim()){new fX.Notice("No content available for this item.");return}new nve(t,e.name,a).open()}catch(r){if(C7t(r)){new fX.Notice("No converted content yet for this item.");return}W(`Failed to read agent cached snapshot: ${n}`,r),new fX.Notice("Failed to read converted content.")}}var fX,rve=b(()=>{S7t();jj();ge();tn();k7t();fX=require("obsidian")});var ive,ove,T7t=b(()
`)),popoverContainer:o}),He.default.createElement(aS,null),He.default.createElement(O3e,{title:"Tags",IconComponent:aP,iconColorClassName:"tw-text-context-manager-orange",items:re(p.tags,$=>$.slice(1)),activeItem:x,activeSection:S,sectionType:"tags",renderIcon:$=>He.default.createElement("span",{className:"tw-mr-2 tw-text-faint"},"#"),onItemClick:G.click.tag,onAddClick:G.add.tag,onDeleteItem:($,te)=>G.delete.tag($,te),tooltip:"must be in note property",onSectionClick:()=>ne("tags",null)}),He.default.createElement(aS,null),He.default.createElement(O3e,{title:"Properties",IconComponent:oP,iconColorClassName:"tw-text-context-manager-purple",items:re(p.properties,$=>kE({pattern:$,type:"property"})),activeItem:x,activeSection:S,sectionType:"properties",onItemClick:G.click.property,onAddClick:G.add.property,onDeleteItem:($,te)=>G.delete.property($,te),tooltip:"Include notes by a frontmatter property, e.g. Topics: Physics",onSectionClick:()=>ne("properties",null)}),He.default.createElement(aS,null),He.default.createElement(O3e,{title:"Folders",IconComponent:Ul,iconColorClassName:"tw-text-context-manager-yellow",items:re(p.folders),activeItem:x,activeSection:S,sectionType:"folders",onItemClick:G.click.folder,onAddClick:G.add.folder,onDeleteItem:($,te)=>G.delete.folder($,te),onSectionClick:()=>ne("folders",null)}),He.default.createElement(aS,null),He.default.createElement("div",null,He.default.createElement(N3e,{IconComponent:Ko,title:"Files",iconColorClassName:"tw-text-context-manager-blue",onAddClick:G.add.file}),He.default.createElement("div",{className:X("tw-cursor-pointer tw-rounded-md tw-p-2 tw-text-sm hover:tw-bg-secondary/50",S==="files"&&"tw-bg-secondary tw-text-normal"),onClick:G.click.files},"Files (",p.notes.length,")")),He.default.createElement(aS,null),He.default.createElement("div",null,He.default.createElement(N3e,{IconComponent:Cn,title:"Ignore Files",iconColorClassName:"tw-text-context-manager-red",onAddClick:G.add.ignoreFile}),He.default.createElement("div",{className:X("tw-cursor-pointer tw-rounded-md tw-p-2 tw-text-sm hover:tw-bg-secondary/50",S==="ignoreFiles"&&"tw-bg-secondary tw-text-normal"),onClick:G.click.ignoreFiles},"Files (",h.files.size,")")))))),He.default.createElement(lYt,{withHandle:!0}),He.default.createElement(I3e,{defaultSize:i?65:70},He.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},He.default.createElement("div",{className:"tw-border-b tw-p-4"},He.default.createElement(mf,{placeholder:"Custom search: title, #tag1, .jpg",value:v,onChange:$=>{_($),$&&ne("search",null,!1)}})),He.default.createElement("div",{className:"tw-p-4"},He.default.createElement("h3",{className:"tw-text-lg tw-font-medium tw-text-muted"},B())),He.default.createElement(aw,{className:"tw-max-h-[400px] tw-flex-1 tw-p-4 tw-pt-0"},T?He.default.createElement(EYt,{app:r,urlItems:s.urlItems,filter:S,agentProcessingByKey:l,onRemove:s.removeUrl}):Z.length===0?He.default.createElement("div",{className:"tw-mt-10 tw-text-center tw-text-muted"},S?"No items found.":"No categories found. Add tags, folders, or files using the sidebar."):He.default.createElement("div",{className:"tw-space-y-2",style:{display:"block"}},S||v?q(Z).map($=>L&&R3e($)?He.default.createElement(NYt,{key:$.id,item:$,onClick:ue}):R3e($)?null:He.default.createElement(igr,{key:$.id,item:$,viewMode:"list",onDelete:S==="ignoreFiles"||$.isIgnored?N:z,...I($)})).filter(Boolean):Z.map($=>R3e($)?He.default.createElement(NYt,{key:$.id,item:$,onClick:ue}):null).filter(Boolean)))))),He.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2 tw-border-t tw-p-1"},He.default.createElement(ie,{variant:"ghost",onClick:n},"Cancel"),He.default.createElement(ie,{onClick:Y},"Save")))}var Fb,He,N3e,O3e,IE,bve=b(()=>{p7t();Ywe();c3e();rve();I7t();A7t();M7t();lve();Hx();ot();cYt();l4();w0();A3e();De();Id();vt();Le();Fb=require("obsidian"),He=R(U());$h();Qa();MYt();RYt();bX();N3e=({IconComponent:t,title:e,iconColorClassName:n,onAddClick:r,tooltip:o,onTitleClick:i})=>He.default.createElement("div",{className:"tw-mb-3 tw-flex tw-items-center tw-justif
`)){let s=lgr(t,i);s&&r.set(s.path,s)}return[...r.values()]}function FYt(t){let{app:e,projectId:n,dropRef:r,enabled:o=!0}=t,[i,s]=(0,Sve.useState)(!1);return(0,Sve.useEffect)(()=>{let a=r.current;if(!a||!o)return;let l=f=>{f.dataTransfer&&(f.preventDefault(),!f.dataTransfer.types.includes($Yt)&&(f.dataTransfer.dropEffect="copy",s(!0)))},c=f=>{let p=a.getBoundingClientRect(),{clientX:m,clientY:h}=f;(m<p.left||m>=p.right||h<p.top||h>=p.bottom)&&s(!1)},u=async f=>{if(!f.dataTransfer||(f.preventDefault(),f.stopPropagation(),s(!1),f.dataTransfer.types.includes($Yt)))return;let p=Array.from(f.dataTransfer.items),m=p.filter(w=>w.kind==="string"),h=p.some(w=>w.kind==="file"),g=m.length>0?await ugr(e,m):[];if(g.length===0){h&&new lS.Notice("Only vault files or folders can be added to project context");return}try{await cgr(e,n,g)>0?new lS.Notice("Added to project context"):new lS.Notice("Already in project context")}catch(w){V("[project-context] failed to add dropped inclusion",w),new lS.Notice("Could not add to project context")}},d=f=>void u(f);return a.addEventListener("dragover",l),a.addEventListener("dragleave",c),a.addEventListener("drop",d),()=>{a.removeEventListener("dragover",l),a.removeEventListener("dragleave",c),a.removeEventListener("drop",d)}},[e,n,r,o]),{isDragging:i}}var lS,Sve,$Yt,zYt=b(()=>{ge();fk();Cd();Id();lS=require("obsidian"),Sve=R(U()),$Yt="copilot/internal-drag"});function BYt(t){if(!t)return UYt;let e=mX(t.contextSource?.inclusions),n={files:0,folders:0,tags:0,extensions:0};for(let i of e)i.type==="note"?n.files++:i.type==="folder"?n.folders++:i.type==="tag"?n.tags++:n.extensions++;let r=Db(t.contextSource?.webUrls??"",t.contextSource?.youtubeUrls??"").length,o=e.length+r;return o===0?UYt:{totalItems:o,isEmpty:!1,...n,urls:r}}function Cve({app:t,projectId:e,popoverContainer:n}){let r=Nme(),o=(0,Qm.useMemo)(()=>r.find(h=>h.id===e),[r,e]),i=o?.contextSource,[s,a]=(0,Qm.useState)(i),l=(0,Qm.useRef)(null),c=(0,Qm.useRef)(!1);(0,Qm.useEffect)(()=>{!l.current&&!c.current&&a(i)},[i]);let u=(0,Qm.useCallback)(()=>{if(c.current)return;let h=l.current;if(!h)return;l.current=null,c.current=!0;let g=ao(e)?.project;if(!g){c.current=!1;return}ll.getInstance(t).updateProject(e,{...g,contextSource:{...g.contextSource,...h}}).catch(w=>{V("[project-context] failed to save context changes",w),l.current||a(ao(e)?.project.contextSource)}).finally(()=>{c.current=!1,l.current&&u()})},[t,e]),d=(0,Qm.useCallback)(h=>{a(g=>({...g??{},...h})),l.current={...l.current??{},...h},u()},[u]),f=(0,Qm.useRef)(null),{isDragging:p}=FYt({app:t,projectId:e,dropRef:f}),m=(0,Qm.useCallback)(()=>{if(!o)return;new IE(t,g=>{ll.getInstance(t).updateProject(e,g).catch(w=>V("[project-context] failed to save context changes",w))},o).open()},[t,o,e]);return o?D3e.createElement("div",{ref:f,"data-copilot-drop-zone":!0,className:X("tw-flex tw-min-h-48 tw-grow tw-flex-col tw-p-2")},D3e.createElement(xve,{contextSource:s,onChange:d,onManage:m,popoverContainer:n,isDragging:p,className:"tw-grow"})):null}var D3e,Qm,UYt,jYt=b(()=>{bve();lve();L3e();De();ge();fk();Cd();iS();D3e=R(U()),Qm=R(U());zYt();UYt=Object.freeze({totalItems:0,isEmpty:!0,files:0,folders:0,tags:0,extensions:0,urls:0})});function dgr({fileType:t}){switch(t){case"pdf":return Tt.default.createElement(Ko,{className:"tw-size-3.5 tw-text-error"});case"image":return Tt.default.createElement(wR,{className:"tw-size-3.5 tw-text-accent"});case"web":case"youtube":return Tt.default.createElement(Go,{className:"tw-size-3.5 tw-text-accent"});case"audio":return Tt.default.createElement(vR,{className:"tw-size-3.5 tw-text-warning"});default:return Tt.default.createElement(Ko,{className:"tw-size-3.5 tw-text-muted"})}}function fgr(t){return{ready:t.filter(e=>e.status==="ready").length,processing:t.filter(e=>e.status==="processing").length,failed:t.filter(e=>e.status==="failed").length,pending:t.filter(e=>e.status==="pending").length,unsupported:t.filter(e=>e.status==="unsupported").length,total:t.length}}function WYt(t){return[...t].sort((e,n)=>(HYt[e.status]??99)-(HYt[n.status]??99))}function KYt({items:t,o
`).filter(o=>o.trim()),r=[];for(let o of n){let i=$yr(t,o.trim());i&&r.push(i)}return r}function zyr(t){let e=t.toLowerCase();return e==="jpg"?"image/jpeg":`image/${e}`}function ibe(t){let{app:e,contextNotes:n,setContextNotes:r,selectedImages:o,onAddImage:i,containerRef:s}=t,[a,l]=(0,obe.useState)(!1);return(0,obe.useEffect)(()=>{let c=s.current;if(!c)return;let u=h=>{if((h.target instanceof HTMLElement?h.target:null)?.closest("[data-copilot-drop-zone]")){l(!1);return}if(h.preventDefault(),h.dataTransfer){if(h.dataTransfer.dropEffect="copy",h.dataTransfer.types.includes("copilot/internal-drag"))return;let w=Array.from(h.dataTransfer.items).some(v=>v.kind==="string"),y=Array.from(h.dataTransfer.items).some(v=>v.kind==="file");(w||y)&&l(!0)}},d=h=>{let g=c.getBoundingClientRect(),w=h.clientX,y=h.clientY;(w<g.left||w>=g.right||y<g.top||y>=g.bottom)&&l(!1)},f=async h=>{if(!h.dataTransfer||(h.target instanceof HTMLElement?h.target:null)?.closest("[data-copilot-drop-zone]"))return;h.preventDefault(),l(!1);let w=h.dataTransfer.items,y=[],v=[];for(let _=0;_<w.length;_++){let S=w[_];S.kind==="string"?y.push(S):S.kind==="file"&&v.push(S)}if(y.length>0){h.stopPropagation();let _=y.map(x=>new Promise(C=>{x.getAsString(T=>C(T))})),S=await Promise.all(_),k=new Map;for(let x of S){let C=Fyr(e,x);for(let T of C)k.set(T.path,T)}for(let x of k.values())if(["png","gif","jpeg","jpg","webp"].includes(x.extension)){if(o.some(D=>D.name===x.name)){new vL.Notice("This image is already in the context");continue}let I=await e.vault.readBinary(x),M=new Blob([I]),O=new File([M],x.name,{type:zyr(x.extension)});i([O])}else if(E_(x)){if(n.some(I=>I.path===x.path)){new vL.Notice("This note is already in the context");continue}r(I=>[...I,x])}else new vL.Notice(`Unsupported file type: ${x.extension}. Supported types: md, pdf, canvas, and images.`)}else if(v.length>0){let _=[];for(let S of v){let k=S.getAsFile();k&&k.type.startsWith("image/")&&_.push(k)}_.length>0&&i(_)}},p=h=>{f(h)},m=()=>l(!1);return c.addEventListener("dragover",u,!0),c.addEventListener("dragleave",d),c.addEventListener("drop",p),c.addEventListener("drop",m,!0),()=>{c.removeEventListener("dragover",u,!0),c.removeEventListener("dragleave",d),c.removeEventListener("drop",p),c.removeEventListener("drop",m,!0)}},[e,n,o,i,r,s]),{isDragActive:a}}var vL,obe,_qe=b(()=>{vt();vL=require("obsidian"),obe=R(U())});var nT,_t,Uyr,Byr,lQt,cQt=b(()=>{HVt();qZt();rHe();o7t();d7t();jYt();tJt();rJt();dJt();W3e();hJt();_Jt();TJt();IJt();OJt();aqe();lqe();wXt();CXt();IXt();RXt();LXt();FXt();UXt();Kve();HXt();VXt();KXt();ZXt();JXt();vqe();bqe();pL();aQt();Ox();Ma();U3e();bve();Hx();xt();no();eX();_qe();De();ge();fk();jme();Cd();Ee();gs();Le();nT=require("obsidian"),_t=R(U());Dc();Uyr=Object.freeze({}),Byr=({backend:t,sessionId:e,chatInputId:n,draft:r,manager:o,plugin:i,onSaveChat:s,updateUserMessageHistory:a})=>{let l=(0,_t.useContext)(LO),c=i.app||l,u=pt(),d=(0,_t.useContext)(Xd),f=xE(),p=$Xt(c);GXt(),(0,_t.useEffect)(()=>{let on=d instanceof ry?d:null,Wi=gC=>{on?.consumePendingInsertText();let yC=gC.detail?.text;typeof yC=="string"&&f.insertTextWithPills(yC,!0)};d?.addEventListener(rs.INSERT_TEXT_TO_CHAT,Wi);let $l=on?.consumePendingInsertText();return typeof $l=="string"&&f.insertTextWithPills($l,!0),()=>{d?.removeEventListener(rs.INSERT_TEXT_TO_CHAT,Wi)}},[d,f]);let{messages:m,isStarting:h,isTurnInFlight:g,hasPendingPlanPermission:w,currentPlan:y,currentTodoList:v,pendingToolPermissions:_,pendingAskUserQuestions:S}=zXt(t),k=r.loading||g,[x,C]=(0,_t.useState)(null),T=(0,_t.useRef)(null);(0,_t.useEffect)(()=>{s(async()=>{await o.saveActiveSession()})},[s,o]);let I=(0,_t.useCallback)(async()=>{try{await o.saveActiveSession()?new nT.Notice("Chat saved as note."):new nT.Notice("Nothing to save yet.")}catch(on){W("[AgentMode] manual save failed",on),new nT.Notice("Failed to save chat as note. Check console for details.")}},[o]),M=(0,_t.useCallback)(()=>{if(o.getIsStarting())return;let on=o.getActiveSession();if(!on||!on.hasUserVisibleMessages())return;let Wi=on.internalId;(async()=>{try{await o.replaceSessionI
`):"",a=Array.isArray(t)?t:[],l=0;for(let u=0;u<a.length;u++){let d=a[u],f=s(d);if(d.role==="system"){n.push("━━━ SYSTEM MESSAGE ━━━"),n.push("");let p=e?.layers.find(h=>h.id==="L1_SYSTEM"),m=e?.layers.find(h=>h.id==="L2_PREVIOUS");if(p&&f.includes(p.text)){let h=p.hash.substring(0,8);n.push(`🔒 L1_SYSTEM (${h}) [CACHEABLE]`);let g=f.indexOf(p.text)+p.text.length,w=p.text.length>300?p.text.substring(0,300)+"...[truncated]":p.text;if(n.push(w),n.push(""),m&&m.text){let _=m.hash.substring(0,8);n.push(`🔒 L2_PREVIOUS (${_}) [CACHEABLE]`);let S=m.text.length>300?m.text.substring(0,300)+"...[truncated]":m.text;n.push(S),n.push("")}let y=f.substring(g),v=i(y);if(v.length>0){n.push("--- PER-TURN ADDITIONS (not cached) ---"),n.push("");for(let _ of v)n.push(`📦 TOOL: ${_.tool} (turn-specific RAG)`),n.push(_.preview),n.push("")}}else{let h=i(f);if(h.length>0){let g=f.match(/<(\w+)>/);if(g){let w=f.substring(0,g.index);if(w.trim()){let y=w.length>300?w.substring(0,300)+"...[truncated]":w;n.push(y),n.push("")}}n.push("--- PER-TURN ADDITIONS (not cached) ---"),n.push("");for(let w of h)n.push(`📦 TOOL: ${w.tool}`),n.push(w.preview),n.push("")}else{let g=f.length>300?f.substring(0,300)+"...[truncated]":f;n.push(g),n.push("")}}}else(d.role==="user"||d.role==="assistant")&&u<a.length-1&&l++}l>0&&(n.push("━━━ CHAT HISTORY (L4) ━━━"),n.push(""),n.push(`${l} message(s)`),n.push(""));let c=a[a.length-1];if(c&&c.role==="user"){n.push("━━━ USER MESSAGE ━━━"),n.push("");let u=s(c),d=i(u);if(d.length>0){n.push("--- PER-TURN TOOL RESULTS ---"),n.push("");for(let m of d)n.push(`📦 TOOL: ${m.tool}`),n.push(m.preview),n.push("")}let f=e?.layers.find(m=>m.id==="L3_TURN"),p=e?.layers.find(m=>m.id==="L5_USER");if(f&&f.text&&u.includes(f.text)){let m=f.hash.substring(0,8);n.push(`⚡ L3_TURN (${m})`);let h=f.text.length>300?f.text.substring(0,300)+"...[truncated]":f.text;n.push(h),n.push("")}if(p&&p.text&&u.includes(p.text)){let m=p.hash.substring(0,8);n.push(`⚡ L5_USER (${m})`),n.push(p.text),n.push("")}}return n.join(`
`)}function zH(t){let{messages:e,modelName:n,contextEnvelope:r}=t;try{FH={timestamp:new Date().toISOString(),modelName:n,serializedMessages:twr(e),messagesArray:e,contextEnvelope:r}}catch{FH={timestamp:new Date().toISOString(),modelName:n,serializedMessages:String(e),messagesArray:e,contextEnvelope:r}}}function UH(){FH=null}async function hbe(){if(!FH)return;let{timestamp:t,modelName:e,serializedMessages:n,messagesArray:r,contextEnvelope:o}=FH,i=[`### Prompt — ${t}${e?` — ${e}`:""}`,"","**Actual Messages Sent to LLM:**","","```json",n,"```",""],s=nwr(r,o);i.push("**Layered Context Metadata:**"),i.push(""),i.push("```"),i.push(s),i.push("```"),i.push(""),qoe(i),FH=null}var FH,RE=b(()=>{ge();$H();FH=null});function fwr(t,e){return dwr(t,e||{},0,0)}function BQt(t,e){if(e){for(var n=new Bf(t.length),r=0;r<t.length;++r)n[r]=t.charCodeAt(r);return n}if(UQt)return UQt.encode(t);for(var o=t.length,i=new Bf(t.length+(t.length>>1)),s=0,a=function(u){i[s++]=u},r=0;r<o;++r){if(s+5>i.length){var l=new Bf(s+8+(o-r<<1));l.set(i),i=l}var c=t.charCodeAt(r);c<128||e?a(c):c<2048?(a(192|c>>6),a(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|t.charCodeAt(++r)&1023,a(240|c>>18),a(128|c>>12&63),a(128|c>>6&63),a(128|c&63)):(a(224|c>>12),a(128|c>>6&63),a(128|c&63))}return KQt(i,0,s)}function XQt(t,e){e||(e={});var n={},r=[];JQt(t,"",n,e);var o=0,i=0;for(var s in n){var a=n[s],l=a[0],c=a[1],u=c.level==0?0:8,d=BQt(s),f=d.length,p=c.comment,m=p&&BQt(p),h=m&&m.length,g=Eqe(c.extra);f>65535&&ybe(11);var w=u?fwr(l,c):l,y=w.length,v=uwr();v.p(l),r.push(YQt(c,{size:l.length,crc:v.d(),c:w,f:d,m,u:f!=s.length||m&&p.length!=h,o,compression:u})),o+=30+f+g+y,i+=76+2*(f+g)+(h||0)+y}for(var _=new Bf(i+22),S=o,k=i-o,x=0;x<r.length;++x){var d=r[x];jQt(_,d.o,d,d.f,d.u,d.c.length);var C=30+d.f.length+Eqe(d.extra);_.set(d.c,d.o+C),jQt(_,o,d,d.f,d.u,d.c.length,d.o,d.m),o+=16+C+(d.m?d.m.length:0)}return hwr(_,o,r.length,k,S),_}var Bf,Sg,Mqe,Oqe,Rqe,DQt,HQt,WQt,rwr,Iqe,VQt,jQo,$Qt,Pqe,rT,ki,NX,_L,ki,ki,ki,ki,gbe,ki,owr,iwr,qQt,KQt,swr,ybe,oT,OX,Tqe,Aqe,FQt,RX,GQt,zQt,awr,ZQt,lwr,cwr,uwr,dwr,YQt,Od,JQt,UQt,pwr,mwr,Eqe,jQt,hwr,QQt=b(()=>{Bf=Uint8Array,Sg=Uint16Array,Mqe=Int32Array,Oqe=new Bf([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Rqe=new Bf([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),DQt=new Bf([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),HQt=function(t,e){for(var n=new Sg(31),r=0;r<31;++r)n[r]=e+=1<<t[r-1];for(var o=new Mqe(n[30]),r=1;r<30;++r)for(var i=n[r];i<n[r+1];++i)o[i]=i-n[r]<<5|r;return{b:n,r:o}},WQt=HQt(Oqe,2),rwr=WQt.b,Iqe=WQt.r;rwr[28]=258,Iqe[258]=28;VQt=HQt(Rqe,0),jQo=VQt.b,$Qt=VQt.r,Pqe=new Sg(32768);for(ki=0;ki<32768;++ki)rT=(ki&43690)>>1|(ki&21845)<<1,rT=(rT&52428)>>2|(rT&13107)<<2,rT=(rT&61680)>>4|(rT&3855)<<4,Pqe[ki]=((rT&65280)>>8|(rT&255)<<8)>>1;NX=function(t,e,n){for(var r=t.length,o=0,i=new Sg(e);o<r;++o)t[o]&&++i[t[o]-1];var s=new Sg(e);for(o=1;o<e;++o)s[o]=s[o-1]+i[o-1]<<1;var a;if(n){a=new Sg(1<<e);var l=15-e;for(o=0;o<r;++o)if(t[o])for(var c=o<<4|t[o],u=e-t[o],d=s[t[o]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)a[Pqe[d]>>l]=c}else for(a=new Sg(r),o=0;o<r;++o)t[o]&&(a[o]=Pqe[s[t[o]-1]++]>>15-t[o]);return a},_L=new Bf(288);for(ki=0;ki<144;++ki)_L[ki]=8;for(ki=144;ki<256;++ki)_L[ki]=9;for(ki=256;ki<280;++ki)_L[ki]=7;for(ki=280;ki<288;++ki)_L[ki]=8;gbe=new Bf(32);for(ki=0;ki<32;++ki)gbe[ki]=5;owr=NX(_L,9,0),iwr=NX(gbe,5,0),qQt=function(t){return(t+7)/8|0},KQt=function(t,e,n){return(e==null||e<0)&&(e=0),(n==null||n>t.length)&&(n=t.length),new Bf(t.subarray(e,n))},swr=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ybe=function(t,e,n){var r=new Error(e||swr[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,ybe),!n)throw r;return r},oT=function(t,e,n){n<<=e&7;var r=e/8|0;t[r]|=n,t[r+1]|=n>>8},OX=function(t,e,n){n<<=e&7;var r=e/8|0;t[r]|=n,t[r+1]|=n>>8,t[r+2]|=
${t}`}function Lqe(t,e){let n=BH(t);if(n.length<=e)return{text:t,totalBytes:n.length};let r=e;for(;r>0&&(n[r]&192)===128;)r--;return{text:new TextDecoder().decode(n.subarray(0,r)),totalBytes:n.length}}function BH(t){return new TextEncoder().encode(t)}function Dqe(t){return BH(t).length}async function oen(t,e){let{size:n}=await t.stat();if(n>e||n===0)return{text:"",totalBytes:n};let r=new Uint8Array(n),o=0;for(;o<n;){let{bytesRead:i}=await t.read(r,o,n-o,o);if(i<=0)break;o+=i}return{text:new TextDecoder().decode(r.subarray(0,o)),totalBytes:o===0?0:n}}var ten,nen,ien=b(()=>{lA();ten=256,nen=64*1024});async function uen(t,e=Bqe()){let n=Iwr-$qe,r=Object.create(null),o=[],i=({result:c,bytes:u})=>{o.push(c),u&&(r[c.name]=u,n-=u.length)};t.screenshotPng!==void 0&&i(Pwr(t.screenshotPng,n));for(let c of t.logs)i(await Awr(c,n,e));let s=Mwr(t,o),a=BH(s);if(a.length>$qe)throw new Error(`The report summary came out ${Xo(a.length)}, over the ${Xo($qe)} set aside for it. Include fewer sources.`);r[sen]=a,o.unshift({id:Uqe,name:sen,bytes:a.length,included:!0});let l=XQt(r,{level:0});if(l.length>cen)throw new Error(Nwr(l.length,o));return{zip:l,zipName:`copilot-report-${t.bundleId}.zip`,uploadAttempt:{body:Rwr(l),idempotencyKey:zr()},issueDraft:{title:Ewr(t.note),body:s},attachments:o}}function Pwr(t,e){let n={id:Twr,name:kwr};if(!t||t.length===0)return{result:{...n,bytes:0,included:!1,note:"no screenshot was captured"}};if(t.length>e){let r=`screenshot is ${Xo(t.length)}, over the ${Xo(e)} left`;return{result:{...n,bytes:0,included:!1,note:r}}}return{result:{...n,bytes:t.length,included:!0},bytes:t}}async function Awr(t,e,n){let r=l=>({result:{id:t.id,name:t.name,bytes:0,included:!1,note:l}}),o=(l,c)=>r(`log is ${Xo(l)}, over the ${c}`),i=()=>r("newest entry alone is larger than the room left"),s=e-ten,a=l=>Nqe(l,s).text.replace(/^[^\n]*\n?/,"");if(t.path==null&&t.text==null)return r(len(t.unavailableReason??"not found"));try{let l=t.path!=null?await n.readLog(t.path,wbe):Nqe(t.text??"",wbe);if(l.totalBytes===0)return r("empty");if(l.totalBytes>wbe)return o(l.totalBytes,`${Xo(wbe)} a report can redact`);let c=LX(l.text),u=Dqe(c),d=u>e;if(d&&e<nen)return o(u,`${Xo(e)} left`);let f=d?a(c):c;if(d&&f.trim()==="")return i();let p=BH(d?ren(f,l.totalBytes):f),m=d?`truncated to the newest entries of ${Xo(l.totalBytes)}`:void 0;return{result:{id:t.id,name:t.name,bytes:p.length,included:!0,note:m},bytes:p}}catch(l){return l?.code==="ENOENT"?r("not found"):r(`failed: ${len(Dt(l))}`)}}function Ewr(t){let e=LX(t).split(`
`).map(n=>n.trim()).find(n=>n.length>0);return e?e.slice(0,80).trim():"Copilot issue report"}function Mwr(t,e){let n=e.filter(r=>r.id!==Uqe);return["## What went wrong","",Lwr(t.note),"","## Environment","",`- Plugin version: ${t.env.pluginVersion}`,`- Active backend: ${t.env.activeBackend}`,`- Platform: ${t.env.platform}`,...t.env.obsidianVersion?[`- Obsidian: ${t.env.obsidianVersion}`]:[],"","## Attached files","",...n.length>0?n.map(Owr):["- (none captured)"],"","> These files are bundled in the zip Copilot prepared for this report.",""].join(`
`)}function Owr({name:t,included:e,note:n}){return e?n?`- ${t} — ${n}`:`- ${t}`:`- ${t} — not included${n?`: ${n}`:""}`}function den(t,e,n){let r=`https://github.com/${Cwr}/issues/new?`,o=a=>r+new URLSearchParams({title:t,body:e+a,labels:"bug"}).toString();if(o(n).length<=DX)return o(n);if(o(Fqe).length>DX)throw new Error(`The GitHub issue link came out longer than the ${DX}-character limit on its own — nothing left to truncate.`);let i=n.length,s=o(n.slice(0,i)+Fqe);for(;i>0&&s.length>DX;)i=Math.max(0,i-Math.ceil((s.length-DX)/3)),s=o(n.slice(0,i)+Fqe);return s}function fen(t){return den(t.title,"",t.body)}function pen(t,e){return den(t.title,`**Copilot report ID:** \`${e}\`
`,t.body)}function Rwr(t){return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function Nwr(t,e){let n=`The report zip came out ${Xo(t)}, over GitHub's ${Xo(cen)} attachment limit. `,r=null;for(let o of e)!o.included||o.id===Uqe||(!r||o.bytes>r.bytes)&&(r=o);return r?`${n}The biggest one it can drop is ${r.name} at ${Xo(r.bytes)} uncompressed — uncheck that first, then anything else you can spare, and prepare the report again.`:`${n}Include fewer sources and prepare it again.`}function Lwr(t){let e=LX(t.trim());if(!e)return"_No description provided._";let{text:n,totalBytes:r}=Lqe(e,zqe);return r<=zqe?e:`${n}
_…description truncated: only the first ${Xo(Dqe(n))} of ${Xo(r)} was kept so the report stays under GitHub's upload limit._`}function len(t){let e=LX(t).replace(/\s+/g," ").trim(),{text:n,totalBytes:r}=Lqe(e,aen);return r>aen?`${n}…`:n}function Bqe(){let t=Te("fs/promises");return{readLog:async(e,n)=>{let r=await t.open(e,"r");try{return await oen(r,n)}finally{await r.close()}}}}var Cwr,kwr,sen,Twr,Uqe,Iwr,cen,zqe,$qe,aen,wbe,DX,Fqe,men=b(()=>{GF();lA();QQt();ed();een();tn();ien();Cwr="logancyang/obsidian-copilot",kwr="screenshot.png",sen="report.md",Twr="screenshot",Uqe="report",Iwr=24*1024*1024,cen=25*1024*1024,zqe=64*1024,$qe=zqe+8*1024,aen=1024,wbe=64*1024*1024;DX=1800,Fqe="\n\n_…report truncated. The full report is `report.md` inside the report zip._"});var Hb,jqe=b(()=>{Hb=class extends Error{constructor(e){super(e),this.name="ReportUploadError"}}});function Dwr(t,e,n){let r=t.XDG_DATA_HOME?.trim(),o=r||n(e,".local","share");return n(o,"opencode","log")}async function hen(t,e,n=$wr()){try{let r=Dwr(t,e,n.join),i=(await n.readdir(r)).filter(l=>l.endsWith(".log"));if(i.length===0)return null;let s=null,a=Number.NEGATIVE_INFINITY;for(let l of i){let c=n.join(r,l);try{let{mtimeMs:u}=await n.stat(c);u>a&&(a=u,s=c)}catch{}}return s}catch{return null}}function $wr(){let t=Te("fs/promises"),e=Te("path");return{join:(...n)=>e.join(...n),readdir:n=>t.readdir(n),stat:async n=>({mtimeMs:(await t.stat(n)).mtimeMs})}}var gen=b(()=>{tn()});async function yen(t){try{let n=require("electron")?.remote;if(!n)return null;let r=t.ownerDocument.defaultView;if(!r)return null;let o=Fwr(n,r);if(!o)return null;let i=t.getBoundingClientRect();if(i.width<=0||i.height<=0)return null;let s={x:Math.max(0,Math.floor(i.left)),y:Math.max(0,Math.floor(i.top)),width:Math.ceil(i.width),height:Math.ceil(i.height)},l=(await o.webContents.capturePage(s)).toPNG();return l.length>0?l:null}catch(e){return V("captureViewScreenshot failed:",e),null}}function Fwr(t,e){let n=t.getCurrentWindow?.()??null;if(e===window)return n;let r=t.BrowserWindow?.getAllWindows?.()??[];if(r.length===0)return n;if(r.length===1)return r[0];let o=null,i=Number.POSITIVE_INFINITY;for(let s of r)try{let a=s.getBounds(),l=Math.abs(a.x-e.screenX)+Math.abs(a.y-e.screenY)+Math.abs(a.width-e.outerWidth)+Math.abs(a.height-e.outerHeight);l<i&&(i=l,o=s)}catch{}return o??n}var wen=b(()=>{ge()});async function Bwr(t){let e=Date.now()+zwr,n=null;for(;Date.now()<e;){if(await new Promise(i=>t.win.setTimeout(i,Uwr)),Date.now()>=e||!t.isConnected)return!1;let r=t.getBoundingClientRect();if(r.width>0&&r.height>0&&n!==null&&r.left===n.left&&r.top===n.top&&r.width===n.width&&r.height===n.height)return!0;n=r}return!1}async function ven(t,e,n){let r=await e();if(!r)return null;let o=t.win===r.win;o?(n(),t.hide()):H("[ReportIssue] the pane is in another window; capturing without dismissing Settings");try{return await Bwr(r)?await yen(r):(V("[ReportIssue] the Agent Mode pane never settled; skipping the screenshot"),null)}finally{o&&t.show()}}var zwr,Uwr,ben=b(()=>{ge();wen();zwr=1200,Uwr=50});function xen(){let t=En.default.useRef(!0);return En.default.useEffect(()=>(t.current=!0,()=>{t.current=!1}),[]),t}function Sen(t){let{sources:e,prepare:n,discardReport:r}=t,[o,i]=En.default.useState("details"),[s,a]=En.default.useState(""),[l,c]=En.default.useState(()=>new Set(e.filter(w=>w.defaultChecked).map(w=>w.id))),[u,d]=En.default.useState(null),[f,p]=En.default.useState(null),m=xen(),h=async()=>{p(null),i("review");try{let w=await n(s,l);if(!m.current){r(w);return}d(w)}catch(w){if(!m.current)return;p(w instanceof Error?w.message:String(w)),i("details")}},g=()=>{u&&r(u),t.onCancel()};return En.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},o==="details"?En.default.createElement(jwr,{sources:e,note:s,onNoteChange:a,selected:l,onToggle:(w,y)=>c(v=>{let _=new Set(v);return y?_.add(w):_.delete(w),_}),error:f,onCancel:t.onCancel,onSubmit:()=>void h()}):En.default.createElement(Hwr,{report:u,upload:t.upload,onUploaded:t.onUploaded,openIssuePage:t.openIssuePage,revealFile:t.revealFil
`)}function rvr(t,e){let n=Te("os"),r=Te("path"),o=[],i=()=>{let x=Object.fromEntries(Is().filter(C=>C.skillsProjectDir).map(C=>[C.id,C.getInstallState(le())]));return o=pme(x,o),o},s=x=>wWt(x,C=>e.saveData(C)),a=Zc.initialize(t,Een(),{availableAgents:i,savePreferences:s,prepare:async x=>{await DBt({folder:x,fs:_Wt(t),settings:le(),availableAgents:i(),registeredAgents:Object.keys(Een())})}}),l=new Map,c=async x=>{await l.get(x)},u=new Eme(t,e,x=>pa[x],c),d=new Ame(t),f=Cse(t),p=r.join(dP(n.homedir()),"vaults",f,"agent-chat-index.json"),m=new Ome(Ajt(),p),h=null,g=SWt(x=>h?.getSessionByBackendId(x)??null,x=>h?.isReadOnlyFanoutSession(x)??!1),w=CWt(x=>h?.getSessionByBackendId(x)??null),y=new Ahe(t,e,{permissionPrompter:g,askUserQuestionPrompter:w,resolveDescriptor:x=>pa[x],modelPreloader:u,beforeBackendStart:c,persistenceManager:d,sessionIndex:m});h=y,a.subscribeToSkillSetChange(x=>{pa[x]?.restartOnManagedSkillsChange&&y.noteSpawnConfigChanged(x,"managed skills changed").catch(T=>W(`[Skills] Failed to refresh backend after skill change: ${x}`,T))});for(let x of Is()){if(!x.restartOnProviderConfigChange)continue;let C=x.id,T=I=>{y.noteSpawnConfigChanged(x.id,I).catch(M=>W(`[AgentMode] restart after ${I} failed: ${x.id}`,M))};e.modelManagement.providerRegistry.subscribe(I=>{let M=le(),O=M.providers[I],D=new Set(M.backends[C]?.enabledModels);O&&O.origin.kind!=="agent"&&M.configuredModels.some(F=>F.providerId===I&&D.has(F.configuredModelId))&&T("provider config changed")}),si((I,M)=>{Ren(I,C)!==Ren(M,C)&&T("model config changed")})}let v=new Map;for(let x of Is())x.restartOnSystemPromptChange&&v.set(x.id,Men(x.id));let _=()=>{for(let x of Is()){if(!x.restartOnSystemPromptChange)continue;let C=Men(x.id);C!==v.get(x.id)&&(v.set(x.id,C),y.noteSpawnConfigChanged(x.id,"system prompt changed").catch(T=>W(`[AgentMode] restart after system prompt change failed: ${x.id}`,T)))}};smt(_),si((x,C)=>{for(let T of Is())Oen(x,T.id)!==Oen(C,T.id)&&y.noteSpawnConfigChanged(T.id,"env overrides changed").catch(I=>W(`[AgentMode] restart after env overrides change failed: ${T.id}`,I))});let S=async()=>{await a.refresh(!0)};si((x,C)=>{for(let O of Is()){let D=Imt(x,C,O.id);if(D==="none")continue;(D==="immediate"?y.restartBackend(O.id,"managed agent env changed",{deferWhileBusy:!1}):y.noteSpawnConfigChanged(O.id,"managed agent env changed")).catch(q=>W(`[AgentMode] restart after managed env change failed: ${O.id}`,q))}let T=OC(x),I=OC(C),M=x.enableMiyoSearchSkill!==C.enableMiyoSearchSkill||x.docProcessorBackend!==C.docProcessorBackend||x.enableMiyo!==C.enableMiyo||x.miyoConnectionMode!==C.miyoConnectionMode||x.miyoServerUrl!==C.miyoServerUrl||x.isPaidUser!==C.isPaidUser;(T!==I||M||x.agentMode.skills.builtinPreferences!==C.agentMode.skills.builtinPreferences)&&S().then(()=>{if(M&&(_(),x.docProcessorBackend!==C.docProcessorBackend))for(let O of Is())O.restartOnSystemPromptChange||y.noteSpawnConfigChanged(O.id,"document processor changed").catch(D=>W(`[AgentMode] restart after doc processor change failed: ${O.id}`,D))}).catch(O=>W("[Skills] builtin skill re-seeding failed",O))});for(let x of Is())x.subscribeInstallState(e,()=>{l.has(x.id)||S().then(()=>y.onInstallStateChanged(x.id)).catch(C=>W(`[AgentMode] install-state refresh failed: ${x.id}`,C))});let k=S().catch(x=>{W("[Skills] Initial discovery pass failed",x)});for(let x of Is()){let C=Promise.resolve().then(()=>x.onPluginLoad?.(e)).catch(T=>W(`[AgentMode] backend ${x.id} onPluginLoad failed`,T)).then(()=>k).finally(()=>l.delete(x.id));l.set(x.id,C),Vqe()&&y.registerPreload(x.id,C.then(()=>{if(x.getInstallState(le()).kind==="ready")return y.preloadModels(x.id)}))}return y}var Nen,Xm=b(()=>{Nen=require("obsidian");ge();Ee();ia();uP();OG();tn();RG();Cz();zm();Cjt();kjt();Pjt();Ejt();nWt();oWt();wme();Tje();vWt();xWt();kWt();xt();xqe();AQt();pL();vqe();bqe();MQt();bme();Xde();LQt();kqe();AHe();Pen();zm();$Z();wme();Aen();jN()});function hS(){return le().enableSelfHostMode===!0&&zen("self_host")}function ovr(t){let e=le(),n=e.configuredModels.find(r=>r.configuredModelId===t);return n?e.providers[n.pr
`));let o=r.reduce((a,l)=>a+l.byteLength,0),i=new Uint8Array(o),s=0;for(let a of r)i.set(a,s),s+=a.byteLength;return{body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),contentType:`multipart/form-data; boundary=${e}`}}function Ven(t,e){let n=t.json;if(typeof n=="string")try{n=JSON.parse(n)}catch{}if(t.status<200||t.status>=300){let o=n?.detail;if(o?.reason){let i=new Error(o.reason);return o.error&&(i.name=o.error),{data:null,error:i,status:t.status,detail:o}}return{data:null,error:new Error(`HTTP error: ${t.status}`),status:t.status}}let r=n&&typeof n=="object"&&"entitlement"in n?{...n,entitlement:"[redacted]"}:n;return H(`[API ${e} request]:`,r),{data:n,status:t.status}}var $X,ua,Ov=b(()=>{xt();ZO();ge();Bl();Ee();u1();$X=require("obsidian");ua=class t{constructor(){this.pluginVersion="Unknown"}static getInstance(){return t.instance||(t.instance=new t),t.instance}checkLicenseKey(){if(!le().plusLicenseKey)throw new TI("Copilot Plus license key not found. Please enter your license key in the settings.")}setPluginVersion(e){this.pluginVersion=e}getPluginVersionHeaders(){return{"X-Client-Version":this.pluginVersion}}async makeRequest(e,n,r="POST",o=!1,i=!1){i||this.checkLicenseKey(),n.user_id=le().userId;let s=new URL(`${OO}${e}`);r==="GET"&&Object.entries(n).forEach(([c,u])=>{s.searchParams.append(c,u)});let a={"Content-Type":"application/json",...this.getPluginVersionHeaders()};o||(a.Authorization=`Bearer ${le().plusLicenseKey}`);let l=await(0,$X.requestUrl)({url:s.toString(),method:r,headers:a,...r==="POST"&&{body:JSON.stringify(n)},throw:!1});return Ven(l,e)}async makeFormDataRequest(e,n,r=!1){r||this.checkLicenseKey(),n.append("user_id",le().userId);let o=new URL(`${OO}${e}`);try{let{body:i,contentType:s}=await pvr(n),a=await(0,$X.requestUrl)({url:o.toString(),method:"POST",headers:{"Content-Type":s,Authorization:`Bearer ${le().plusLicenseKey}`,...this.getPluginVersionHeaders()},body:i,throw:!1});return Ven(a,`${e} form-data`)}catch(i){return{data:null,error:i instanceof Error?i:new Error(String(i)),status:0}}}async validateLicenseKey(e,n){let r=le().plusLicenseKey;if(!r)return{isValid:!1};let o={license_key:r};if(n&&typeof n=="object"){let c=Object.fromEntries(Object.entries(n).filter(([d,f])=>f!=null)),u=new Set(["license_key","user_id"]);for(let d of u)d in c&&delete c[d];Object.assign(o,c)}let{data:i,error:s,status:a,detail:l}=await this.makeRequest("/license",o,"POST",!0,!0);return le().plusLicenseKey!==r?{isValid:void 0}:s?a===403&&l?(Yqe(e),{isValid:!1}):{isValid:void 0}:(i?.entitlement?await Hen(i.entitlement)||Zqe():Zqe(),{isValid:!0,plan:i?.plan})}async rerank(e,n){let{data:r,error:o}=await this.makeRequest("/rerank",{query:e,documents:n,model:"rerank-2"});if(o)throw o;if(!r)throw new Error("No data returned from rerank");return r}async getUsage(){let e=le().plusLicenseKey;if(!e)return null;try{let n=await(0,$X.requestUrl)({url:`${bC}/usage`,method:"GET",headers:{Authorization:`Bearer ${e}`,...this.getPluginVersionHeaders()},throw:!1});return n.status!==200?(H(`[BrevilabsClient] usage read returned ${n.status}; no cap meters`),null):n.json}catch(n){return H("[BrevilabsClient] usage read failed; no cap meters",n),null}}async getModels(){try{let e=await(0,$X.requestUrl)({url:`${bC}/models`,method:"GET",headers:this.getPluginVersionHeaders(),throw:!1});return e.status!==200?(H(`[BrevilabsClient] models read returned ${e.status}`),null):e.json}catch(e){return H("[BrevilabsClient] models read failed",e),null}}async url4llm(e){let{data:n,error:r}=await this.makeRequest("/url4llm",{url:e});if(r)throw r;if(!n)throw new Error("No data returned from url4llm");return n}async pdf4llm(e){let n=vd(e),{data:r,error:o}=await this.makeRequest("/pdf4llm",{pdf:n});if(o)throw o;if(!r)throw new Error("No data returned from pdf4llm");return r}async docs4llm(e,n){let r=new FormData,o=this.getMimeTypeFromExtension(n),i=new Blob([e],{type:o}),s=`file.${n}`,a=new File([i],s,{type:o});r.append("files",a),r.append("file_type",n);let{data:l,error:c}=await this.makeFormDataRequest("/docs4llm",r);if(c)throw c;if(!l)throw new Err
`)}var dtn=b(()=>{});function ftn(t){return Array.isArray(t)?t:typeof t=="string"?t===""?[]:[{type:"text",text:t}]:t==null?[]:[t]}function zp(t,e){if(typeof t=="string")return t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(n=>jf(n))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e];if(Array.isArray(e)){let n=ftn(t);return SL(n,e)??[...n,...e]}else return e===""?t:Array.isArray(t)&&t.some(n=>jf(n))?[...t,{type:"file",source_type:"text",text:e}]:[...ftn(t),{type:"text",text:e}]}function a5e(t,e){return t==="error"||e==="error"?"error":"success"}function Lvr(t,e){function n(r,o){if(typeof r!="object"||r===null||r===void 0)return r;if(o>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(s=>n(s,o+1));let i={};for(let s of Object.keys(r))i[s]=n(r[s],o+1);return i}return JSON.stringify(n(t,0),null,2)}function Ha(t,e,n){let r=n?.ignoreKeys??ytn;if(t==null&&e==null)return;if(t==null||e==null)return t??e;let o={...t};for(let[i,s]of Object.entries(e))if(o[i]==null)o[i]=s;else{if(s==null)continue;if(typeof o[i]!=typeof s||Array.isArray(o[i])!==Array.isArray(s))throw new Error(`field[${i}] already exists in the message chunk, but with a different type.`);if(typeof o[i]=="string"){if(i==="type")continue;if(["id","name","output_version","model_provider"].includes(i))s&&(o[i]=s);else{if(r.includes(i))continue;o[i]+=s}}else if(typeof o[i]=="number"){if(r.includes(i))continue;o[i]=o[i]+s}else if(typeof o[i]=="object"&&!Array.isArray(o[i]))o[i]=Ha(o[i],s,n);else if(Array.isArray(o[i]))o[i]=SL(o[i],s,n);else{if(o[i]===s)continue;console.warn(`field[${i}] already exists in this message chunk and value has unsupported type.`)}}return o}function Dvr(t){return typeof t=="number"||typeof t=="string"}function ptn(t){return typeof t!="object"||t===null||!("index"in t)?!1:Dvr(t.index)}function mtn(t){if(typeof t!="object"||t===null||!("id"in t))return!1;let e=t.id;return e!=null&&e!==""}function htn(t){return t.endsWith("_delta")?t.slice(0,-6):t}function $vr(t,e){return typeof t!="object"||t===null||typeof e!="object"||e===null||!("type"in t)||!("type"in e)?!1:typeof t.type=="string"&&typeof e.type=="string"&&htn(t.type)!==htn(e.type)}function Fvr(t,e){let n=ptn(e),r=mtn(e);return!n&&!r?-1:t.findIndex(o=>{let i=ptn(o),s=mtn(o);return n&&i?o.index!==e.index||$vr(o,e)?!1:s&&r?o.id===e.id:!0:!n&&!i&&r&&s?o.id===e.id:!1})}function SL(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{let r=[...t];for(let o of e){let i=Fvr(r,o);if(i!==-1)r[i]=Ha(r[i],o,n);else{if(typeof o=="object"&&o!==null&&"text"in o&&o.text==="")continue;r.push(o)}}return r}}}function l5e(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
Left ${typeof t}
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return SL(t,e,n);if(typeof t=="object"&&typeof e=="object")return Ha(t,e,n);if(t===e)return t;throw new Error(`Can not merge objects of different types.
`)&&(r=r.substring(1));let o=r.indexOf("```"),i=r;return o!==-1&&(i=r.substring(0,o)),e(i.trim())}function Wvr(t){try{return JSON.parse(t)}catch{}let e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let n=0;function r(){for(;n<e.length&&/\s/.test(e[n]);)n+=1}function o(){if(e[n]!=='"')throw new Error(`Expected '"' at position ${n}, got '${e[n]}'`);n+=1;let u="",d=!1;for(;n<e.length;){let f=e[n];if(d){if(f==="n")u+=`
`;else if(f==="t")u+=" ";else if(f==="r")u+="\r";else if(f==="\\")u+="\\";else if(f==='"')u+='"';else if(f==="b")u+="\b";else if(f==="f")u+="\f";else if(f==="/")u+="/";else if(f==="u"){let p=e.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?u+=String.fromCharCode(Number.parseInt(p,16)):u+=`u${p}`,n+=p.length;else throw new Error(`Invalid unicode escape sequence '\\u${p}' at position ${n}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${n}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return n+=1,u;u+=f}n+=1}return d&&(u+="\\"),u}function i(){let u=n,d="";if(e[n]==="-"&&(d+="-",n+=1),n<e.length&&e[n]==="0"&&(d+="0",n+=1,e[n]>="0"&&e[n]<="9"))throw new Error(`Invalid number at position ${u}`);if(n<e.length&&e[n]>="1"&&e[n]<="9")for(;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&e[n]===".")for(d+=".",n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&(e[n]==="e"||e[n]==="E"))for(d+=e[n],n+=1,n<e.length&&(e[n]==="+"||e[n]==="-")&&(d+=e[n],n+=1);n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(d==="-")return-0;let f=Number.parseFloat(d);if(Number.isNaN(f))throw n=u,new Error(`Invalid number '${d}' at position ${u}`);return f}function s(){if(r(),n>=e.length)throw new Error(`Unexpected end of input at position ${n}`);let u=e[n];if(u==="{")return l();if(u==="[")return a();if(u==='"')return o();if("null".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),null;if("true".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),!0;if("false".startsWith(e.substring(n,n+5)))return n+=Math.min(5,e.length-n),!1;if(u==="-"||u>="0"&&u<="9")return i();throw new Error(`Unexpected character '${u}' at position ${n}`)}function a(){if(e[n]!=="[")throw new Error(`Expected '[' at position ${n}, got '${e[n]}'`);let u=[];if(n+=1,r(),n>=e.length)return u;if(e[n]==="]")return n+=1,u;for(;n<e.length;){if(r(),n>=e.length||(u.push(s()),r(),n>=e.length))return u;if(e[n]==="]")return n+=1,u;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or ']' at position ${n}, got '${e[n]}'`)}return u}function l(){if(e[n]!=="{")throw new Error(`Expected '{' at position ${n}, got '${e[n]}'`);let u={};if(n+=1,r(),n>=e.length)return u;if(e[n]==="}")return n+=1,u;for(;n<e.length;){if(r(),n>=e.length)return u;let d=o();if(r(),n>=e.length)return u;if(e[n]!==":")throw new Error(`Expected ':' at position ${n}, got '${e[n]}'`);if(n+=1,r(),n>=e.length||(u[d]=s(),r(),n>=e.length))return u;if(e[n]==="}")return n+=1,u;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or '}' at position ${n}, got '${e[n]}'`)}return u}let c=s();if(r(),n<e.length)throw new Error(`Unexpected character '${e[n]}' at position ${n}`);return c}function CL(t){try{return typeof t>"u"?null:Wvr(t)}catch{return null}}var GH=b(()=>{});var Vf,$E,HX=b(()=>{Wf();Vf=class nnn extends Ml{constructor(n,r){(typeof n=="string"||Array.isArray(n))&&(n={content:n,role:r});super(n);A(this,"type","generic");A(this,"role");this.role=n.role}static lc_name(){return"ChatMessage"}static _chatMessageClass(){return nnn}static isInstance(n){return super.isInstance(n)&&n.type==="generic"}static[Symbol.hasInstance](n){return this.isInstance(n)}get _printableFields(){return{...super._printableFields,role:this.role}}},$E=class extends th{constructor(e,n){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:n});super(e);A(this,"type","generic");A(this,"role");this.role=e.role}static lc_name(){return"ChatMessageChunk"}concat(e){let n=this.constructor;return new n({content:zp(this.content,e.content),additional_kwargs:Ha(this.additional_kwargs,e.additional_kwargs),response_metadata:Ha(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}static[Symbol.hasInstance](e){return this.isInstance(e)}get _printableFields(){return{...super._printableFields,role:this.role}}}});var FE,Obe=b(()=>{Wf();FE=class extends th{constructor(){super(...arguments);A(this,"type","function")}static lc_name(){return"FunctionMessageChunk"}concat(e){let n=this.con
- "owner/prompt-name:commit-hash" (with owner and commit)`}function k_e(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}function Zon(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithConflictError"}async function Jt(t,e,n){let r;if(t.ok){n&&(r=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let a=new Error(`${t.status} ${t.statusText}`);throw a.status=t?.status,a}if(r===void 0)try{r=await t.text()}catch{r=""}let o=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${r}`;if(t.status===404)throw new _Ge(o);if(t.status===409)throw new bGe(o);let i=new Error(o);throw i.status=t.status,i}function Jon(t){return typeof t=="object"&&t!==null&&t.code===Yon}var bGe,_Ge,Yon,S_e,T_e=b(()=>{bGe=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},_Ge=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};Yon="ERR_CONFLICTING_ENDPOINTS",S_e=class extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Yon}),this.name="ConflictingEndpointsError"}}});function Gf(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(C_e(t));let[e,n]=t.split(":"),r=n||"latest";if(e.includes("/")){let[o,i]=e.split("/",2);if(!o||!i)throw new Error(C_e(t));return[o,i,r]}else{if(!e)throw new Error(C_e(t));return["-",e,r]}}var Xon=b(()=>{T_e()});function exr(t){return new Promise(e=>setTimeout(e,t))}function txr(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}function ein(t){try{return EL(Kb.join(t,Qon)).split(`
`)}catch{return}}function nxr(t){let e=ein(t);if(e&&e[0]&&e[0].trim()){let n=Date.parse(e[0].trim());if(!Number.isNaN(n))return n}return void 0}function rxr(t){let e=ein(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}async function oxr(t){let e=nxr(t);return e===void 0||Date.now()-e<=Q_r?!1:(await Ybe(t),!0)}async function tin(t,e){let n=`${t}.oauth.lock.lock`,r=Kb.dirname(n);r&&await Zbe(r);let o=globalThis.crypto.randomUUID();for(;;){try{await $rn(n)}catch(i){if(!txr(i))throw i;if(!await oxr(n)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await exr(Math.min(X_r,Math.max(0,e-Date.now())))}continue}try{await iW(Kb.join(n,Qon),`${new Date().toISOString()}
Context: ${e}`:""}`),P_e("[Unserializable]");Os("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
`,TGe=class{constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(this.worker!==null)return!0;if(this.startPromise!==null)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){if(!!1||null===null)return this.disabled=!0,!1;try{let e=new null(Ixr,{eval:!0});return e.on("message",n=>{let r=this.pending.get(n.id);r&&(this.pending.delete(n.id),n.error?r.reject(new Error(n.error)):n.bytes&&typeof n.length=="number"?r.resolve(new Uint8Array(n.bytes,0,n.length)):r.reject(new Error("worker returned malformed message")))}),e.on("error",n=>{for(let[,r]of this.pending)r.reject(n);this.pending.clear(),this.disabled=!0,this.worker=null}),e.on("exit",n=>{for(let[,r]of this.pending)r.reject(new Error(`worker exited with code ${n}`));this.pending.clear(),this.worker=null}),e.unref(),this.worker=e,!0}catch{return this.disabled=!0,!1}}async serialize(e){if(!await this.ensureStarted())return null;let r=this.nextId++;return new Promise((o,i)=>{this.pending.set(r,{resolve:o,reject:i});try{this.worker.postMessage({id:r,op:"serialize",payload:e})}catch(s){this.pending.delete(r),i(s)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(let[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}},kGe=null;Pxr=64*1024,Axr=2048});function Exr(t,e){let[n]=Gf(t);if(n!=="-"&&!e)throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}function vin(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}function vW(t){return{...t,start_time:vin(t.start_time),end_time:vin(t.end_time)}}function bin(t,e,n){if(n)return t;let r=t_e(),o=e??dKe(),i=t.extra??{},s=i.metadata;return t.extra={...i,runtime:{...r,...i?.runtime},metadata:{...o,...o.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??o.revision_id}:{},...s}},t}async function Rxr(t){let e=[];for await(let n of t)e.push(n);return e}function E_e(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function _in(t){return typeof t=="number"?Number(t.toFixed(4)):t}function Lxr(t,e){if(!t)return;let n=c=>c.split(".").map(u=>parseInt(u,10)),[r,o,i]=n(t),[s,a,l]=n(e);if(isNaN(r)||isNaN(o)||isNaN(i)||isNaN(s)||isNaN(a)||isNaN(l)){console.warn(`[LANGSMITH]: Could not parse backend version ${JSON.stringify(t)} for compatibility check.`);return}(r<s||r===s&&o<a||r===s&&o===a&&i<l)&&console.warn(`[LANGSMITH]: Backend version ${JSON.stringify(t)} is older than the minimum version required by this SDK (${JSON.stringify(e)}). Some features may not work as expected. See https://docs.langchain.com/langsmith/smithdb-sdk-migration`)}function Tin(t,e){new Headers({[t]:e})}function xin(t){for(let[e,n]of Object.entries(t??{}))Tin(e,n)}function Sin(t){if(!t)return{};let e=t instanceof Headers?[...t.entries()]:Array.isArray(t)?t.map(([o,i])=>[o,i]):Object.entries(t),n={},r=new Map;for(let[o,i]of e){Tin(o,i);let s=o.toLowerCase(),a=r.get(s);a===void 0?(r.set(s,o),n[o]=i):n[a]=i}return n}function zxr(t,e,n){let r={...t},o=new Map(Object.keys(r).map(i=>[i.toLowerCase(),i]));for(let[i,s]of Object.entries(e)){let a=i.toLowerCase();r[o.get(a)??i]=s}for(let i of Object.keys(r))n.has(i.toLowerCase())&&delete r[i];return r}function Cin(t){return"dataset_id"in t||"dataset_name"in t}var Mxr,Oxr,Nxr,Dxr,kin,$xr,Fxr,IGe,V
=== LangSmith Server Configuration ===
`+JSON.stringify(n,null,2)+`
`),n}_checkStainlessVersion(e){this._stainlessVersionsChecked.has(e)||(this._stainlessVersionsChecked.add(e),this._ensureServerInfo().then(n=>{Lxr(n?.version,e)}).catch(()=>{}))}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _supportsSDBQuery(){return(await this._ensureServerInfo()).instance_flags?.sdb_query_enabled===!0}async _checkFeedbackSessionId(){let e="https://docs.langchain.com/langsmith/smithdb-sdk-migration#feedback-create",n=await this._ensureServerInfo();if(Kon(n.instance_flags)===uQ.SMITHDB_ONLY)throw new Error(`sessionId must be provided when creating feedback for a run: this deployment cannot locate the run without it. See ${e}`);ju(`Creating feedback for a run without sessionId is deprecated and will stop working in a future release. See ${e}`)}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n})}_cloneCurrentOTELContext(){let e=r_e(),n=Hrn();if(this.langSmithToOTELTranslator!==void 0){let r=e.getActiveSpan();if(r)return e.setSpan(n.active(),r)}}async createRun(e,n){if(!this._filterForSampling([e]).length)return;let r={...this._mergedHeaders,"Content-Type":"application/json"},o=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:o,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:l,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}let s=await this._mergeRuntimeEnvAndMaskMetadata(i);n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(r["x-tenant-id"]=n.workspaceId);let a=Zf(s,`Creating run with id: ${s.id}`);await this.caller.call(async()=>{let l=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Jt(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let o=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),i=await Promise.all(n?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(o.length>0&&i.length>0){let l=o.reduce((u,d)=>(d.id&&(u[d.id]=d),u),{}),c=[];for(let u of i)u.id!==void 0&&l[u.id]?l[u.id]={...l[u.id],...u}:c.push(u);o=Object.values(l),i=c}let s={post:o,patch:i};if(!s.post.length&&!s.patch.length)return;let a={post:[],patch:[]};for(let l of["post","patch"]){let c=l,u=s[c].reverse(),d=u.pop();for(;d!==void 0;)a[c].push(d),d=u.pop()}if(a.post.length>0||a.patch.length>0){let l=a.post.map(c=>c.id).concat(a.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(a,`Ingesting runs with ids: ${l}`),r)}}async _postBatchIngestRuns(e,n){let r={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(r["x-tenant-id"]=n.workspaceId),await this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await Jt(o,"batch create run",!0),o})}async multipartIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let o={},i=[];for(let d of e??[]){let f=aw
`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,n){let r=new TextEncoder;return new ReadableStream({async start(i){let s=async a=>{typeof a=="string"?i.enqueue(r.encode(a)):i.enqueue(a)};for(let a of e){await s(`--${n}\r
`),i.close()}})}async _sendMultipartRequest(e,n,r){let o="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=()=>this._createNodeFetchBody(e,o),s=()=>this._createMultipartStream(e,o),a=async l=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let c=await l(),u={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${o}`};r?.apiKey!==void 0&&(u["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(u["x-tenant-id"]=r.workspaceId);let d=c;r?.useGzip&&typeof c=="object"&&"pipeThrough"in c&&(d=c.pipeThrough(new CompressionStream("gzip")),u["Content-Encoding"]="gzip");let f=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:u,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Jt(f,"Failed to send multipart request",!0),f});try{let l,c=!1;grn()&&!this.multipartStreamingDisabled&&oQ()!=="bun"?(c=!0,l=await a(s)):l=await a(i),(!this.multipartStreamingDisabled||c)&&l.status===422&&(r?.apiUrl??this.apiUrl)!==I_e&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,l=await a(i))}catch(l){if(k_e(l))throw l;if(console.warn(`${l.message.trim()}
Context: ${n}`),this.failedTracesDir){let c=await this._createNodeFetchBody(e,o).catch(()=>null);c&&await t._writeTraceToFallbackDir(this.failedTracesDir,c,{"Content-Type":`multipart/form-data; boundary=${o}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,n,r){hr(e),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs)),n.error&&(n.error=await this.processError(n.error)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events&&(n.events=this._filterNewTokenEvents(n.events));let o={...n,id:e};if(!this._filterForSampling([o],!0).length)return;if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){let a=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&o.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:o,otelContext:a,apiKey:r?.apiKey,apiUrl:r?.apiUrl,workspaceId:r?.workspaceId}).catch(console.error);return}else this.processRunOperation({action:"update",item:o,otelContext:a,apiKey:r?.apiKey,apiUrl:r?.apiUrl,workspaceId:r?.workspaceId}).catch(console.error);return}let i={...this._mergedHeaders,"Content-Type":"application/json"};r?.apiKey!==void 0&&(i["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(i["x-tenant-id"]=r.workspaceId);let s=Zf(n,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let a=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Jt(a,"update run",!0),a})}async readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){return ju("readRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-retrieve for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN"}),this._readRun(e,{loadChildRuns:n})}async _readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){hr(e);let r=vW(await this._get(`/runs/${e}`));return n&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:n,projectOpts:r}){if(ju("getRunUrl() is deprecated and will be removed after Jan 31, 2027. Use client.runs.getURL() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-get-url for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_GET_RUN_URL"}),n!==void 0){let o;n.session_id?o=n.session_id:r?.projectName?o=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?o=r?.projectId:o=(await this.readProject({projectName:Os("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${n.id}?poll=true`}else if(e!==void 0){let o=await this._readRun(e);if(!o.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${o.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let n=await Rxr(this._listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},o={};n.sort((i,s)=>(i?.dotted_order??"").localeCompare(s?.dotted_order??""));for(let i of n){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in r||(r[i.parent_run_id]=[]),r[i.parent_run_id].push(i),o[i.id]=i)}e.child_runs=r[e.id]||[];for(let i in r)i!==e.id&&(o[i].child_runs=r[i]);return e}async*listRuns(e){ju("listRuns() is deprecated and will be removed after Jan 31, 2027. Use client.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_RUNS"}),yield*this._listRuns(e)}async*_listRuns(e){let{projectId:n,projectName:r,parentRunId:o,traceId:i,referenceExampleId:s,startTime:a,executionOrder:l,isRoot:c,runType:u,error:d,id:f,query:p,filter:m,traceFilt
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return s.map(a=>({...a,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:n=null,metadata:r=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:s=null,numExamples:a=null,numRepetitions:l=null,evaluatorKeys:c=null,tagValueIds:u=null}){let d=o?"?upsert=true":"",f=`${this.apiUrl}/sessions${d}`,p=i||{};r&&(p.metadata=r);let m={name:e,extra:p,description:n};s!==null&&(m.reference_dataset_id=s),a!=null&&(m.num_examples=a),l!=null&&(m.num_repetitions=l),c!=null&&c.length>0&&(m.evaluator_keys=c),u!==null&&(m.tag_value_ids=u);let h=JSON.stringify(m);return await(await this.caller.call(async()=>{let y=await this._fetch(f,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:h});return await Jt(y,"create project"),y})).json()}async updateProject(e,{name:n=null,description:r=null,metadata:o=null,projectExtra:i=null,endTime:s=null}){let a=`${this.apiUrl}/sessions/${e}`,l=i;o&&(l={...l||{},metadata:o});let c=JSON.stringify({name:n,extra:l,description:r,end_time:s?new Date(s).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(a,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await Jt(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:n}){let r="/sessions",o=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)hr(e),r+=`/${e}`;else if(n!==void 0)o.append("name",n);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${r}?${o}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Jt(s,"has project"),s});try{let s=await i.json();return i.ok?Array.isArray(s)?s.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:n,includeStats:r}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)hr(e),o+=`/${e}`;else if(n!==void 0)i.append("name",n);else throw new Error("Must provide projectName or projectId");r!==void 0&&i.append("include_stats",r.toString());let s=await this._get(o,i),a;if(Array.isArray(s)){if(s.length===0)throw new Error(`Project[id=${e}, name=${n}] not found`);a=s[0]}else a=s;return a}async getProjectUrl({projectId:e,projectName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");let r=await this.readProject({projectId:e,projectName:n}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");let r=await this.readDataset({datasetId:e,datasetName:n}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let n of this._getPaginated("/sessions",e))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:n,nameContains:r,referenceDatasetId:o,referenceDatasetName:i,includeStats:s,datasetVersion:a,referenceFree:l,metadata:c}={}){let u=new URLSearchParams;if(e!==void 0)for(let d of e)u.append("id",d);if(n!==void 0&&u.append("name",n),r!==void 0&&u.append("name_contains",r),o!==void 0)u.append("reference_dataset",o);else if(i!==void 0){let d=await this.readDataset({datasetName:i});u.append("reference_dataset",d.id)}s!==void 0&&u.append("include_stats",s.toString()),a!==void 0&&u.append("dataset_version",a),l!==void 0&&u.append("reference_free",l.toString())
`).map(a=>JSON.parse(a))}async*listDatasets({limit:e=100,offset:n=0,datasetIds:r,datasetName:o,datasetNameContains:i,metadata:s}={}){let a="/datasets",l=new URLSearchParams({limit:e.toString(),offset:n.toString()});if(r!==void 0)for(let c of r)l.append("id",c);o!==void 0&&l.append("name",o),i!==void 0&&l.append("name_contains",i),s!==void 0&&l.append("metadata",JSON.stringify(s));for await(let c of this._getPaginated(a,l))yield*c}async updateDataset(e){let{datasetId:n,datasetName:r,...o}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");let i=n??(await this.readDataset({datasetName:r})).id;hr(i);let s=JSON.stringify(o);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Jt(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:n,datasetName:r,asOf:o,tag:i}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");let s=n??(await this.readDataset({datasetName:r})).id;hr(s);let a=JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Jt(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:n}){let r="/datasets",o=e;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(o=(await this.readDataset({datasetName:n})).id),o!==void 0)hr(o),r+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Jt(i,`delete ${r}`,!0),i})}async createExample(e,n,r){if(Cin(e)&&(n!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let o=n?r?.datasetId:e.dataset_id,i=n?r?.datasetName:e.dataset_name;if(o===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:i})).id);let s=(n?r?.createdAt:e.created_at)||new Date,a;Cin(e)?a=e:a={inputs:e,outputs:n,created_at:s?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};let l=await this._uploadExamplesMultipart(o,[a]);return await this.readExample(l.example_ids?.[0]??PL())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let y=e,v=y[0].dataset_id,_=y[0].dataset_name;if(v===void 0&&_===void 0)throw new Error("Must provide either datasetName or datasetId");if(v!==void 0&&_!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");v===void 0&&(v=(await this.readDataset({datasetName:_})).id);let S=await this._uploadExamplesMultipart(v,y);return await Promise.all(S.example_ids.map(x=>this.readExample(x)))}let{inputs:n,outputs:r,metadata:o,splits:i,sourceRunIds:s,useSourceRunIOs:a,useSourceRunAttachments:l,attachments:c,exampleIds:u,datasetId:d,datasetName:f}=e;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d,m=f;if(p===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:m})).id);let h=n.map((y,v)=>({dataset_id:p,inputs:y,outputs:r?.[v],metadata:o?.[v],split:i?.[v],id:u?.[v],attachments:c?.[v],source_run_id:s?.[v],use_source_
Current tenant: ${r.tenant_handle}
Requested tenant: ${n}`)}async _getLatestCommitHash(e){let r=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Jt(o,"get latest commit hash"),o})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _createCommitTags(e,n,r){let o=typeof r=="string"?[r]:r;await Promise.all(o.map(async i=>this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${e}/tags`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify({tag_name:i,commit_id:n})});return await Jt(s,"create commit tag"),s})))}async _likeOrUnlikePrompt(e,n){let[r,o,i]=Gf(e),s=JSON.stringify({like:n});return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/likes/${r}/${o}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Jt(l,`${n?"like":"unlike"} prompt`),l})).json()}async _getPromptUrl(e){let[n,r,o]=Gf(e);if(await this._currentTenantIsOwner(n)){let i=await this._getSettings();return o!=="latest"?`${this.getHostUrl()}/prompts/${r}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${i.id}`}else return o!=="latest"?`${this.getHostUrl()}/hub/${n}/${r}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){let[n,r,o]=Gf(e);for await(let i of this._getPaginated(`/commits/${n}/${r}/`,new URLSearchParams,s=>s.commits))yield*i}async*listPrompts(e){let n=new URLSearchParams;n.append("sort_field",e?.sortField??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&n.append("is_public",e.isPublic.toString()),e?.query&&n.append("query",e.query);for await(let r of this._getPaginated("/repos",n,o=>o.repos))yield*r}async getPrompt(e){let[n,r,o]=Gf(e),s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return a?.status===404?null:(await Jt(a,"get prompt"),a)}))?.json();return s?.repo?s.repo:null}async createPrompt(e,n){let r=await this._getSettings();if(n?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
creating a LangChain Hub handle.
You can add a handle by creating a public prompt at:
https://smith.langchain.com/prompts`);let[o,i,s]=Gf(e);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("create a prompt",o);let a={repo_handle:i,...n?.description&&{description:n.description},...n?.readme&&{readme:n.readme},...n?.tags&&{tags:n.tags},is_public:!!n?.isPublic},l=JSON.stringify(a),c=await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Jt(d,"create prompt"),d}),{repo:u}=await c.json();return u}async createCommit(e,n,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[o,i,s]=Gf(e),a=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${o}/${i}`):r?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(n)),parent_commit:a,...r?.description!==void 0&&{description:r.description}},c=JSON.stringify(l),d=await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await Jt(p,"create commit"),p})).json(),f=d.commit??d;return r?.tags&&await this._createCommitTags(`${o}/${i}`,f.id,r.tags),this._getPromptUrl(`${o}/${i}${f.commit_hash?`:${f.commit_hash}`:""}`)}async updateExamplesMultipart(e,n=[]){return this._updateExamplesMultipart(e,n)}async _updateExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let s of n){let a=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=Zf(l,`Serializing body for example with id: ${a}`),u=new Blob([c],{type:"application/json"});if(r.append(a,u),s.inputs){let d=Zf(s.inputs,`Serializing inputs for example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.inputs`,f)}if(s.outputs){let d=Zf(s.outputs,`Serializing outputs whle updating example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.outputs`,f)}if(s.attachments)for(let[d,f]of Object.entries(s.attachments)){let p,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);let h=new Blob([m],{type:`${p}; length=${m.byteLength}`});r.append(`${a}.attachment.${d}`,h)}if(s.attachments_operations){let d=Zf(s.attachments_operations,`Serializing attachments while updating example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.attachments_operations`,f)}}let o=e??n[0]?.dataset_id;return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${o}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await Jt(s,"update examples"),s})).json()}async uploadExamplesMultipart(e,n=[]){return this._uploadExamplesMultipart(e,n)}async _uploadExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let i of n){let s=(i.id??PL()).toString(),a={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},l=Zf(a,`Serializing body for uploaded example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(r.append(s,c),i.inputs){let u=Zf(i.inputs,`Serializing inputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});r.append(`${s}.inputs`,d)}if(i.outputs){let u
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,n){e.child_runs.push(n)}_addRunToRunMap(e){let{dottedOrder:n,microsecondPrecisionDatestring:r}=EGe(new Date(e.start_time).getTime(),e.id,e.execution_order),o={...e},i=this.getRunById(o.parent_run_id);if(o.parent_run_id!==void 0?i?(this._addChildRun(i,o),i.child_execution_order=Math.max(i.child_execution_order,o.child_execution_order),o.trace_id=i.trace_id,i.dotted_order!==void 0&&(o.dotted_order=[i.dotted_order,n].join("."),o._serialized_start_time=r)):o.parent_run_id=void 0:(o.trace_id=o.id,o.dotted_order=n,o._serialized_start_time=r),this.usesRunTreeMap){let s=OGe(o,i);s!==void 0&&this.runTreeMap.set(o.id,s)}else this.runMap.set(o.id,o);return o}async _endTrace(e){let n=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);n?n.child_execution_order=Math.max(n.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let n=e!==void 0&&this.getRunById(e);return n?n.child_execution_order+1:1}_createRunForLLMStart(e,n,r,o,i,s,a,l){let c=this._getExecutionOrder(o),u=Date.now(),d=a?{...i,metadata:a}:i,f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:n},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForLLMStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,n,r,o,i,s,a,l){let c=this._getExecutionOrder(o),u=Date.now(),d=a?{...i,metadata:a}:i,f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:n},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForChatModelStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,n,r,o,i){let s=this.getRunById(n);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=e,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(e,n,r,o,i){let s=this.getRunById(n);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(e,n,r,o,i,s,a,l,c){let u=this._getExecutionOrder(o),d=Date.now(),f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:n,execution_order:u,child_execution_order:u,run_type:a??"chain",child_runs:[],extra:s?{...c,metadata:s}:{...c},tags:i||[]};return this._addRunToRunMap(f)}async handleChainStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForChainStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,n,r,o,i){let s=this.getRunById(n);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=MGe(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=MGe(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,n,r,o,i){let s=this.getRunById(n);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=MGe(i.inputs,"input")),await this.onChainError?.(s),await
`)}var ySr,nsn,W_e=b(()=>{ySr=Object.prototype.hasOwnProperty;nsn=class extends Error{constructor(e,n,r,o,i){super(esn(e,{name:n,index:r,operation:o,tree:i}));A(this,"name");A(this,"index");A(this,"operation");A(this,"tree");this.name=n,this.index=r,this.operation=o,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=esn(e,{name:n,index:r,operation:o,tree:i})}}});function hQ(t,e){if(e=="")return t;var n={op:"_get",path:e};return tM(t,n),n.value}function tM(t,e,n=!1,r=!0,o=!0,i=0){if(n&&(typeof n=="function"?n(e,0,t,e.path):gQ(e,0)),e.path===""){let s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=hQ(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=CW(t,e.value),s.test===!1)throw new pl("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(n)throw new pl("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{r||(t=Eg(t));let s=(e.path||"").split("/"),a=t,l=1,c=s.length,u,d,f;for(typeof n=="function"?f=n:f=gQ;;){if(d=s[l],d&&d.indexOf("~")!=-1&&(d=tsn(d)),o&&(d=="__proto__"||d=="prototype"&&l>0&&s[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&u===void 0&&(a[d]===void 0?u=s.slice(0,l).join("/"):l==c-1&&(u=e.path),u!==void 0&&f(e,0,t,u)),l++,Array.isArray(a)){if(d==="-")d=a.length;else{if(n&&!H_e(d))throw new pl("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);H_e(d)&&(d=~~d)}if(l>=c){if(n&&e.op==="add"&&d>a.length)throw new pl("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let p=vSr[e.op].call(e,a,d,t);if(p.test===!1)throw new pl("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}}else if(l>=c){let p=SW[e.op].call(e,a,d,t);if(p.test===!1)throw new pl("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}if(a=a[d],n&&l<c&&(!a||typeof a!="object"))throw new pl("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function nM(t,e,n,r=!0,o=!0){if(n&&!Array.isArray(e))throw new pl("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=Eg(t));let i=new Array(e.length);for(let s=0,a=e.length;s<a;s++)i[s]=tM(t,e[s],n,!0,o,s),t=i[s].newDocument;return i.newDocument=t,i}function osn(t,e,n){let r=tM(t,e);if(r.test===!1)throw new pl("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function gQ(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new pl("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(SW[t.op]){if(typeof t.path!="string")throw new pl("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new pl('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new pl("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new pl("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&U_e(t.value))throw new pl("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,i=
`}}let u={};for(let m of e){let h=m.source.split(":"),g=m.target.split(":"),w=h.filter((y,v)=>y===g[v]).join(":");u[w]||(u[w]=[]),u[w].push(m)}let d=new Set;function f(m){return[...m].sort((h,g)=>h.split(":").length-g.split(":").length)}function p(m,h){let g=m.length===1&&m[0].source===m[0].target;if(h&&!g){let y=h.split(":").pop();if(d.has(h))throw new Error(`Found duplicate subgraph '${y}' at '${h} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(h),c+=` subgraph ${y}
`}let w=f(Object.keys(u).filter(y=>y.startsWith(`${h}:`)&&y!==h&&y.split(":").length===h.split(":").length+1));for(let y of w)p(u[y],y);for(let y of m){let{source:v,target:_,data:S,conditional:k}=y,x="";if(S!==void 0){let C=S,T=C.split(" ");T.length>l&&(C=Array.from({length:Math.ceil(T.length/l)},(I,M)=>T.slice(M*l,(M+1)*l).join(" ")).join(" <br> ")),x=k?` -. ${C} .-> `:` -- ${C} --> `}else x=k?" -.-> ":" --> ";c+=` ${l9e(v)}${x}${l9e(_)};
`}h&&!g&&(c+=` end
`)}p(u[""]??[],"");for(let m in u)!m.includes(":")&&m!==""&&p(u[m],m);return s&&(c+=USr(i??{})),c}async function Asn(t,e){let n=e?.backgroundColor??"white",r=e?.imageType??"png",o=Csn(t);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));let i=`https://mermaid.ink/img/${o}?bgColor=${n}&type=${r}`,s=await fetch(i);if(!s.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${s.status}`,`Status text: ${s.statusText}`].join(`
`));return await s.blob()}var zSr,Esn=b(()=>{G_e();zSr=["*","_","`"]});var u9e,c9e,d9e,Z_e=b(()=>{u9e=Symbol("Let zodToJsonSchema decide on which parser to use"),c9e={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},d9e=t=>typeof t=="string"?{...c9e,name:t}:{...c9e,...t}});var f9e,p9e=b(()=>{Z_e();f9e=t=>{let e=d9e(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});var TQ,Y_e=b(()=>{TQ=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function Xs(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?TQ(e,t.currentPath):e.join("/")}}var Cw=b(()=>{Y_e()});function J_e(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function Ao(t,e,n,r,o){t[e]=n,J_e(t,e,r,o)}var rM=b(()=>{});var wo,m9e,Bt,ES,IQ=b(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},t.find=(o,i)=>{for(let s of o)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(wo||(wo={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(m9e||(m9e={}));Bt=wo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ES=t=>{switch(typeof t){case"undefined":return Bt.undefined;case"string":return Bt.string;case"number":return Number.isNaN(t)?Bt.nan:Bt.number;case"boolean":return Bt.boolean;case"function":return Bt.function;case"bigint":return Bt.bigint;case"symbol":return Bt.symbol;case"object":return Array.isArray(t)?Bt.array:t===null?Bt.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Bt.promise:typeof Map<"u"&&t instanceof Map?Bt.map:typeof Set<"u"&&t instanceof Set?Bt.set:typeof Date<"u"&&t instanceof Date?Bt.date:Bt.object;default:return Bt.unknown}}});var it,BSr,ch,X_e=b(()=>{IQ();it=wo.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),BSr=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ch=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}f
]`;continue}o+=r[l],r[l]==="\\"?i=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var z9e,Pw,QCr,axe=b(()=>{rM();Pw={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(z9e===void 0&&(z9e=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),z9e),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};QCr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function RQ(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===Me.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:nr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Xs(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:nr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===Me.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=OQ(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===Me.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Me.ZodBranded&&t.keyType._def.type._def.typeName===Me.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=MQ(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var lxe=b(()=>{Cw();ixe();axe();rc();RS()});function B9e(t,e){return e.mapStrategy==="record"?RQ(t,e):{type:"array",maxItems:125,items:{type:"array",items:[nr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Xs(e),nr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Xs(e)],minItems:2,maxItems:2}}}var j9e=b(()=>{Cw();lxe();rc()});function H9e(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),r=Array.from(new Set(n.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:
Known schemas:
- ${Object.keys(r).join(`
- `)}`,new Error(Qe)}let Xe=`${a}/$ref`,Be=Qs(t,$e,n,r,o,i,s,Xe,l);if(Be.valid||Oe.push({instanceLocation:s,keyword:"$ref",keywordLocation:Xe,error:"A subschema had errors."},...Be.errors),n==="4"||n==="7")return{valid:Oe.length===0,errors:Oe}}if(Array.isArray(m)){let Ke=m.length,$e=!1;for(let Xe=0;Xe<Ke;Xe++)if(u===m[Xe]||m[Xe]==="integer"&&u==="number"&&t%1===0&&t===t){$e=!0;break}$e||Oe.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(u!=="number"||t%1||t!==t)&&Oe.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&Oe.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u==="object"||u==="array"?vT(t,h)||Oe.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&Oe.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u==="object"||u==="array"?g.some(Ke=>vT(t,Ke))||Oe.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(Ke=>t===Ke)||Oe.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),y!==void 0){let Ke=`${a}/not`;Qs(t,y,n,r,o,i,s,Ke).valid&&Oe.push({instanceLocation:s,keyword:"not",keywordLocation:Ke,error:'Instance matched "not" schema.'})}let Kt=[];if(v!==void 0){let Ke=`${a}/anyOf`,$e=Oe.length,Xe=!1;for(let Be=0;Be<v.length;Be++){let Qe=v[Be],dt=Object.create(l),yt=Qs(t,Qe,n,r,o,p===!0?i:null,s,`${Ke}/${Be}`,dt);Oe.push(...yt.errors),Xe=Xe||yt.valid,yt.valid&&Kt.push(dt)}Xe?Oe.length=$e:Oe.splice($e,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:Ke,error:"Instance does not match any subschemas."})}if(_!==void 0){let Ke=`${a}/allOf`,$e=Oe.length,Xe=!0;for(let Be=0;Be<_.length;Be++){let Qe=_[Be],dt=Object.create(l),yt=Qs(t,Qe,n,r,o,p===!0?i:null,s,`${Ke}/${Be}`,dt);Oe.push(...yt.errors),Xe=Xe&&yt.valid,yt.valid&&Kt.push(dt)}Xe?Oe.length=$e:Oe.splice($e,0,{instanceLocation:s,keyword:"allOf",keywordLocation:Ke,error:"Instance does not match every subschema."})}if(S!==void 0){let Ke=`${a}/oneOf`,$e=Oe.length,Xe=S.filter((Be,Qe)=>{let dt=Object.create(l),yt=Qs(t,Be,n,r,o,p===!0?i:null,s,`${Ke}/${Qe}`,dt);return Oe.push(...yt.errors),yt.valid&&Kt.push(dt),yt.valid}).length;Xe===1?Oe.length=$e:Oe.splice($e,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:Ke,error:`Instance does not match exactly one subschema (${Xe} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...Kt),k!==void 0){let Ke=`${a}/if`;if(Qs(t,k,n,r,o,i,s,Ke,l).valid){if(x!==void 0){let Xe=Qs(t,x,n,r,o,i,s,`${a}/then`,l);Xe.valid||Oe.push({instanceLocation:s,keyword:"if",keywordLocation:Ke,error:'Instance does not match "then" schema.'},...Xe.errors)}}else if(C!==void 0){let Xe=Qs(t,C,n,r,o,i,s,`${a}/else`,l);Xe.valid||Oe.push({instanceLocation:s,keyword:"if",keywordLocation:Ke,error:'Instance does not match "else" schema.'},...Xe.errors)}}if(u==="object"){if(w!==void 0)for(let Be of w)Be in t||Oe.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${Be}".`});let Ke=Object.keys(t);if(F!==void 0&&Ke.length<F&&Oe.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${F} properties.`}),q!==void 0&&Ke.length>q&&Oe.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${q} properties.`}),Z!==void 0){let Be=`${a}/propertyNames`;for(let Qe in t){let dt=`${s}/${Og(Qe)}`,yt=Qs(Qe,Z,n,r,o,i,dt,Be);yt.valid||Oe.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:Be,error:`Property name "${Qe}" does not
data: ${JSON.stringify(o)}
`));r.enqueue(e.encode(`event: end
`)),r.close()}});return lh.fromReadableStream(n)}var san=b(()=>{PS()});function A8e(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function pxe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function E8e(t){return t!=null&&typeof t=="object"&&typeof t.next=="function"}async function lan(t,e){try{let n=await t.next();for(;!n.done;)await e?.(n.value),n=await t.next();return n.value}finally{await t.return?.(void 0)}}function*M8e(t,e){for(;;){let{value:n,done:r}=Dd.runWithConfig(ah(t),e.next.bind(e),!0);if(r)break;yield n}}async function*mxe(t,e){let n=e[Symbol.asyncIterator]();for(;;){let{value:r,done:o}=await Dd.runWithConfig(ah(t),n.next.bind(e),!0);if(o)break;yield r}}var aan,O8e=b(()=>{JL();XL();IS();aan=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function lu(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function $0r(t){if(Gbe(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function _T(t){if(typeof t=="function")return new xT({func:t});if(Lo.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=_T(r);return new NW({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function F0r(t,e){let n=e.name??t.getName(),r=e.description??mT(e.schema);return kQ(e.schema)?new R8e({name:n,description:r,schema:Mg.object({input:Mg.string()}).transform(o=>o.input),bound:t}):new R8e({name:n,description:r,schema:e.schema,bound:t})}var Lo,xD,N8e,SD,NW,D0r,xT,pan,hxe,man,R8e,Wu=b(()=>{Mbe();xL();TL();JL();XL();IS();xW();PS();csn();msn();t9e();xQ();xsn();G_e();AS();oan();san();O8e();$Ge();RS();Lo=class extends yw{constructor(){super(...arguments);A(this,"lc_runnable",!0);A(this,"name")}getName(e){let n=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${n}${e}`:n}withRetry(e){return new N8e({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new xD({bound:this,config:e,kwargs:{}})}withFallbacks(e){let n=Array.isArray(e)?e:e.fallbacks;return new pan({runnable:this,fallbacks:n})}_getOptionsList(e,n=0){if(Array.isArray(e)&&e.length!==n)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${n} inputs`);if(Array.isArray(e))return e.map(uo);if(n>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));return Array.from({length:n},(o,i)=>uo(i===0?e:r))}return Array.from({length:n},()=>uo(e))}async batch(e,n,r){let o=this._getOptionsList(n??{},e.length),i=new tD({maxConcurrency:o[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:a=>{throw a}}),s=e.map((a,l)=>i.call(async()=>{try{return await this.invoke(a,o[l])}catch(c){if(r?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,n){yield this.invoke(e,n)}async stream(e,n){let r=uo(n),o=new QL({generator:this._streamIterator(e,r),config:r});return await o.setup,lh.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let n;e===void 0?n=uo(e):n=uo({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[n,r]}async _callWithConfig(e,n,r){let o=uo(r),i=await(await sh(o))?.handleChainStart(this.toJSON(),lu(n,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{s=await xw(e.call(this,n,o,i),o.signal)}catch(a){throw await i?.handleChainError(a),a}return await i?.handleChainEnd(lu(s,"output")),s}async _batchWithConfig(e,n,r,o){let i=this._getOptionsList(r??{},n.length),s=await Promise.all(i.map(sh)),a=await Promise.all(s.map(async(c,u)=>{let d=await c?.handleChainStart(this.toJSON(),lu(n[u],"input"),i[u].runId,i[u].runType,void 0,void 0,i[u].runName??this.getName());return delete i[u].runId,d})),l;try{l=await xw(e.call(this,n,i,a,o),i?.[0]?.signal)}catch(c){throw await Promise.all(a.map(u=>u?.handleChainError(c))),c}return await Promise.all(a.map(c=>c?.handleChainEnd(lu(l,"output")))),l}_concatOutputChunks(e,n){return Yb(e,n)}async*_transformStreamWithConfig(e,n,r){let o,i=!0,s,a=!0,l=uo(r),c=await sh(l),u=this;async function*d(){for await(let p of e){if(i)if(o===void 0)o=p;else try{o=u._concatOutputChunks(o,p)}catch{o=void 0,i=!1}yield p}}let f;try{let p=await Qin(n.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName(),void 0,{lc_defers_inputs:!0}),l.signal,l);delete l.runId,f=p.setup;let m=f?.handlers.find(fsn),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let g=f?.handlers.find(lsn);g!==void 0&&f!==void 0&&(h=g.tapOutputIterable(f.runId,h));for await(let w of h)if(yield w,a)if(s===void 0)s=w;else try{s=this._concatOutputChunks(s,w)}catch{s=void 0,a=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,void 0,{inputs:lu(o,"input")})
`).filter(Boolean).reduce((r,o)=>{let[i,s,...a]=o.split(" "),l=Number.parseInt(s,10);return a.forEach((c,u)=>r[c]=l+u),r},{});for(let[r,o]of Object.entries(n)){let i=Lan.default.toByteArray(r);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[o,i])=>(r[i]=this.textEncoder.encode(o),r),{})}encode(t,e=[],n="all"){let r=new RegExp(this.patStr,"ug"),o=W8e.specialTokenRegex(Object.keys(this.specialTokens)),i=[],s=new Set(e==="all"?Object.keys(this.specialTokens):e),a=new Set(n==="all"?Object.keys(this.specialTokens).filter(c=>!s.has(c)):n);if(a.size>0){let c=W8e.specialTokenRegex([...a]),u=t.match(c);if(u!=null)throw new Error(`The text contains a special token that is not allowed: ${u[0]}`)}let l=0;for(;;){let c=null,u=l;for(;o.lastIndex=u,c=o.exec(t),!(c==null||s.has(c[0]));)u=c.index+1;let d=c?.index??t.length;for(let p of t.substring(l,d).matchAll(r)){let m=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...ekr(m,this.rankMap))}if(c==null)break;let f=this.specialTokens[c[0]];i.push(f),l=c.index+c[0].length}return i}decode(t){let e=[],n=0;for(let i=0;i<t.length;++i){let s=t[i],a=this.textMap.get(s)??this.inverseSpecialTokens[s];a!=null&&(e.push(a),n+=a.length)}let r=new Uint8Array(n),o=0;for(let i of e)r.set(i,o),o+=i.length;return this.textDecoder.decode(r)}},xxe=W8e;X0r(xxe,"specialTokenRegex",t=>new RegExp(t.map(e=>tkr(e)).join("|"),"g"))});var $an=b(()=>{Dan()});async function Fan(t){return t in Sxe||(Sxe[t]=nkr.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new xxe(e)).catch(e=>{throw delete Sxe[t],e})),await Sxe[t]}async function zan(t){return Fan(V8e(t))}var Sxe,nkr,q8e=b(()=>{pr();xQ();$an();Sxe={},nkr=new tD({})});function $S(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}var rkr,okr,Cxe,DW,Ng=b(()=>{pr();Vb();Ran();xQ();Wu();BQ();q8e();rkr=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t;okr=()=>!1,Cxe=class extends Lo{constructor(e){super(e);A(this,"verbose");A(this,"callbacks");A(this,"tags");A(this,"metadata");this.verbose=e.verbose??okr(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.2.8")}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}_addVersion(e,n){let r=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:n}}}},DW=class extends Cxe{constructor({callbacks:e,callbackManager:n,...r}){let{cache:o,...i}=r;super({callbacks:e??n,...i});A(this,"caller");A(this,"cache");A(this,"_encoding");typeof o=="object"?this.cache=o:o?this.cache=Man.global():this.cache=void 0,this.caller=new tD(r??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let n;typeof e=="string"?n=e:n=e.map(o=>typeof o=="string"?o:o.type==="text"&&"text"in o?o.text:"").join("");let r=Math.ceil(n.length/4);if(!this._encoding)try{this._encoding=await zan("modelName"in this?rkr(this.modelName):"gpt2")}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}if(this._encoding)try{r=this._encoding.encode(n).length}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new bxe(e):Array.isArray(e)?new _xe(e.map(Wb)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...n}){let r={...this._identifyingParams(),...n,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([o,i])=>i!==void 0).map(([o,i])=>`${o}:${JSON.stringify(i)}`).sort().join(",")}se
Details: ${m.message}`),a9e(m)&&(h=`${h}
${rOe(m)}`),new jX(h,JSON.stringify(e))}else{let m=Qs(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
`)}`),new jX(h,JSON.stringify(e))}i=o}let s=YL(n),a=Hu.configure(s.callbacks,this.callbacks,s.tags||r,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),l;DE(e)&&(l=e.id),!l&&tnn(s)&&(l=s.toolCall.id);let c=await a?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),s.runId,void 0,void 0,void 0,s.runName,l);delete s.runId;let u;try{let m=await this._call(i,c,s);u=E8e(m)?await lan(m,async h=>{try{await c?.handleToolEvent(h)}catch(g){await c?.handleToolError(g)}}):m}catch(m){throw await c?.handleToolError(m),m}let d,f;if(this.responseFormat==="content_and_artifact")if(Array.isArray(u)&&u.length===2)[d,f]=u;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(u)}`);else d=u;let p=akr({content:d,artifact:f,toolCallId:l,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(p),p}},Ban=class extends Uan{constructor(e){super(e);A(this,"schema",Mg.object({input:Mg.string().optional()}).transform(e=>e.input))}call(e,n){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,n)}},jan=class extends Ban{constructor(e){super(e);A(this,"name");A(this,"description");A(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,n){let r=YL(n);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,n,r){return this.func(e,n,r)}},ikr=class extends Uan{constructor(e){super(e);A(this,"description");A(this,"func");A(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,n,r){let o=YL(n);return o.runName===void 0&&(o.runName=this.name),super.call(e,o,r)}_call(e,n,r){return this.func(e,n,r)}}});var Ew=b(()=>{pr();AS()});var jQ,Pxe=b(()=>{IS();PS();Wu();jQ=class extends Lo{constructor(e){super(e);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"lc_serializable",!0);A(this,"func");e&&(this.func=e.func)}static lc_name(){return"RunnablePassthrough"}async invoke(e,n){let r=uo(n);return this.func&&await this.func(e,r),this._callWithConfig(o=>Promise.resolve(o),e,r)}async*transform(e,n){let r=uo(n),o,i=!0;for await(let s of this._transformStreamWithConfig(e,a=>a,r))if(yield s,i)if(o===void 0)o=s;else try{o=Yb(o,s)}catch{o=void 0,i=!1}this.func&&o!==void 0&&await this.func(o,r)}static assign(e){return new hxe(new NW({steps:e}))}}});var Jan=b(()=>{IS();Wu()});var Xan=b(()=>{IS();PS();Wu()});var Qan=b(()=>{Wf();rh();UE();Wu();ei();Pxe()});var cM=b(()=>{pr();IS();xW();Wu();Pxe();Jan();Xan();Qan()});var zW,uM,Ud,PD=b(()=>{sT();Wu();cM();zW=class extends Lo{parseResultWithPrompt(t,e,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),t,{...e,runType:"parser"})}},uM=class extends zW{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},Ud=class extends Error{constructor(e,n,r,o=!1){super(e);A(this,"llmOutput");A(this,"observation");A(this,"sendToLLM");if(this.llmOutput=n,this.observation=r,this.sendToLLM=o,o&&(r===void 0||n===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");LE(this,"OUTPUT_PARSING_FAILURE")}}});var HQ,UW,dM=b(()=>{Wf();Vb();$d();PD();fxe();HQ=class extends uM{async*_transform(t){for await(let e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},UW=class extends HQ{constructor(e){super(e);A(this,"diff",!1);this.diff=e?.diff??this.diff}async*_transform(e){let n,r;for await(let o of e){if(typeof o!="string"&&typeof o.content!="string")throw new Error("Cannot handle non-string output.");let i;if(Pbe(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new fi({message:o,text:o.content})}else if(ww(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new fi({message:Dbe(o),text:o.content})}else i=new pT({text:o});r===void 0?r=i:r=r.concat(i);let s=await this.parsePartialResult([r]);s!=null&&!vT(s,n)&&(this.diff?yield this._dif
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(Gi(this.schema))}
\`\`\`
`}async parse(e){try{let n=e.trim(),r=(n.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||n.match(/```json\s*([\s\S]*?)```/)?.[1]||n).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await iD(this.schema,JSON.parse(r))}catch(n){throw new Ud(`Failed to parse. Text: "${e}". Error: ${n}`,e)}}_baseMessageToString(e){return e.text}}});var Akr,Ekr,rln=b(()=>{Akr=function(){let t={};t.parser=function(E,N){return new n(E,N)},t.SAXParser=n,t.SAXStream=c,t.createStream=l,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(E,N){if(!(this instanceof n))return new n(E,N);var Y=this;o(Y),Y.q=Y.c="",Y.bufferCheckPosition=t.MAX_BUFFER_LENGTH,Y.opt=N||{},Y.opt.lowercase=Y.opt.lowercase||Y.opt.lowercasetags,Y.looseCase=Y.opt.lowercase?"toLowerCase":"toUpperCase",Y.tags=[],Y.closed=Y.closedRoot=Y.sawRoot=!1,Y.tag=Y.error=null,Y.strict=!!E,Y.noscript=!!(E||Y.opt.noscript),Y.state=C.BEGIN,Y.strictEntities=Y.opt.strictEntities,Y.ENTITIES=Y.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),Y.attribList=[],Y.opt.xmlns&&(Y.ns=Object.create(m)),Y.trackPosition=Y.opt.position!==!1,Y.trackPosition&&(Y.position=Y.line=Y.column=0),I(Y,"onready")}Object.create||(Object.create=function(E){function N(){}return N.prototype=E,new N}),Object.keys||(Object.keys=function(E){var N=[];for(var Y in E)E.hasOwnProperty(Y)&&N.push(Y);return N});function r(E){for(var N=Math.max(t.MAX_BUFFER_LENGTH,10),Y=0,$=0,te=e.length;$<te;$++){var de=E[e[$]].length;if(de>N)switch(e[$]){case"textNode":O(E);break;case"cdata":M(E,"oncdata",E.cdata),E.cdata="";break;case"script":M(E,"onscript",E.script),E.script="";break;default:F(E,"Max buffer length exceeded: "+e[$])}Y=Math.max(Y,de)}E.bufferCheckPosition=t.MAX_BUFFER_LENGTH-Y+E.position}function o(E){for(var N=0,Y=e.length;N<Y;N++)E[e[N]]=""}function i(E){O(E),E.cdata!==""&&(M(E,"oncdata",E.cdata),E.cdata=""),E.script!==""&&(M(E,"onscript",E.script),E.script="")}n.prototype={end:function(){q(this)},write:z,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){i(this)}};var s=ReadableStream;s||(s=function(){});var a=t.EVENTS.filter(function(E){return E!=="error"&&E!=="end"});function l(E,N){return new c(E,N)}function c(E,N){if(!(this instanceof c))return new c(E,N);s.apply(this),this._parser=new n(E,N),this.writable=!0,this.readable=!0;var Y=this;this._parser.onend=function(){Y.emit("end")},this._parser.onerror=function($){Y.emit("error",$),Y._parser.error=null},this._decoder=null,a.forEach(function($){Object.defineProperty(Y,"on"+$,{get:function(){return Y._parser["on"+$]},set:function(te){if(!te)return Y.removeAllListeners($),Y._parser["on"+$]=te,te;Y.on($,te)},enumerable:!0,configurable:!1})})}c.prototype=Object.create(s.prototype,{constructor:{value:c}}),c.prototype.write=function(E){return this._parser.write(E.toString()),this.emit("data",E),!0},c.prototype.end=function(E){return E&&E.length&&this.write(E),this._parser.end(),!0},c.prototype.on=function(E,N){var Y=this;return!Y._parser["on"+E]&&a.indexOf(E)!==-1&&(Y._parser["on"+E]=function(){var $=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);$.splice(0,0,E),Y.emit.apply(Y,$)}),s.prototype.on.call(Y,E,N)};var u="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",p="http://www.w3.org/2000/xmlns/",m={xml:f,xmlns:p},h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,g=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,w=/[#:_A-Za-z\u00C0-\u00
`?(N.line++,N.column=0):N.column++);N.textNode+=E.substring(te,Y-1)}$==="<"&&!(N.sawRoot&&N.closedRoot&&!N.strict)?(N.state=C.OPEN_WAKA,N.startTagPosition=N.position):(!v($)&&(!N.sawRoot||N.closedRoot)&&Z(N,"Text data outside of root node."),$==="&"?N.state=C.TEXT_ENTITY:N.textNode+=$);continue;case C.SCRIPT:$==="<"?N.state=C.SCRIPT_ENDING:N.script+=$;continue;case C.SCRIPT_ENDING:$==="/"?N.state=C.CLOSE_TAG:(N.script+="<"+$,N.state=C.SCRIPT);continue;case C.OPEN_WAKA:if($==="!")N.state=C.SGML_DECL,N.sgmlDecl="";else if(!v($))if(k(h,$))N.state=C.OPEN_TAG,N.tagName=$;else if($==="/")N.state=C.CLOSE_TAG,N.tagName="";else if($==="?")N.state=C.PROC_INST,N.procInstName=N.procInstBody="";else{if(Z(N,"Unencoded <"),N.startTagPosition+1<N.position){var de=N.position-N.startTagPosition;$=new Array(de).join(" ")+$}N.textNode+="<"+$,N.state=C.TEXT}continue;case C.SGML_DECL:(N.sgmlDecl+$).toUpperCase()===u?(M(N,"onopencdata"),N.state=C.CDATA,N.sgmlDecl="",N.cdata=""):N.sgmlDecl+$==="--"?(N.state=C.COMMENT,N.comment="",N.sgmlDecl=""):(N.sgmlDecl+$).toUpperCase()===d?(N.state=C.DOCTYPE,(N.doctype||N.sawRoot)&&Z(N,"Inappropriately located doctype declaration"),N.doctype="",N.sgmlDecl=""):$===">"?(M(N,"onsgmldeclaration",N.sgmlDecl),N.sgmlDecl="",N.state=C.TEXT):(_($)&&(N.state=C.SGML_DECL_QUOTED),N.sgmlDecl+=$);continue;case C.SGML_DECL_QUOTED:$===N.q&&(N.state=C.SGML_DECL,N.q=""),N.sgmlDecl+=$;continue;case C.DOCTYPE:$===">"?(N.state=C.TEXT,M(N,"ondoctype",N.doctype),N.doctype=!0):(N.doctype+=$,$==="["?N.state=C.DOCTYPE_DTD:_($)&&(N.state=C.DOCTYPE_QUOTED,N.q=$));continue;case C.DOCTYPE_QUOTED:N.doctype+=$,$===N.q&&(N.q="",N.state=C.DOCTYPE);continue;case C.DOCTYPE_DTD:N.doctype+=$,$==="]"?N.state=C.DOCTYPE:_($)&&(N.state=C.DOCTYPE_DTD_QUOTED,N.q=$);continue;case C.DOCTYPE_DTD_QUOTED:N.doctype+=$,$===N.q&&(N.state=C.DOCTYPE_DTD,N.q="");continue;case C.COMMENT:$==="-"?N.state=C.COMMENT_ENDING:N.comment+=$;continue;case C.COMMENT_ENDING:$==="-"?(N.state=C.COMMENT_ENDED,N.comment=D(N.opt,N.comment),N.comment&&M(N,"oncomment",N.comment),N.comment=""):(N.comment+="-"+$,N.state=C.COMMENT);continue;case C.COMMENT_ENDED:$!==">"?(Z(N,"Malformed comment"),N.comment+="--"+$,N.state=C.COMMENT):N.state=C.TEXT;continue;case C.CDATA:$==="]"?N.state=C.CDATA_ENDING:N.cdata+=$;continue;case C.CDATA_ENDING:$==="]"?N.state=C.CDATA_ENDING_2:(N.cdata+="]"+$,N.state=C.CDATA);continue;case C.CDATA_ENDING_2:$===">"?(N.cdata&&M(N,"oncdata",N.cdata),M(N,"onclosecdata"),N.cdata="",N.state=C.TEXT):$==="]"?N.cdata+="]":(N.cdata+="]]"+$,N.state=C.CDATA);continue;case C.PROC_INST:$==="?"?N.state=C.PROC_INST_ENDING:v($)?N.state=C.PROC_INST_BODY:N.procInstName+=$;continue;case C.PROC_INST_BODY:if(!N.procInstBody&&v($))continue;$==="?"?N.state=C.PROC_INST_ENDING:N.procInstBody+=$;continue;case C.PROC_INST_ENDING:$===">"?(M(N,"onprocessinginstruction",{name:N.procInstName,body:N.procInstBody}),N.procInstName=N.procInstBody="",N.state=C.TEXT):(N.procInstBody+="?"+$,N.state=C.PROC_INST_BODY);continue;case C.OPEN_TAG:k(g,$)?N.tagName+=$:(re(N),$===">"?ne(N):$==="/"?N.state=C.OPEN_TAG_SLASH:(v($)||Z(N,"Invalid character in tag name"),N.state=C.ATTRIB));continue;case C.OPEN_TAG_SLASH:$===">"?(ne(N,!0),G(N)):(Z(N,"Forward-slash in opening tag not followed by >"),N.state=C.ATTRIB);continue;case C.ATTRIB:if(v($))continue;$===">"?ne(N):$==="/"?N.state=C.OPEN_TAG_SLASH:k(h,$)?(N.attribName=$,N.attribValue="",N.state=C.ATTRIB_NAME):Z(N,"Invalid attribute name");continue;case C.ATTRIB_NAME:$==="="?N.state=C.ATTRIB_VALUE:$===">"?(Z(N,"Attribute without value"),N.attribValue=N.attribName,oe(N),ne(N)):v($)?N.state=C.ATTRIB_NAME_SAW_WHITE:k(g,$)?N.attribName+=$:Z(N,"Invalid attribute name");continue;case C.ATTRIB_NAME_SAW_WHITE:if($==="=")N.state=C.ATTRIB_VALUE;else{if(v($))continue;Z(N,"Attribute without value"),N.tag.attributes[N.attribName]="",N.attribValue="",M(N,"onattribute",{name:N.attribName,value:""}),N.attribName="",$===">"?ne(N):k(h,$)?(N.attribName=$,N.state=C.ATTRIB_NAME):(Z(N,"Invalid attribute name"),N.state=C.ATTRIB)}continue;case C.ATTRIB_VALUE:if(v($))continue;_($)?(
`))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}function Lkr(t){let e=[];for(let n of t)if(n._getType()==="tool")if(typeof n.content=="string"){let r=e[e.length-1];r?._getType()==="human"&&Array.isArray(r.content)&&"type"in r.content[0]&&r.content[0].type==="tool_result"?r.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):e.push(new Zs({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else e.push(new Zs({content:[{type:"tool_result",...n.content!=null?{content:mZe(n)}:{},tool_use_id:n.tool_call_id}]}));else e.push(n);return e}function pZe(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*Dkr(t,e){let n=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],r=["text","text_delta"];for(let o of t){jf(o)&&(yield iT(o,mln));let i="cache_control"in o?o.cache_control:void 0;if(o.type==="image_url"){let s;typeof o.image_url=="string"?s=fZe(o.image_url):typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"&&(s=fZe(o.image_url.url)),s&&(yield{type:"image",source:s,...i?{cache_control:i}:{}})}else if(pln(o))yield o;else if(o.type==="image"){let s;"url"in o&&typeof o.url=="string"?s=fZe(o.url):"data"in o&&(typeof o.data=="string"||o.data instanceof Uint8Array)?s={type:"base64",media_type:"mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:"image/jpeg",data:typeof o.data=="string"?o.data:Buffer.from(o.data).toString("base64")}:"fileId"in o&&typeof o.fileId=="string"&&(s={type:"file",file_id:o.fileId}),s&&(yield{type:"image",source:s,...i?{cache_control:i}:{}})}else if(o.type==="file"){let s;"url"in o&&typeof o.url=="string"?s={type:"url",url:o.url}:"data"in o&&(typeof o.data=="string"||o.data instanceof Uint8Array)?s={type:"base64",media_type:"mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:"application/pdf",data:typeof o.data=="string"?o.data:Buffer.from(o.data).toString("base64")}:"fileId"in o&&typeof o.fileId=="string"&&(s={type:"file",file_id:o.fileId}),s&&(yield{type:"document",source:s,...i?{cache_control:i}:{}})}else if(o.type==="document")yield{...o,...i?{cache_control:i}:{}};else if(uln(o))yield{type:"thinking",thinking:o.thinking,signature:o.signature,...i?{cache_control:i}:{}};else if(dln(o))yield{type:"redacted_thinking",data:o.data,...i?{cache_control:i}:{}};else if(Axe(o))yield{type:"compaction",content:o.content,...i?{cache_control:i}:{}};else if(fln(o))yield{type:"search_result",title:o.title,source:o.source,..."cache_control"in o&&o.cache_control?{cache_control:o.cache_control}:{},..."citations"in o&&o.citations?{citations:o.citations}:{},content:o.content};else if(r.find(s=>s===o.type)&&"text"in o)yield{type:"text",text:o.text,...i?{cache_control:i}:{},..."citations"in o&&o.citations?{citations:o.citations}:{}};else if(n.find(s=>s===o.type)){let s={...o};if(s.type==="input_json_delta")continue;if(s.type==="tool_use"&&typeof s.input=="string"){let a=e?.find(l=>l.id===s.id);a?s.input=a.args:s.input=t.filter(l=>l.index===s.index&&l.type==="input_json_delta"&&typeof l.input=="string").reduce((l,c)=>l+c.input,s.input)}if("index"in s&&delete s.index,"input"in s&&typeof s.input=="string")try{s.input=JSON.parse(s.input)}catch{s.input={}}yield{...s,...i?{cache_control:i}:{}}}else o.type==="container_upload"&&(yield{...o,...i?{cache_control:i}:{}})}}function mZe(t,e){let{content:n}=t;return typeof n=="string"?n:Array.from(Dkr(n,e))}function GQ(t){let e=Lkr(t),n;return e.length>0&&e[0]._getType()==="system"&&(n=t[0].content),{messages:$kr((n!==void 0?e.slice(1):e).map(r=>{let o;if(r._getType()==="human")o="user";else if(r._getType()==="ai")o="assistant";else if(r._getType()==="tool")o="user";else throw r._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${r.type}" is not supported.`);if(mr.isInstance(r)&&r.response_metadata?.output_version==="v1")r
`,t}function yZe(t){let e;return t.status===400&&typeof t.message=="string"&&t.message.includes("prompt is too long")?e=ZQ(Ebe.fromError(t),"CONTEXT_OVERFLOW"):t.status===400&&t.message.includes("tool")?e=nc(ZQ(t,"INVALID_TOOL_RESULTS"),!1):t.status===401?e=nc(ZQ(t,"MODEL_AUTHENTICATION"),!1):t.status===404?e=nc(ZQ(t,"MODEL_NOT_FOUND"),!1):t.status===429?e=nc(ZQ(t,"MODEL_RATE_LIMIT"),!0):e=t,e}var Pln=b(()=>{sT()});var Aln,Eln=b(()=>{Aln={"claude-sonnet-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-fable-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-8":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5-20251101":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-7":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-5":{maxInpu
`,"\r"]);TT.NEWLINE_REGEXP=/\r\n|[\n\r]/g});async function*Ecn(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ft("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ft("Attempted to iterate over a response with no body");let n=new UZe,r=new TT,o=tee(t.body);for await(let i of dTr(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*dTr(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?oV(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=Acn(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function fTr(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var iee,Fg,UZe,see=b(()=>{Lg();va();eV();zZe();eV();fM();n_();Hxe();kT();va();Nxe();Fg=class t{constructor(e,n,r){this.iterator=e,iee.set(this,void 0),this.controller=n,qe(this,iee,r,"f")}static rawEvents(e,n=new AbortController){return Ecn(e,n)}static fromSSEResponse(e,n,r){let o=!1,i=r?pi(r):console;async function*s(){if(o)throw new ft("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of Ecn(e,n)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="user.tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="session.updated"||l.event==="span.model_request_start"||l.event==="span.model_request_end"||l.event==="span.outcome_evaluation_start"||l.event==="span.outcome_evaluation_ongoing"||l.event==="span.outcome_evaluation_end"||l.event==="user.define_outcome"||l.event==="agent.thread_message_received"||l.event==="agent.thread_message_sent"||l.event==="agent.session_thread_message_received"||l.event==="agent.session_thread_message_sent"||l.event==="session.thread_created"||l.event==="session.thread_status_created"||l.event==="session.thread_status_running"||l.event==="session.thread_status_idle"||l.event==="session.thread_status_rescheduled"||l.event==="session.thread_status_terminated"||l.event==="event_start"||l.event==="event_delta"||l.event==="system.message")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){let c=XQ(l.data)??l.data,u=c?.error?.type;throw new Ol(void 0,c,void 0,e.headers,u)}}a=!0}catch(l){if(Mw(l))return;throw l}finally{a||n.abort(),US(n)}}return new t(s,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new TT,l=tee(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new ft("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(Mw(l))return;throw l}finally{a||n.abort(),US(n)}}return new t(s,n,r)}[(iee=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=fTr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}}});async function Gxe(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(e.options.stream)return pi(t).debug("response",n.status,n.url,n.headers,n.body),Fg.fromSSEResponse(n,e.controller);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let f=await n.json();return aee(f,n)}return await n.text()})().finally(()=>{!e.options.stream&&!e.options.__binaryResponse&&US(e.controller)});return pi(t).debug(`[${r}] response parsed`,jS({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}function aee(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Zxe=b(()=>{see();kT();Nxe()});function BZe(t){return typeof t=="object"&&t!==null&&Ocn.has(t)}function Rcn(t){let e=new Set;for(;typeof t=="object"&&t!==null&&!e.has(t);){if(e.add(t),BZe(t)||Mw(t)||t instanceof zS||t instanceof YQ)return!0;t=t.cause}return!1}function jZe(t,e,n,r){return async(o,i={})=>{if(e.length===0)return t.call(void 0,o,i);let s=i.headers instanceof Headers?i.headers:new Headers(i.headers),a=await mTr(t,e,n,r)({...i,headers:s,url:typeof o=="string"?o:o instanceof URL?o.href:o.url});if(a.bodyUsed||a.body?.locked)throw new ft("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return a}}function pTr(t,e){let n=new WeakMap;return{options:t,logger:e?pi(e):gcn(),parse(r){if(t?.stream&&r.ok)return Mcn(r,t);let o=n.get(r);return o||(o=Mcn(r,t),n.set(r,o)),o}}}async function Mcn(t,e){if(t.bodyUsed||t.body?.locked)throw new ft("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(e?.stream&&t.ok)return Fg.fromSSEResponse(t.clone(),new AbortController);if(t.status===204)return null;if(e?.__binaryResponse)return t;let r=t.headers.get("content-type")?.split(";")[0]?.trim();return r?.includes("application/json")||r?.endsWith("+json")?t.headers.get("content-length")==="0"?void 0:aee(await t.clone().json(),t):await t.clone().text()}function mTr(t,e,n,r){let o=async({url:s,...a})=>{try{return await t.call(void 0,s,a)}catch(l){let c=AD(l);throw Ocn.add(c),c}},i=pTr(n,r);for(let s=e.length-1;s>=0;s--){let a=e[s],l=o;o=async c=>a(c,l,i)}return o}var Ocn,Ncn=b(()=>{fM();Zxe();kT();va();see();Ocn=new WeakSet});var lee,MD,Yxe=b(()=>{Lg();Zxe();MD=class t extends Promise{constructor(e,n,r=Gxe){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,lee.set(this,void 0),qe(this,lee,e,"f")}_thenUnwrap(e){return new t(ae(this,lee,"f"),this.responsePromise,async(n,r)=>aee(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(ae(this,lee,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};lee=new WeakMap});var Jxe,cee,uee,Rw,Lr,Xxe,zi=b(()=>{Lg();va();Zxe();Yxe();n_();cee=class{constructor(e,n,r,o){Jxe.set(this,void 0),qe(this,Jxe,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new ft("No next page expected; please check `.hasNextPage()` before calling `.g
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},ze=kTr(jcn)});var aV,GZe=b(()=>{ti();zi();po();ts();aV=class extends en{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(ze`/v1/deployment_runs/${e}?beta=true`,{...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",Lr,{query:o,...n,headers:Se([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}}});var lV,ZZe=b(()=>{ti();zi();po();ts();lV=class extends en{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/deployments?beta=true",{body:o,...n,headers:Se([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(ze`/v1/deployments/${e}?beta=true`,{...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(ze`/v1/deployments/${e}?beta=true`,{body:i,...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/deployments?beta=true",Lr,{query:o,...n,headers:Se([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(ze`/v1/deployments/${e}/archive?beta=true`,{...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}pause(e,n={},r){let{betas:o}=n??{};return this._client.post(ze`/v1/deployments/${e}/pause?beta=true`,{...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}run(e,n={},r){let{betas:o}=n??{};return this._client.post(ze`/v1/deployments/${e}/run?beta=true`,{...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}unpause(e,n={},r){let{betas:o}=n??{};return this._client.post(ze`/v1/deployments/${e}/unpause?beta=true`,{...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var cV,YZe=b(()=>{ti();zi();po();ts();cV=class extends en{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/dreams?beta=true",{body:o,...n,headers:Se([{"anthropic-beta":[...r??[],"dreaming-2026-04-21"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(ze`/v1/dreams/${e}?beta=true`,{...r,headers:Se([{"anthropic-beta":[...o??[],"dreaming-2026-04-21"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/dreams?beta=true",Lr,{query:o,...n,headers:Se([{"anthropic-beta":[...r??[],"dreaming-2026-04-21"].toString()},n?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(ze`/v1/dreams/${e}/archive?beta=true`,{...r,headers:Se([{"anthropic-beta":[...o??[],"dreaming-2026-04-21"].toString()},r?.headers])})}cancel(e,n={},r){let{betas:o}=n??{};return this._client.post(ze`/v1/dreams/${e}/cancel?beta=true`,{...r,headers:Se([{"anthropic-beta":[...o??[],"dreaming-2026-04-21"].toString()},r?.headers])})}}});function pee(t){return{[pM]:t}}function tSe(t){return typeof t=="object"&&t!==null&&fee in t}function JZe(t,e){let n=new Set;if(t)for(let r of t)tSe(r)&&n.add(r[fee]);if(e)for(let r of e){tSe(r)&&n.add(r[fee]);let o=r.content;if(Array.isArray(o))for(let i of o)tSe(i)&&n.add(i[fee])}return Array.from(n)}function rSe(t,e){let n=JZe(t,e);return n.length===0?{}:{[pM]:n.join(", ")}}function Hcn(t){return tSe(t)?{[pM]:t[fee]}:{}}var pM,nSe,fee,HS=b(()=>{pM="x-stainless-helper",nSe="x-stainless-helper-method";fee=Symbol("anthropic.sdk.stainlessHelper")});var uV,XZe=b(()=>{ti();zi();po();HS();sV();ts();uV=class extends en{list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/files?beta=true",Rw,{query:o,...n,headers:Se([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`});async function TIr(t,e=t.messages.at(-1),n){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let r=e.content.filter(s=>s.type==="tool_use");if(r.length===0)return null;let o=PIr(t);return{role:"user",content:await Promise.all(r.map(async s=>{let a=t.tools.find(l=>("name"in l?l.name:l.mcp_server_name)===s.name);if(!a||!("run"in a)||!o.has(s.name))return IIr(s);try{let l=s.input;"parse"in a&&a.parse&&(l=a.parse(l));let c=await a.run(l,{toolUse:s,toolUseBlock:s,signal:n?.signal});return{type:"tool_result",tool_use_id:s.id,content:c}}catch(l){return{type:"tool_result",tool_use_id:s.id,content:l instanceof IT?l.content:`Error: ${l instanceof Error?l.message:String(l)}`,is_error:!0}}}))}}function IIr(t){return{type:"tool_result",tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0}}function PIr(t){let e=new Set;for(let n of t.tools)"run"in n&&e.add(n.name);for(let n of t.messages)if(!(n.role!=="system"||typeof n.content=="string"))for(let r of n.content)AIr(r,e);return e}function AIr(t,e){switch(t.type){case"tool_removal":case"tool_addition":Eun(t,e);break;case"mid_conv_system":for(let n of t.content)(n.type==="tool_removal"||n.type==="tool_addition")&&Eun(n,e);break;default:break}}function Eun(t,e){let n=EIr(t.tool);n!==void 0&&(t.type==="tool_removal"?e.delete(n):e.add(n))}function EIr(t){switch(t.type){case"tool_reference":return t.name;default:return}}var Eee,OV,FD,du,ph,Bg,AT,kM,Mee,Aun,L7e,RV,D7e=b(()=>{Lg();wee();va();po();Tun();Pun();HS();RV=class{constructor(e,n,r){Eee.add(this),this.client=e,OV.set(this,!1),FD.set(this,!1),du.set(this,void 0),ph.set(this,void 0),Bg.set(this,void 0),AT.set(this,void 0),kM.set(this,void 0),Mee.set(this,0),qe(this,du,{params:{...n,messages:structuredClone(n.messages)}},"f");let o=JZe(n.tools,n.messages);qe(this,ph,{...r,headers:Se([pee("BetaToolRunner"),o.length?{[pM]:o.join(", ")}:void 0,r?.headers])},"f"),qe(this,kM,N7e(),"f"),n.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(OV=new WeakMap,FD=new WeakMap,du=new WeakMap,ph=new WeakMap,Bg=new WeakMap,AT=new WeakMap,kM=new WeakMap,Mee=new WeakMap,Eee=new WeakSet,Aun=async function(){let n=ae(this,du,"f").params.compactionControl;if(!n||!n.enabled)return!1;let r=0;if(ae(this,Bg,"f")!==void 0)try{let c=await ae(this,Bg,"f");r=c.usage.input_tokens+(c.usage.cache_creation_input_tokens??0)+(c.usage.cache_read_input_tokens??0)+c.usage.output_tokens}catch{return!1}let o=n.contextTokenThreshold??1e5;if(r<o)return!1;let i=n.model??ae(this,du,"f").params.model,s=n.summaryPrompt??Iun,a=ae(this,du,"f").params.messages;if(a[a.length-1].role==="assistant"){let c=a[a.length-1];if(Array.isArray(c.content)){let u=c.content.filter(d=>d.type!=="tool_use");u.length===0?a.pop():c.content=u}}let l=await this.client.beta.messages.create({model:i,messages:[...a,{role:"user",content:[{type:"text",text:s}]}],max_tokens:ae(this,du,"f").params.max_tokens},{signal:ae(this,ph,"f").signal,headers:Se([ae(this,ph,"f").headers,pee("compaction")])});if(l.content[0]?.type!=="text")throw new ft("Expected text response for compaction");return ae(this,du,"f").params.messages=[{role:"user",content:l.content}],!0},Symbol.asyncIterator)](){var e;if(ae(this,OV,"f"))throw new ft("Cannot iterate over a consumed stream");qe(this,OV,!0,"f"),qe(this,FD,!0,"f"),qe(this,AT,void 0,"f");try{for(;;){let n;try{if(ae(this,du,"f").params.max_iterations&&ae(this,Mee,"f")>=ae(this,du,"f").params.max_iterations)break;qe(this,FD,!1,"f"),qe(this,AT,void 0,"f"),qe(this,Mee,(e=ae(this,Mee,"f"),e++,e),"f"),qe(this,Bg,void 0,"f");let{max_iterations:r,compactionControl:o,...i}=ae(this,du,"f").params;if(i.stream?(n=this.client.beta.messages.stream({...i},ae(this,ph,"f")),qe(this,Bg,n.finalMessage(),"f"),ae(th
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),MIr.includes(s.model)&&s.thinking&&s.thinking.type==="enabled"&&console.warn(`Using Claude with ${s.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let a=this._client._options.timeout;if(!s.stream&&a==null){let c=CSe[s.model]??void 0;a=this._client.calculateNonstreamingTimeout(s.max_tokens,c)}let l=rSe(s.tools,s.messages);return this._client.post("/v1/messages?beta=true",{body:s,timeout:a??6e5,...n,headers:Se([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0,...i!=null?{"anthropic-user-profile-id":i}:void 0},l,n?.headers]),stream:r.stream??!1})}parse(e,n){return n={...n,headers:Se([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},n?.headers])},this.create(e,n).then(r=>C7e(r,e,{logger:this._client.logger??console}))}stream(e,n){return OSe.createMessage(this,e,n)}countTokens(e,n){let r=Oun(e),{betas:o,user_profile_id:i,...s}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...n,headers:Se([{"anthropic-beta":[...o??[],"token-counting-2024-11-01"].toString(),...i!=null?{"anthropic-user-profile-id":i}:void 0},n?.headers])})}toolRunner(e,n){return new RV(this._client,e,n)}};ET.Batches=AV;ET.BetaToolRunner=RV;ET.ToolError=IT});var zD,F7e=b(()=>{ti();zi();po();ts();xSe();xSe();zD=class extends en{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(ze`/v1/sessions/${e}/events?beta=true`,Lr,{query:i,...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,n,r){let{betas:o,...i}=n;return this._client.post(ze`/v1/sessions/${e}/events?beta=true`,{body:i,...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,n={},r){let{betas:o,...i}=n??{};return this._client.get(ze`/v1/sessions/${e}/events/stream?beta=true`,{query:i,...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}toolRunner(e,n){return new bM(e,{...n,client:this._client})}};zD.SessionToolRunner=bM});var NV,z7e=b(()=>{ti();zi();po();ts();NV=class extends en{retrieve(e,n,r){let{session_id:o,betas:i}=n;return this._client.get(ze`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:Se([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.post(ze`/v1/sessions/${o}/resources/${e}?beta=true`,{body:s,...r,headers:Se([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(ze`/v1/sessions/${e}/resources?beta=true`,Lr,{query:i,...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{session_id:o,betas:i}=n;return this._client.delete(ze`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:Se([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,n,r){let{betas:o,...i}=n;return this._client.post(ze`/v1/sessions/${e}/resources?beta=true`,{body:i,...r,headers:Se([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var LV,U7e=b(()=>{ti();zi();po();ts();LV=class extends en{list(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.getAPIList(ze`/v1/sessions/${o}/threads/${e}/events?beta=true`,Lr,{query:s,...r,headers:Se([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.get(ze`/v1/sessions/${o}/threads/${e}/stream?beta=true`,{query:s,...r,headers:Se([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}}});var UD,B7e=b(()=>{ti();U7e();U7e();zi();po();ts();UD=class extends en{c
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),qIr.includes(o.model)&&o.thinking&&o.thinking.type==="enabled"&&console.warn(`Using Claude with ${o.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let i=this._client._options.timeout;if(!o.stream&&i==null){let a=CSe[o.model]??void 0;i=this._client.calculateNonstreamingTimeout(o.max_tokens,a)}let s=rSe(o.tools,o.messages);return this._client.post("/v1/messages",{body:o,timeout:i??6e5,...n,headers:Se([{...r!=null?{"anthropic-user-profile-id":r}:void 0},s,n?.headers]),stream:e.stream??!1})}parse(e,n){return this.create(e,n).then(r=>X7e(r,e,{logger:this._client.logger??console}))}stream(e,n){return zSe.createMessage(this,e,n,{logger:this._client.logger??console})}countTokens(e,n){let{user_profile_id:r,...o}=e;return this._client.post("/v1/messages/count_tokens",{body:o,...n,headers:Se([{...r!=null?{"anthropic-user-profile-id":r}:void 0},n?.headers])})}},$un={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026","claude-opus-4-1":"August 5th, 2026","claude-opus-4-1-20250805":"August 5th, 2026","claude-mythos-preview":"June 30th, 2026"},qIr=["claude-mythos-preview","claude-opus-4-6"];IM.Batches=UV});var qD,lYe=b(()=>{ti();zi();po();ts();qD=class extends en{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(ze`/v1/models/${e}`,{...r,headers:Se([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models",Rw,{query:o,...n,headers:Se([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}}});var Fun=b(()=>{Fcn();Z7e();Y7e();aYe();lYe()});var cYe,uYe,USe,zun,Uun,jun,Va,qS,dYe=b(()=>{Lg();Mxe();n_();QW();fM();Oxe();Nxe();eV();_Ze();AZe();QQ();va();nV();ccn();Pcn();Ncn();zi();KZe();Fun();Yxe();Y7e();lYe();Z7e();aYe();Oxe();po();rV();kT();n_();Uun="\\n\\nHuman:",jun="\\n\\nAssistant:",Va=class{get credentials(){return this._authState.provider}constructor({baseURL:e=fo("ANTHROPIC_BASE_URL"),apiKey:n,authToken:r,webhookKey:o=fo("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...i}={}){if(cYe.add(this),this._requestAuthFlags=new WeakMap,USe.set(this,void 0),n===void 0&&(n=i.profile!=null?null:fo("ANTHROPIC_API_KEY")??null),r===void 0&&(r=i.profile!=null?null:fo("ANTHROPIC_AUTH_TOKEN")??null),i.profile!=null&&(i.credentials!=null||i.config!=null))throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let s={apiKey:n,authToken:r,webhookKey:o,...i,baseURL:e||"https://api.anthropic.com"};if(!s.dangerouslyAllowBrowser&&zln())throw new ft(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);this.baseURL=s.baseURL,this._baseURLIsExplicit=i.__baseURLIsExplicit??!!e,this.timeout=s.timeout??uYe.DEFAULT_TIMEOUT,this.logger=s.logger??console,this.logLevel=oee,this.logLevel=qxe(s.logLevel,"ClientOptions.logLevel",pi(this))??qxe(fo("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",pi(this))??oee,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Hln(),qe(this,USe,Vln,"f"),this.middleware=[...s.middleware??[]];let a=fo("ANTHROPIC_CUSTOM_HEADERS");if(a){let c={};for(let u of a.split(`
`)){let d=u.indexOf(":");d>=0&&(c[u.substring(0,d).trim()]=u.substring(d+1).trim())}s.defaultHeaders={...c,...s.defaultHeaders}}let l=i.__auth;if(delete s.__auth,delete s.__baseURLIsExplicit,this._options=s,this.apiKey=typeof n=="string"?n:null,this.authToken=r,this.webhookKey=o,l)this._authState=l,!this._baseURLIsExplicit&&l.baseURL&&(this.baseURL=l.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let c=s.credentials??null;if(c)this._authState.provider=c,this._authState.tokenCache=this._makeTokenCache(c);else if(s.config!=null){let u=FZe(s.config,this._credentialResolverOptions());this._authState.provider=u.provider,this._authState.tokenCache=this._makeTokenCache(u.provider),this._authState.extraHeaders=u.extraHeaders,this._applyCredentialBaseURL(u.baseURL)}else s.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(s.profile):this._shouldResolveDefaultCredentials()&&(this._authState.resolution=this._resolveDefaultCredentials())}}_shouldResolveDefaultCredentials(){return!0}_applyCredentialBaseURL(e){if(!e)return;let n=e.replace(/\/+$/,"");this._authState.baseURL=n,this._baseURLIsExplicit||(this.baseURL=n)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:e=>{pi(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{pi(this).warn(e)}}}_credentialsFetch(){return jZe(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new jxe(e,n=>{pi(this).debug("advisory token refresh failed; serving cached token",n)})}withOptions(e){let n="credentials"in e||"config"in e||"profile"in e,r="apiKey"in e||"authToken"in e||n,o={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...n?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:r?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(o)}async _resolveDefaultCredentials(e){try{let n=await Icn(this._credentialResolverOptions(),e);if(n)this._authState.provider=n.provider,this._authState.tokenCache=this._makeTokenCache(n.provider),this._authState.extraHeaders=n.extraHeaders,this._applyCredentialBaseURL(n.baseURL);else if(e!=null)throw new ft(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(n){this._authState.error=n}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.get("x-api-key")||e.get("authorization"))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}}_authFlags(e){let n=this._requestAuthFlags.get(e);return n||(n={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,n)),n}async authHeaders(e){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){let n=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,Se([{Authorization:`Bearer ${n}`}])}return Se([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return Se([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return Se([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return ncn(e)}getUserAgent(){return`${this.co
`,t}var Ldn=b(()=>{});function Mn(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n}function Ce(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}var zw=b(()=>{});var YD,jee=b(()=>{YD=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return YD=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))}});function Hee(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Wee,HSe=b(()=>{Wee=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var ht,yl,qa,AM,YS,WV,VV,qV,KV,GV,ZV,YV,JV,XV,QV,JS,JD,Vee,Uw=b(()=>{HSe();ht=class extends Error{},yl=class t extends ht{constructor(e,n,r,o){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=n;let i=n;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new AM({message:r,cause:Wee(n)});let i=n?.error;return e===400?new WV(e,i,r,o):e===401?new VV(e,i,r,o):e===403?new qV(e,i,r,o):e===404?new KV(e,i,r,o):e===409?new GV(e,i,r,o):e===422?new ZV(e,i,r,o):e===429?new YV(e,i,r,o):e>=500?new JV(e,i,r,o):new t(e,i,r,o)}},qa=class extends yl{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},AM=class extends yl{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},YS=class extends AM{constructor({message:e}={}){super({message:e??"Request timed out."})}},WV=class extends yl{},VV=class extends yl{},qV=class extends yl{},KV=class extends yl{},GV=class extends yl{},ZV=class extends yl{},YV=class extends yl{},JV=class extends yl{},XV=class extends ht{constructor(){super("Could not parse response content as the length limit was reached")}},QV=class extends ht{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},JS=class extends Error{constructor(e){super(e)}},JD=class extends yl{constructor(e,n,r){let o="OAuth2 authentication error",i;if(n&&typeof n=="object"){let s=n;i=s.error;let a=s.error_description;a&&typeof a=="string"?o=a:i&&(o=i)}super(e,n,o,r),this.error_code=i}},Vee=class extends ht{constructor(e,n,r){super(e),this.provider=n,this.cause=r}}});function WSe(t){return typeof t!="object"?{}:t??{}}function vYe(t){if(!t)return!0;for(let e in t)return!1;return!0}function $dn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function qee(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var KPr,Ddn,Qf,wYe,Fdn,zdn,LT=b(()=>{Uw();KPr=/^[a-z][a-z0-9+.-]*:/i,Ddn=t=>KPr.test(t),Qf=t=>(Qf=Array.isArray,Qf(t)),wYe=Qf;Fdn=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ht(`${t} must be an integer`);if(e<0)throw new ht(`${t} must be a positive integer`);return e},zdn=t=>{try{return JSON.parse(t)}catch{return}}});var XS,e6=b(()=>{XS=t=>new Promise(e=
`,"\r"]);XD.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Zee(){}function GSe(t,e,n){return!e||ZSe[t]>ZSe[n]?Zee:e[t].bind(e)}function Rl(t){let e=t.logger,n=t.logLevel??"off";if(!e)return nAr;let r=ufn.get(e);if(r&&r[0]===n)return r[1];let o={error:GSe("error",e,n),warn:GSe("warn",e,n),info:GSe("info",e,n),debug:GSe("debug",e,n)};return ufn.set(e,[n,o]),o}var ZSe,RYe,nAr,ufn,DT,Yee=b(()=>{LT();ZSe={off:0,error:200,warn:300,info:400,debug:500},RYe=(t,e,n)=>{if(t){if($dn(ZSe,t))return t;Rl(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(ZSe))}`)}};nAr={error:Zee,warn:Zee,info:Zee,debug:Zee},ufn=new WeakMap;DT=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*rAr(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ht("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ht("Attempted to iterate over a response with no body");let n=new NYe,r=new XD,o=qSe(t.body);for await(let i of oAr(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*oAr(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?jg(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=lfn(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function iAr(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var Jee,mh,NYe,LYe=b(()=>{zw();Uw();t6();cfn();t6();HSe();Gee();Yee();Uw();mh=class t{constructor(e,n,r){this.iterator=e,Jee.set(this,void 0),this.controller=n,Mn(this,Jee,r,"f")}static fromSSEResponse(e,n,r,o){let i=!1,s=r?Rl(r):console;async function*a(){if(i)throw new ht("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let l=!1;try{for await(let c of rAr(e,n))if(!l){if(c.data.startsWith("[DONE]")){l=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let u;try{u=JSON.parse(c.data)}catch(d){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),d}if(u&&u.error)throw new yl(void 0,u.error,void 0,e.headers);yield o?{event:c.event,data:u}:u}else{let u;try{u=JSON.parse(c.data)}catch(d){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),d}if(c.event=="error")throw new yl(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}l=!0}catch(c){if(Hee(c))return;throw c}finally{l||n.abort()}}return new t(a,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new XD,l=e.getReader(),c=!1,u,d=()=>{u??(u=l.cancel()),u.catch(()=>{})};n.signal.addEventListener("abort",d,{once:!0});try{if(n.signal.aborted){d();return}for(;;){let{value:f,done:p}=await l.read();if(p){c=!0;break}if(n.signal.aborted)return;for(let m of a.decode(f)){if(n.signal.aborted)return;yield m}}if(n.signal.aborted)return;for(let f of a.flush()){if(n.signal.aborted)return;yield f}}finally{n.signal.removeEventListener("abort",d),c||d(),l.releaseLock()}}async function*s(){if(o)throw new ht("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(n.signal.aborted||Hee(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}[(Jee=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=
`)}async function*pAr(t){if(!(!t||typeof t!="object"))for(let[e,n]of Object.entries(t))yield*UYe(e,n)}async function*UYe(t,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||WYe(e))yield{key:t,value:e};else if(Array.isArray(e))for(let n of e)yield*UYe(t+"[]",n);else if(typeof e=="object")for(let[n,r]of Object.entries(e))yield*UYe(`${t}[${n}]`,r);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function mAr(t){return ete(t)?t.name:o6(t)??"unknown_file"}function hAr(t){return ete(t)?t.type||"application/octet-stream":nCe(t)&&t.type?t.type:t instanceof Response&&t.headers.get("content-type")||"application/octet-stream"}function gAr(t){return ete(t)?t.data:t}async function*r6(t){if(typeof t=="string")yield jg(t);else if(ArrayBuffer.isView(t))yield new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof ArrayBuffer)yield new Uint8Array(t);else if(t instanceof Response)t.body?yield*r6(t.body):yield*r6(await t.blob());else if(t instanceof Blob)typeof t.stream=="function"?yield*r6(t.stream()):yield new Uint8Array(await t.arrayBuffer());else if(HYe(t))for await(let e of qSe(t))yield*r6(e);else if(s6(t))for await(let e of t)yield*r6(e);else throw new TypeError(`Invalid streaming file chunk: ${String(t)}`)}function FYe(t){return t.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}var mfn,jYe,s6,MM,tp,pfn,hfn,nCe,HYe,ete,WYe,eCe,zYe,gfn,BYe,Vg=b(()=>{Pi();t6();Gee();mfn=Symbol("brand.privateStreamingFile");jYe=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};s6=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",MM=async(t,e)=>zYe(t.body)?eCe(t.body)?gfn(t):{...t,body:await hfn(t.body,e)}:t,tp=async(t,e)=>eCe(t.body)?gfn(t):{...t,body:await hfn(t.body,e)},pfn=new WeakMap;hfn=async(t,e)=>{if(!await dAr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,o])=>BYe(n,r,o))),n},nCe=t=>t instanceof Blob&&"name"in t,HYe=t=>typeof t=="object"&&t!==null&&"getReader"in t&&typeof t.getReader=="function",ete=t=>typeof t=="object"&&t!==null&&mfn in t,WYe=t=>typeof t=="object"&&t!==null&&(t instanceof Response||s6(t)||HYe(t)||ete(t)||nCe(t)),eCe=t=>{if(ete(t)||s6(t)||HYe(t))return!0;if(Array.isArray(t))return t.some(eCe);if(t&&typeof t=="object"&&!nCe(t)&&!(t instanceof Response)){for(let e in t)if(eCe(t[e]))return!0}return!1},zYe=t=>{if(WYe(t))return!0;if(Array.isArray(t))return t.some(zYe);if(t&&typeof t=="object"){for(let e in t)if(zYe(t[e]))return!0}return!1},gfn=t=>{let e=`openai-${Math.random().toString(36).slice(2)}`,n=Kee(fAr(t.body,e));return{...t,body:n,headers:Ze([{"content-type":`multipart/form-data; boundary=${e}`},t.headers])}};BYe=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,i6([await n.blob()],o6(n)));else if(s6(n))t.append(e,i6([await new Response(Kee(n)).blob()],o6(n)));else if(nCe(n))t.append(e,n,o6(n));else if(Array.isArray(n))await Promise.all(n.map(r=>BYe(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,o])=>BYe(t,`${e}[${r}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}});async function tte(t,e,n){if(jYe(),t=await t,yAr(t))return t instanceof File?t:i6([await t.arrayBuffer()],t.n
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},pe=_Ar(bfn)});var e$,rCe=b(()=>{st();Gn();rn();e$=class extends be{list(e,n={},r){return this._client.getAPIList(pe`/chat/completions/${e}/messages`,ar,{query:n,...r,__security:{bearerAuth:!0}})}}});var hh=b(()=>{Uw()});function nte(t){return t!==void 0&&"function"in t&&t.function!==void 0}function xfn(t,e){let n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function rte(t){return t?.$brand==="auto-parseable-response-format"}function t$(t){return t?.$brand==="auto-parseable-tool"}function Sfn(t,e){return!e||!KYe(e)?{...t,choices:t.choices.map(n=>(kfn(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:ote(t,e)}function ote(t,e){let n=t.choices.map(r=>{if(r.finish_reason==="length")throw new XV;if(r.finish_reason==="content_filter")throw new QV;return kfn(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(o=>CAr(e,o))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?SAr(e,r.message.content):null}}});return{...t,choices:n}}function SAr(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function CAr(t,e){let n=t.tools?.find(r=>nte(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:t$(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function Cfn(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let n=t.tools?.find(r=>nte(r)&&r.function?.name===e.function.name);return nte(n)&&(t$(n)||n?.function.strict||!1)}function KYe(t){return rte(t.response_format)?!0:t.tools?.some(e=>t$(e)||e.type==="function"&&e.function.strict===!0)??!1}function kfn(t){for(let e of t||[])if(e.type!=="function")throw new ht(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Tfn(t){for(let e of t??[]){if(e.type!=="function")throw new ht(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new ht(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var a6=b(()=>{hh()});var $T,ite,oCe=b(()=>{$T=t=>t?.role==="assistant",ite=t=>t?.role==="tool"});var ste,iCe,sCe,ate,lte,aCe,cte,FT,lCe,ute,cCe,uCe,l6,Ifn,GYe,OM,dCe=b(()=>{zw();hh();OM=class{constructor(){ste.add(this),this.controller=new AbortController,iCe.set(this,void 0),sCe.set(this,()=>{}),ate.set(this,()=>{}),lte.set(this,void 0),aCe.set(this,()=>{}),cte.set(this,()=>{}),FT.set(this,{}),lCe.set(this,[]),ute.set(this,!1),cCe.set(this,!1),uCe.set(this,!1),l6.set(this,!1),Mn(this,iCe,new Promise((e,n)=>{Mn(this,sCe,e,"f"),Mn(this,ate,n,"f")}),"f"),Mn(this,lte,new Promise((e,n)=>{Mn(this,aCe,e,"f"),Mn(this,cte,n,"f")}),"f"),Ce(this,iCe,"f").catch(()=>{}),Ce(this,lte,"f").catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(n){Ce(this,ste,"m",GYe).call(this,n);return}this._emit("end")},Ce(this,ste,"m",GYe).bind(this))},0)}_connected(){this.ended||(Ce(this,sCe,"f").call(this),this._emit("connect"))}get ended(){return Ce(this,ute,"f")}get errored(){return Ce(this,cCe,"f")}get aborted(){return Ce(this,uCe,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let n=()=>this.controller.abort();e.addEventListener("abort",n,{once:!0}),Ce(this,lCe,"f").push({signal:e,listener:n})}on(e,n){return(Ce(this,FT,"f")[e]||(Ce(this,FT,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=Ce(this,FT,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(Ce(this,FT,"f")[e]||(Ce(this,FT,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Mn(this,l6,!0,"f"),e!=="error"&&this.once("error",r
\r `.includes(t[r]);)r++};return s()},oJe=t=>PAr(t,qu.ALL^qu.NUM)});var fte=b(()=>{LYe()});function Rfn(t,e,n){let r={type:"message",message:e,...n?{tool_call_ids:n}:{}};return{id:t.id,choices:[],created:t.created,model:t.model,object:`${dJe}${JSON.stringify(r)}`}}function EAr(t){return"type"in t&&t.type==="message"&&"message"in t||"object"in t&&typeof t.object=="string"&&t.object.startsWith(dJe)}function MAr(t){return"type"in t?t:JSON.parse(t.object.slice(dJe.length))}function OAr(t,e,n){let{id:r,choices:o,created:i,model:s,system_fingerprint:a,...l}=t,c={...l,id:r,choices:o.map(({message:u,finish_reason:d,index:f,logprobs:p,...m})=>{let{content:h=null,function_call:g,tool_calls:w,audio:y,...v}=u,_=d??(n.has(f)&&RAr(y)?"stop":null);if(!_)throw new ht(`missing finish_reason for choice ${f}`);let S=y?{audio:y}:{},k=u.role;if(!k)throw new ht(`missing role for choice ${f}`);if(g){let{arguments:x,name:C}=g;if(x==null)throw new ht(`missing function_call.arguments for choice ${f}`);if(!C)throw new ht(`missing function_call.name for choice ${f}`);return{...m,message:{...S,content:h,function_call:{arguments:x,name:C},role:k,refusal:u.refusal??null},finish_reason:_,index:f,logprobs:p}}return w?{...m,index:f,finish_reason:_,logprobs:p,message:{...v,...S,role:k,content:h,refusal:u.refusal??null,tool_calls:w.map((x,C)=>{let{function:T,type:I,id:M,...O}=x,{arguments:D,name:F,...q}=T||{};if(I==null)throw new ht(`missing choices[${f}].tool_calls[${C}].type
${uJe(t)}`);if(F==null)throw new ht(`missing choices[${f}].tool_calls[${C}].function.name
${uJe(t)}`);if(D==null)throw new ht(`missing choices[${f}].tool_calls[${C}].function.arguments
${uJe(t)}`);return{...O,id:M||`call_${YD()}`,type:I,function:{...q,name:F,arguments:D}}})}}:{...m,message:{...v,...S,content:h,role:k,refusal:u.refusal??null},finish_reason:_,index:f,logprobs:p}}),created:i,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Sfn(c,e)}function RAr(t){return t?.id!=null&&t.data!=null&&t.transcript!=null&&t.expires_at!=null}function uJe(t){return JSON.stringify(t)}var sc,zT,RM,u6,l_,iJe,pCe,sJe,aJe,lJe,pte,cJe,Ofn,dJe,n$,mCe=b(()=>{zw();Mfn();hh();jee();a6();fte();eJe();dJe="chat.completion.chunk.message:";n$=class t extends c6{constructor(e){super(),sc.add(this),zT.set(this,void 0),RM.set(this,void 0),u6.set(this,void 0),l_.set(this,void 0),Mn(this,zT,e,"f"),Mn(this,RM,new Set,"f"),Mn(this,u6,[],"f")}get currentChatCompletionSnapshot(){return Ce(this,l_,"f")}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){let o=new t(n);return o._run(()=>o._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,n,r){super._createChatCompletion,this._listenForAbort(r?.signal),Ce(this,sc,"m",iJe).call(this);let o=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)Ce(this,sc,"m",sJe).call(this,i);if(o.controller.signal?.aborted)throw new qa;return this._addChatCompletion(Ce(this,sc,"m",pte).call(this))}async _fromReadableStream(e,n){this._listenForAbort(n?.signal),Ce(this,sc,"m",iJe).call(this),this._connected();let r=mh.fromReadableStream(e,this.controller),o;for await(let s of r){if(EAr(s)){let l=MAr(s);if(Ce(this,l_,"f")){let c=Ce(this,l_,"f").choices[0]?.message.tool_calls;for(let[u,d]of l.tool_call_ids?.entries()??[]){let f=c?.[u];f&&d&&(f.id=d)}this._addChatCompletion(Ce(this,sc,"m",pte).call(this)),o=void 0}this._addMessage(l.message);continue}let a=s;o&&a.id&&o!==a.id&&this._addChatCompletion(Ce(this,sc,"m",pte).call(this)),Ce(this,sc,"m",sJe).call(this,a),a.id&&(o=a.id)}if(r.controller.signal?.aborted)throw new qa;if(Ce(this,l_,"f"))return this._addChatCompletion(Ce(this,sc,"m",pte).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new ht("request ended without sending any chunks")}[(zT=new WeakMap,RM=new WeakMap,u6=new WeakMap,l_=new WeakMap,sc=new WeakSet,iJe=function(){this.ended||(Mn(this,RM,new Set,"f"),Mn(this,l_,void 0,"f"))},pCe=function(n){let r=Ce(this,u6,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Ce(this,u6,"f")[n.index]=r,r)},sJe=function(n){if(this.ended)return;let r=Ce(this,sc,"m",Ofn).call(this,n);this._emit("chunk",n,r);for(let o of n.choices){let i=r.choices[o.index],{delta:s}=o;s?.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",s.content,i.message.content),this._emit("content.delta",{delta:s.content,snapshot:i.message.content,parsed:i.message.parsed})),s?.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:s.refusal,snapshot:i.message.refusal}),o.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:i.logprobs?.content??[]}),o.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});let a=Ce(this,sc,"m",pCe).call(this,i);i.finish_reason&&(Ce(this,sc,"m",lJe).call(this,i),a.current_tool_call_index!=null&&Ce(this,sc,"m",aJe).call(this,i,a.current_tool_call_index));for(let l of s?.tool_calls??[])a.current_tool_call_index!==l.index&&(Ce(this,sc,"m",lJe).call(this,i),a.current_tool_call_index!=null&&Ce(this,sc,"m",aJe).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=l.index;for(let l of s?.tool_calls??[]){let c=i.message.tool_calls?.[l.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.f
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
`);this.baseURL=f.baseURL,this.timeout=f.timeout??lQe.DEFAULT_TIMEOUT,this.logger=f.logger??console;let p="warn";this.logLevel=p,this.logLevel=RYe(f.logLevel,"ClientOptions.logLevel",this)??RYe(c_("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??p,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??VSe(),Mn(this,vte,qdn,"f");let m=n?void 0:c_("OPENAI_CUSTOM_HEADERS");if(m){let h={};for(let g of m.split(`
`)){let w=g.indexOf(":");w>=0&&(h[g.substring(0,w).trim()]=g.substring(w+1).trim())}f.defaultHeaders=Ze([h,f.defaultHeaders])}this._options=f,this._provider=d,c&&(this._workloadIdentityAuth=new QSe(c,this.fetch)),this.apiKey=typeof o=="string"?o:null,this.adminAPIKey=i,this.organization=s,this.project=a,this.webhookSecret=l}withOptions(e){let n=this._options.provider,r=e.provider??n,o={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return r&&(delete o.apiKey,delete o.adminAPIKey,delete o.workloadIdentity,delete o.baseURL,r!==n&&(delete o.organization,delete o.project,delete o.defaultHeaders)),new this.constructor({...o,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(n.has("authorization")||n.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,n={bearerAuth:!0,adminAPIKeyAuth:!0}){return Ze([n.bearerAuth?await this.bearerAuth(e):null,n.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return Ze([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return Ze([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return Ze([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return ofn(e)}getUserAgent(){return`${this.constructor.name}/JS ${EM}`}defaultIdempotencyKey(){return`stainless-node-retry-${YD()}`}makeStatusError(e,n,r,o){return yl.generate(e,n,r,o)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(r){throw r instanceof ht?r:new ht(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new ht(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,r){let o=!Ce(this,aQe,"m",dpn).call(this)&&r||this.baseURL,i=Ddn(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!vYe(s)||!vYe(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new QD(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n}),c=o.__metadata?.hasStreamingBody===!0;await this.prepareRequest(s,{url:a,options:o}),await this._provider?.prepareRequest?.(s,{url:a,options:o});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=r===void 0?"":`, retryOf: ${r}`,f=Date.now();if(Rl(this).debug(`[${u}] sending request`,DT({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new qa;let p=o.__security??{bearerAuth:!0},m=new AbortController,h=await this.fetchWithAuth(a,s,l,m,p).catch
]`;continue}i+=o[c],o[c]==="\\"?s=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{let c=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return i}});function ECe(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===Me.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:rr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let n={type:"object",additionalProperties:rr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===Me.ZodString&&t.keyType._def.checks?.length){let r=Object.entries(PCe(t.keyType._def,e)).reduce((o,[i,s])=>i==="type"?o:{...o,[i]:s},{});return{...n,propertyNames:r}}else if(t.keyType?._def.typeName===Me.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}var MCe=b(()=>{RS();ac();ACe()});function Vpn(t,e){if(e.mapStrategy==="record")return ECe(t,e);let n=rr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=rr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var PQe=b(()=>{ac();MCe()});function qpn(t){let e=t.values,r=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(r.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var AQe=b(()=>{});function Kpn(){return{not:{}}}var EQe=b(()=>{});function Gpn(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var MQe=b(()=>{});function Ypn(t,e){if(e.target==="openApi3")return Zpn(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in xte&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,i)=>{let s=xte[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){let o=r.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(i=>!r.includes(i))],[])};return Zpn(t,e)}var xte,Zpn,OCe=b(()=>{ac();xte={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Zpn=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>rr(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function Jpn(t,e,n){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:xte[t.innerType._def.typeName],nullable:!0}:{type:[xte[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=rr(t.innerType._def,{...e,currentPath:[...e.currentPath]},n);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let r=rr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var OQe=b(()=>{ac();OCe()});function Xpn(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",pQe(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclus
`+s.executableCode.code+"\n```\n"),s.codeExecutionResult&&i.push("\n```\n"+s.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function Phn(t){var e,n,r,o;let i=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(let s of(o=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||o===void 0?void 0:o.parts)s.functionCall&&i.push(s.functionCall);if(i.length>0)return i}function JCe(t){return!!t.finishReason&&jOr.includes(t.finishReason)}function nO(t){var e,n,r;let o="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)o+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(o+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(o+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((r=t.candidates)===null||r===void 0)&&r[0]){let i=t.candidates[0];JCe(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function Rte(t){return this instanceof Rte?(this.v=t,this):new Rte(t)}function HOr(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,i=[];return o={},s("next"),s("throw"),s("return"),o[Symbol.asyncIterator]=function(){return this},o;function s(f){r[f]&&(o[f]=function(p){return new Promise(function(m,h){i.push([f,p,m,h])>1||a(f,p)})})}function a(f,p){try{l(r[f](p))}catch(m){d(i[0][3],m)}}function l(f){f.value instanceof Rte?Promise.resolve(f.value.v).then(c,u):d(i[0][2],f)}function c(f){a("next",f)}function u(f){a("throw",f)}function d(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function WOr(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=KOr(e),[r,o]=n.tee();return{stream:qOr(r),response:VOr(o)}}async function VOr(t){let e=[],n=t.getReader();for(;;){let{done:r,value:o}=await n.read();if(r)return wet(GOr(e));e.push(o)}}function qOr(t){return HOr(this,arguments,function*(){let n=t.getReader();for(;;){let{value:r,done:o}=yield Rte(n.read());if(o)break;yield yield Rte(wet(r))}})}function KOr(t){let e=t.getReader();return new ReadableStream({start(r){let o="";return i();function i(){return e.read().then(({value:s,done:a})=>{if(a){if(o.trim()){r.error(new Zu("Failed to parse stream"));return}r.close();return}o+=s;let l=o.match(Ahn),c;for(;l;){try{c=JSON.parse(l[1])}catch{r.error(new Zu(`Error parsing JSON response: "${l[1]}"`));return}r.enqueue(c),o=o.substring(l[0].length),l=o.match(Ahn)}return i()}).catch(s=>{let a=s;throw a.stack=s.stack,a.name==="AbortError"?a=new QCe("Request aborted when reading from the stream"):a=new Zu("Error reading from the stream"),a})}}})}function GOr(t){let e=t[t.length-1],n={promptFeedback:e?.promptFeedback};for(let r of t){if(r.candidates){let o=0;for(let i of r.candidates)if(n.candidates||(n.candidates=[]),n.candidates[o]||(n.candidates[o]={index:o}),n.candidates[o].citationMetadata=i.citationMetadata,n.candidates[o].groundingMetadata=i.groundingMetadata,n.candidates[o].finishReason=i.finishReason,n.candidates[o].finishMessage=i.finishMessage,n.candidates[o].safetyRatings=i.safetyRatings,i.content&&i.content.parts){n.candidates[o].content||(n.candidates[o].content={role:i.content.role||"user",parts:[]});let s={};for(let a of i.content.parts)a.text&&(s.text=a.text),a.functionCall&&(s.functionCall=a.functionCall),a.executableCode&&(s.executableCode=a.executableCode),a.codeExecutionResult&&(s.codeExecutionResult=a.codeExecutionResult),Object.keys(s).length===0&&(s.text=""),n.candidates[o].content.parts.push(s)}o++}r.usageMetadata&&(n.usageMetadata=r.usageMetadata)}return n}async function Nhn(t,e,n,r){let o=await Lte(e,F$.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),r);return WOr(o)}async function Lhn(t,e,n,r){let i=await(await Lte(e,F$.GENERATE_CONTENT,t,!1,JSON.stringify(n),r)).json();return{response:wet(i)}}function Dhn(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role
`,"\r"]);V$.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Hte(){}function a0e(t,e,n){return!e||l0e[t]>l0e[n]?Hte:e[t].bind(e)}function Wd(t){let e=t.logger,n=t.logLevel??"off";if(!e)return ERr;let r=kgn.get(e);if(r&&r[0]===n)return r[1];let o={error:a0e("error",e,n),warn:a0e("warn",e,n),info:a0e("info",e,n),debug:a0e("debug",e,n)};return kgn.set(e,[n,o]),o}var l0e,Get,ERr,kgn,ZT,c0e=b(()=>{zte();l0e={off:0,error:200,warn:300,info:400,debug:500},Get=(t,e,n)=>{if(t){if(Yhn(l0e,t))return t;Wd(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(l0e))}`)}};ERr={error:Hte,warn:Hte,info:Hte,debug:Hte},kgn=new WeakMap;ZT=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*MRr(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new lc("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new lc("Attempted to iterate over a response with no body");let n=new Zet,r=new V$,o=Aet(t.body);for await(let i of ORr(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*ORr(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?jte(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=Sgn(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function RRr(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var Wte,u0e,Zet,Tgn=b(()=>{Dte();iO();Ute();Cgn();Ute();n0e();Ket();c0e();iO();u0e=class t{constructor(e,n,r){this.iterator=e,Wte.set(this,void 0),this.controller=n,Gp(this,Wte,r,"f")}static fromSSEResponse(e,n,r){let o=!1,i=r?Wd(r):console;async function*s(){if(o)throw new lc("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of MRr(e,n))if(!a){if(l.data.startsWith("[DONE]")){a=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(c&&c.error)throw new pu(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(l.data)}catch(u){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),u}if(l.event=="error")throw new pu(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}a=!0}catch(l){if($te(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new V$,l=Aet(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new lc("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if($te(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}[(Wte=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller,ea(this,Wte,"f")),new t(()=>o(n),this.controller,ea(this,Wte,"f"))]}toReadableStream(){let e=this,n;return Pet({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:o,done:i}=await n.next();if(i)return r.close();let s=jte(JSON.stringify(o)+`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=RRr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}}});async function Ign(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(n.status===204)return null;if(e.options.__binaryResponse)return n;if(e.options.stream)return u0e.fromSSEResponse(n,e.controller,t);let l=n.headers.get("content-type")?.split(";")[0]?.trim();return l?.includes("application/json")||l?.endsWith("+json")?n.headers.get("content-length")==="0"?void 0:await n.json():await n.text()})();return Wd(t).debug(`[${r}] response parsed`,ZT({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}var Pgn=b(()=>{Tgn();c0e()});var Vte,qte,Yet=b(()=>{Dte();Pgn();qte=class t extends Promise{constructor(e,n,r=Ign){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,Vte.set(this,void 0),Gp(this,Vte,e,"f")}_thenUnwrap(e){return new t(ea(this,Vte,"f"),this.responsePromise,async(n,r)=>e(await this.parseResponse(n,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(ea(this,Vte,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Vte=new WeakMap});var Kte,Agn=b(()=>{Kte=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0}});var Jet,Xet,Gte,Egn,Ui,Qet=b(()=>{Dte();Ghn();zte();egn();n0e();Iet();Ute();cgn();dgn();Tet();iO();Net();vgn();Yet();zet();jet();Het();Wet();Vet();Fet();Bet();Iet();i0e();Agn();c0e();zte();Ui=class{constructor({baseURL:e=Kte("GROQ_BASE_URL"),apiKey:n=Kte("GROQ_API_KEY"),...r}={}){if(Jet.add(this),Gte.set(this,void 0),this.completions=new B$(this),this.chat=new aO(this),this.embeddings=new j$(this),this.audio=new oC(this),this.models=new W$(this),this.batches=new U$(this),this.files=new H$(this),n===void 0)throw new lc("The GROQ_API_KEY environment variable is missing or empty; either provide it, or instantiate the Groq client with an apiKey option, like new Groq({ apiKey: 'My API Key' }).");let o={apiKey:n,...r,baseURL:e||"https://api.groq.com"};if(!o.dangerouslyAllowBrowser&&ogn())throw new lc(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Groq({ apiKey, dangerouslyAllowBrowser: true })`);this.baseURL=o.baseURL,this.timeout=o.timeout??Xet.DEFAULT_TIMEOUT,this.logger=o.logger??console;let i="warn";this.logLevel=i,this.logLevel=Get(o.logLevel,"ClientOptions.logLevel",this)??Get(Kte("GROQ_LOG"),"process.env['GROQ_LOG']",this)??i,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??sgn(),Gp(this,Gte,lgn,"f");let s=Kte("GROQ_CUSTOM_HEADERS");if(s){let a={};for(let l of s.split(`
`)){let c=l.indexOf(":");c>=0&&(a[l.substring(0,c).trim()]=l.substring(c+1).trim())}o.defaultHeaders={...a,...o.defaultHeaders}}this._options=o,this.apiKey=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){}async authHeaders(e){return GT([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return ugn(e)}getUserAgent(){return`${this.constructor.name}/JS ${sO}`}defaultIdempotencyKey(){return`stainless-node-retry-${_et()}`}makeStatusError(e,n,r,o){return pu.generate(e,n,r,o)}buildURL(e,n,r){let o=!ea(this,Jet,"m",Egn).call(this)&&r||this.baseURL,i=Zhn(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!ket(s)||!ket(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new qte(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n});await this.prepareRequest(s,{url:a,options:o});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Wd(this).debug(`[${c}] sending request`,ZT({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new z$;let f=new AbortController,p=await this.fetchWithTimeout(a,s,l,f).catch(Fte),m=Date.now();if(p instanceof globalThis.Error){let g=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new z$;let w=$te(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(n)return Wd(this).info(`[${c}] connection ${w?"timed out":"failed"} - ${g}`),Wd(this).debug(`[${c}] connection ${w?"timed out":"failed"} (${g})`,ZT({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),this.retryRequest(o,n,r??c);throw Wd(this).info(`[${c}] connection ${w?"timed out":"failed"} - error; no more retries left`),Wd(this).debug(`[${c}] connection ${w?"timed out":"failed"} (error; no more retries left)`,ZT({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),w?new T3:new oO({cause:p})}let h=`[${c}${u}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let g=await this.shouldRetry(p);if(n&&g){let k=`retrying, ${n} attempts remaining`;return await agn(p.body),Wd(this).info(`${h} - ${k}`),Wd(this).debug(`[${c}] response error (${k})`,ZT({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),this.retryRequest(o,n,r??c,p.headers)}let w=g?"error; no more retries left":"error; not retryable";Wd(this).info(`${h} - ${w}`);let y=await p.text().catch(k=>Fte(k).message),v=Xhn(y),_=v?void 0:y;throw Wd(this).debug(`[${c}] response error (${w})`,ZT({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:_,durationMs:Date.now()-d})),this.makeStatusError(p.status,v,_,p.headers)}return Wd(this).info(h),Wd(this).debug(`[${c}] response start`,ZT({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),{response:p,options:o,controller:f,requestLogID:c,retryOfRequestLogID:r,startTime:d}}async fetchWithTimeout(e,n,r,o){let{signal:i,method:s,...a}=n||{},l=this._makeAbort(o);i&&i.addEventListener("abort",l,{once:!0});let c=setTimeout(l,r),u=globalThis.ReadableStream&&a.
`)===0?r.substr(1,r.length):r}).forEach(function(r){var o=r.split(":"),i=o.shift().trim();if(i){var s=o.join(":").trim();try{e.append(i,s)}catch(a){console.warn("Response "+a.message)}}}),e}function sC(t,e){if(!(this instanceof sC))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new mu(e.headers),this.url=e.url||"",this._initBody(t)}function Vgn(t,e){return new Promise(function(n,r){var o=new K$(t,e);if(o.signal&&o.signal.aborted)return r(new q$("Aborted","AbortError"));var i=new XMLHttpRequest;function s(){i.abort()}i.onload=function(){var c={statusText:i.statusText,headers:QRr(i.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(i.status<200||i.status>599)?c.status=200:c.status=i.status,c.url="responseURL"in i?i.responseURL:c.headers.get("X-Request-URL");var u="response"in i?i.response:i.responseText;setTimeout(function(){n(new sC(u,c))},0)},i.onerror=function(){setTimeout(function(){r(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){r(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){r(new q$("Aborted","AbortError"))},0)};function a(c){try{return c===""&&Vd.location.href?Vd.location.href:c}catch{return c}}if(i.open(o.method,a(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(Zp.blob?i.responseType="blob":Zp.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof mu||Vd.Headers&&e.headers instanceof Vd.Headers)){var l=[];Object.getOwnPropertyNames(e.headers).forEach(function(c){l.push(j3(c)),i.setRequestHeader(c,ott(e.headers[c]))}),o.headers.forEach(function(c,u){l.indexOf(u)===-1&&i.setRequestHeader(u,c)})}else o.headers.forEach(function(c,u){i.setRequestHeader(u,c)});o.signal&&(o.signal.addEventListener("abort",s),i.onreadystatechange=function(){i.readyState===4&&o.signal.removeEventListener("abort",s)}),i.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}var Vd,Zp,Ugn,jgn,YRr,eNr,q$,qgn=b(()=>{Vd=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},Zp={searchParams:"URLSearchParams"in Vd,iterable:"Symbol"in Vd&&"iterator"in Symbol,blob:"FileReader"in Vd&&"Blob"in Vd&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Vd,arrayBuffer:"ArrayBuffer"in Vd};Zp.arrayBuffer&&(Ugn=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],jgn=ArrayBuffer.isView||function(t){return t&&Ugn.indexOf(Object.prototype.toString.call(t))>-1});mu.prototype.append=function(t,e){t=j3(t),e=ott(e);var n=this.map[t];this.map[t]=n?n+", "+e:e};mu.prototype.delete=function(t){delete this.map[j3(t)]};mu.prototype.get=function(t){return t=j3(t),this.has(t)?this.map[t]:null};mu.prototype.has=function(t){return this.map.hasOwnProperty(j3(t))};mu.prototype.set=function(t,e){this.map[j3(t)]=ott(e)};mu.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)};mu.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),itt(t)};mu.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),itt(t)};mu.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),itt(t)};Zp.iterable&&(mu.prototype[Symbol.iterator]=mu.prototype.entries);YRr=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];K$.prototype.clone=function(){return new K$(this,{body:this._bodyInit})};Wgn.call(K$.prototype);Wgn.call(sC.pro
`);n=s.pop()??"";for(let a of s)try{yield JSON.parse(a)}catch{console.warn("invalid json: ",a)}}n+=e.decode();for(let o of n.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},cNr=t=>{if(!t)return Ggn;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let n=new URL(t),r=n.port;r||(e?r=n.protocol==="https:"?"443":"80":r=Kgn);let o="";n.username&&(o=n.username,n.password&&(o+=`:${n.password}`),o+="@");let i=`${n.protocol}//${o}${n.hostname}:${r}${n.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i},uNr=Object.defineProperty,dNr=(t,e,n)=>e in t?uNr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ltt=(t,e,n)=>(dNr(t,typeof e!="symbol"?e+"":e,n),n),Zte=class{constructor(e){ltt(this,"config"),ltt(this,"fetch"),ltt(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=cNr(e?.host??Ggn)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,n){n.stream=n.stream??!1;let r=`${this.config.host}/api/${e}`;if(n.stream){let i=new AbortController,s=await lO(this.fetch,r,n,{signal:i.signal,headers:this.config.headers});if(!s.body)throw new Error("Missing body");let a=lNr(s.body),l=new utt(i,a,()=>{let c=this.ongoingStreamedRequests.indexOf(l);c>-1&&this.ongoingStreamedRequests.splice(c,1)});return this.ongoingStreamedRequests.push(l),l}return await(await lO(this.fetch,r,n,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let n=new Uint8Array(e),r="",o=n.byteLength;for(let i=0;i<o;i++)r+=String.fromCharCode(n[i]);return btoa(r)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let n of e.messages)n.images&&(n.images=await Promise.all(n.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await aNr(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await lO(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await att(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await lO(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await lO(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await lO(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await att(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await att(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await lO(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await lO(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},l8i=new Zte});var ptt,Zgn=b(()=>{Dgn();zgn();ei();ZD();d0e();$d();NT();PS();Ms();Ew();Rg();NS();GD();ptt=class extends s_{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e??{};super(r);A(this,"model","llama3");A(this,"numa");A(this,"numCtx");A(this,"numBatch");A(this,"numGpu");A(this,"mainGpu");A(this,"lowVram");A(this,"f16Kv");A(this,"logitsAll");A(this,"vocabOnly");A(this,"useMmap");A(this,"useMlock");A(this,"embeddingOnly");A(this,"numT
`&&(u(),l="",c=0,n=!1);if(!h.scan(d))break;if(s=!0,w=h.scan(SDr)||"name",h.scan(bDr),w==="="?(y=h.scanUntil(vvn),h.scan(vvn),h.scanUntil(f)):w==="{"?(y=h.scanUntil(p),h.scan(xDr),h.scanUntil(f),w="&"):y=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(w==">"?_=[w,y,g,h.pos,l,c,n]:_=[w,y,g,h.pos],c++,o.push(_),w==="#"||w==="^")r.push(_);else if(w==="/"){if(S=r.pop(),!S)throw new Error('Unopened section "'+y+'" at '+g);if(S[1]!==y)throw new Error('Unclosed section "'+S[1]+'" at '+g)}else w==="name"||w==="{"||w==="&"?a=!0:w==="="&&m(y)}if(u(),S=r.pop(),S)throw new Error('Unclosed section "'+S[1]+'" at '+h.pos);return TDr(kDr(o))}function kDr(t){for(var e=[],n,r,o=0,i=t.length;o<i;++o)n=t[o],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function TDr(t){for(var e=[],n=e,r=[],o,i,s=0,a=t.length;s<a;++s)switch(o=t[s],o[0]){case"#":case"^":n.push(o),r.push(o),n=o[4]=[];break;case"/":i=r.pop(),i[5]=o[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(o)}return e}function Dne(t){this.string=t,this.tail=t,this.pos=0}function iq(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function Yp(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var dDr,sq,mDr,gDr,wDr,bDr,_Dr,vvn,xDr,SDr,Yw,Lne,wnt,bvn=b(()=>{dDr=Object.prototype.toString,sq=Array.isArray||function(e){return dDr.call(e)==="[object Array]"};mDr=RegExp.prototype.test;gDr=/\S/;wDr={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};bDr=/\s*/,_Dr=/\s+/,vvn=/\s*=/,xDr=/\s*\}/,SDr=/#|\^|\/|>|\{|&|=|!/;Dne.prototype.eos=function(){return this.tail===""};Dne.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};Dne.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};iq.prototype.push=function(e){return new iq(e,this)};iq.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var o=this,i,s,a,l=!1;o;){if(e.indexOf(".")>0)for(i=o.view,s=e.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=wvn(i,s[a])||pDr(i,s[a])),i=i[s[a++]];else i=o.view[e],l=wvn(o.view,e);if(l){r=i;break}o=o.parent}n[e]=r}return ynt(r)&&(r=r.call(this.view)),r};Yp.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Yp.prototype.parse=function(e,n){var r=this.templateCache,o=e+":"+(n||Yw.tags).join(":"),i=typeof r<"u",s=i?r.get(o):void 0;return s==null&&(s=CDr(e,n),i&&r.set(o,s)),s};Yp.prototype.render=function(e,n,r,o){var i=this.getConfigTags(o),s=this.parse(e,i),a=n instanceof iq?n:new iq(n,void 0);return this.renderTokens(s,a,r,e,o)};Yp.prototype.renderTokens=function(e,n,r,o,i){for(var s="",a,l,c,u=0,d=e.length;u<d;++u)c=void 0,a=e[u],l=a[0],l==="#"?c=this.renderSection(a,n,r,o,i):l==="^"?c=this.renderInverted(a,n,r,o,i):l===">"?c=this.renderPartial(a,n,r,i):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};Yp.prototype.renderSection=function(e,n,r,o,i){var s=this,a="",l=n.lookup(e[1]);function c(f){return s.render(f,n,r,i)}if(l){if(sq(l))for(var u=0,d=l.length;u<d;++u)a+=this.renderTokens(e[4],n.push(l[u]),r,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,o,i);else if(ynt(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,o.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,r,o,i);return a}};Yp.prototype.renderInverted=function(e,n,r,o,i){var s=n.lookup(e[1]);if(!s||sq(s)&&s.length===0)return this.renderTokens(e[4],n,r,o,i)};Yp.prototype.indentPartial=function(e,n,r){for(var o=n.replace(/[^ \t]/g,""),i=e.split(`
`)};Yp.prototype.renderPartial=function(e,n,r,o){if(r){var i=this.getConfigTags(o),s=ynt(r)?r(e[1]):r[e[1]];if(s!=null){var a=e[6],l=e[5],c=e[4],u=s;l==0&&c&&(u=this.indentPartial(s,c,a));var d=this.parse(u,i);return this.renderTokens(d,n,r,u,o)}}};Yp.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};Yp.prototype.escapedValue=function(e,n,r){var o=this.getConfigEscape(r)||Yw.escape,i=n.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Yw.escape?String(i):o(i)};Yp.prototype.rawValue=function(e){return e[1]};Yp.prototype.getConfigTags=function(e){return sq(e)?e:e&&typeof e=="object"?e.tags:void 0};Yp.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!sq(e))return e.escape};Yw={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){Lne.templateCache=t},get templateCache(){return Lne.templateCache}},Lne=new Yp;Yw.clearCache=function(){return Lne.clearCache()};Yw.parse=function(e,n){return Lne.parse(e,n)};Yw.render=function(e,n,r,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+fDr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return Lne.render(e,n,r,o)};Yw.escape=vDr;Yw.Scanner=Dne;Yw.Context=iq;Yw.Writer=Yp;wnt=Yw});var IDr,aq,_vn,$ne,xvn,Svn,J0e,Cvn,Qg,lq,cq,tF=b(()=>{sT();bvn();IDr={escape:t=>t},aq=t=>{let e=t.split(""),n=[],r=(i,s)=>{for(let a=s;a<e.length;a+=1)if(i.includes(e[a]))return a;return-1},o=0;for(;o<e.length;)if(e[o]==="{"&&o+1<e.length&&e[o+1]==="{")n.push({type:"literal",text:"{"}),o+=2;else if(e[o]==="}"&&o+1<e.length&&e[o+1]==="}")n.push({type:"literal",text:"}"}),o+=2;else if(e[o]==="{"){let i=r("}",o);if(i<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(o+1,i).join("")}),o=i+1}else{if(e[o]==="}")throw new Error("Single '}' in template.");{let i=r("{}",o),s=(i<0?e.slice(o):e.slice(o,i)).join("");n.push({type:"literal",text:s}),o=i<0?e.length:i}}return n},_vn=(t,e=[])=>{let n=[];for(let r of t)if(r[0]==="name"){let o=r[1].includes(".")?r[1].split(".")[0]:r[1];n.push({type:"variable",name:o})}else if(["#","&","^",">"].includes(r[0])){if(n.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){let o=[...e,r[1]],i=_vn(r[4],o);n.push(...i)}}else n.push({type:"literal",text:r[1]});return n},$ne=t=>{let e=wnt.parse(t);return _vn(e)},xvn=(t,e)=>aq(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e)return n+(typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]));throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),Svn=(t,e)=>wnt.render(t,e,void 0,IDr),J0e={"f-string":xvn,mustache:Svn},Cvn={"f-string":aq,mustache:$ne},Qg=(t,e,n)=>{try{return J0e[e](t,n)}catch(r){throw LE(r,"INVALID_PROMPT_INPUT")}},lq=(t,e)=>Cvn[e](t),cq=(t,e,n)=>{if(!(e in J0e)){let r=Object.keys(J0e);throw new Error(`Invalid template format. Got \`${e}\`;
should be one of ${r}`)}try{let r=Object.fromEntries(n.map(o=>[o,"foo"]));Array.isArray(t)?t.forEach(o=>{if(o.type==="text"&&"text"in o&&typeof o.text=="string")Qg(o.text,e,r);else if(o.type==="image_url"){if(typeof o.image_url=="string")Qg(o.image_url,e,r);else if(typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"){let i=o.image_url.url;Qg(i,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Qg(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}}});var aC,X0e=b(()=>{Nne();tF();aC=class Fne extends eF{constructor(n){super(n);A(this,"template");A(this,"templateFormat","f-string");A(this,"validateTemplate",!0);A(this,"additionalContentFields");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),cq(this.template,this.templateFormat,r)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(n){let r=await this.mergePartialAndUserVariables(n);return Qg(this.template,this.templateFormat,r)}static fromExamples(n,r,o,i=`
`,s=""){let a=[s,...n,r].join(i);return new Fne({inputVariables:o,template:a})}static fromTemplate(n,r){let{templateFormat:o="f-string",...i}=r??{},s=new Set;return lq(n,o).forEach(a=>{a.type==="variable"&&s.add(a.name)}),new Fne({inputVariables:[...s],templateFormat:o,template:n,...i})}async partial(n){let r=this.inputVariables.filter(s=>!(s in n)),o={...this.partialVariables??{},...n},i={...this,inputVariables:r,partialVariables:o};return new Fne(i)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(n){if(!n.template)throw new Error("Prompt template must have a template");return new Fne({inputVariables:n.input_variables,template:n.template,templateFormat:n.template_format})}}});var zne,vnt=b(()=>{BQ();oq();tF();zne=class kvn extends QT{constructor(n){super(n);A(this,"lc_namespace",["langchain_core","prompts","image"]);A(this,"template");A(this,"templateFormat","f-string");A(this,"validateTemplate",!0);A(this,"additionalContentFields");if(this.template=n.template,this.templateFormat=n.templateFormat??this.templateFormat,this.validateTemplate=n.validateTemplate??this.validateTemplate,this.additionalContentFields=n.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),cq([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(n){let r=this.inputVariables.filter(s=>!(s in n)),o={...this.partialVariables??{},...n},i={...this,inputVariables:r,partialVariables:o};return new kvn(i)}async format(n){let r={};for(let[a,l]of Object.entries(this.template))typeof l=="string"?r[a]=Qg(l,this.templateFormat,n):r[a]=l;let o=n.url||r.url,i=n.detail||r.detail;if(!o)throw new Error("Must provide either an image URL.");if(typeof o!="string")throw new Error("url must be a string.");let s={url:o};return i&&(s.detail=i),s}async formatPromptValue(n){return new Nan(await this.format(n))}}});function bnt(t,e){let n=[];for(let r of Object.values(t))if(typeof r=="string")lq(r,e).forEach(o=>{o.type==="variable"&&n.push(o.name)});else if(Array.isArray(r))for(let o of r)typeof o=="string"?lq(o,e).forEach(i=>{i.type==="variable"&&n.push(i.name)}):typeof o=="object"&&n.push(...bnt(o,e));else typeof r=="object"&&r!==null&&n.push(...bnt(r,e));return Array.from(new Set(n))}function _nt(t,e,n){let r={};for(let[o,i]of Object.entries(t))if(typeof i=="string")r[o]=Qg(i,n,e);else if(Array.isArray(i)){let s=[];for(let a of i)typeof a=="string"?s.push(Qg(a,n,e)):typeof a=="object"&&s.push(_nt(a,e,n));r[o]=s}else typeof i=="object"&&i!==null?r[o]=_nt(i,e,n):r[o]=i;return r}var Q0e,xnt=b(()=>{Wu();tF();Q0e=class extends Lo{constructor(e){let n=e.templateFormat??"f-string",r=bnt(e.template,n);super({inputVariables:r,...e});A(this,"lc_namespace",["langchain_core","prompts","dict"]);A(this,"lc_serializable",!0);A(this,"template");A(this,"templateFormat");A(this,"inputVariables");this.template=e.template,this.templateFormat=n,this.inputVariables=r}static lc_name(){return"DictPromptTemplate"}async format(e){return _nt(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function PDr(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function ADr(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}function EDr(t){return typeof t.formatMessages=="function"}function MDr(t,e){if(EDr(t)||ww(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){let o=t[1];if(e?.templateFormat==="mustache"&&typeof o=="string"&&o.slice(0,2)==="{{"&&o.slice(-2)==="}}")retur
`));throw s.name="InputFormatError",s.lc_error_code=o.lc_error_code,s}return r}},Tvn=class extends tke{constructor(e){"prompt"in e||(e={prompt:e});super(e);A(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},Snt=class extends QT{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){return new _xe(await this.formatMessages(t))}},Ivn=class extends Tvn{constructor(e,n){"prompt"in e||(e={prompt:e,role:n});super(e);A(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new Vf(await this.prompt.format(e),this.role)}static fromTemplate(e,n,r){return new this(aC.fromTemplate(e,{templateFormat:r?.templateFormat}),n)}};Cnt=class extends tke{constructor(e,n){"prompt"in e||(e={prompt:e});super(e);A(this,"lc_namespace",["langchain_core","prompts","chat"]);A(this,"lc_serializable",!0);A(this,"inputVariables",[]);A(this,"additionalOptions",{});A(this,"prompt");A(this,"messageClass");A(this,"chatMessageClass");if(this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(o=>{"inputVariables"in o&&(r=r.concat(o.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=n??this.additionalOptions}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){let n=this.constructor;if(n._messageClass())return new(n._messageClass())({content:e});if(n.chatMessageClass){let r=n.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,n){if(typeof e=="string")return new this(aC.fromTemplate(e,n));let r=[];for(let o of e)if(typeof o=="string")r.push(aC.fromTemplate(o,n));else if(o!==null)if(PDr(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let s={...n,additionalContentFields:o};r.push(aC.fromTemplate(i,s))}else if(ADr(o)){let i=o.image_url??"",s,a=[];if(typeof i=="string"){let l;n?.templateFormat==="mustache"?l=$ne(i):l=aq(i);let c=l.flatMap(u=>u.type==="variable"?[u.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
Got: ${c}
From: ${i}`);a=[c[0]]}else a=[];i={url:i},s=new zne({template:i,inputVariables:a,templateFormat:n?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let l;n?.templateFormat==="mustache"?l=$ne(i.url):l=aq(i.url),a=l.flatMap(c=>c.type==="variable"?[c.name]:[])}else a=[];s=new zne({template:i,inputVariables:a,templateFormat:n?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");r.push(s)}else typeof o=="object"&&r.push(new Q0e({template:o,templateFormat:n?.templateFormat}));return new this({prompt:r,additionalOptions:n})}async format(e){if(this.prompt instanceof eF){let n=await this.prompt.format(e);return this.createMessage(n)}else{let n=[];for(let r of this.prompt){let o={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(let i of r.inputVariables)o||(o={[i]:e[i]}),o={...o,[i]:e[i]};if(r instanceof eF){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),i!==""&&n.push({...s,type:"text",text:i})}else if(r instanceof zne){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),n.push({...s,type:"image_url",image_url:i})}else if(r instanceof Q0e){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),n.push({...s,...i})}}return this.createMessage(n)}}async formatMessages(e){return[await this.format(e)]}},rF=class extends Cnt{static _messageClass(){return Zs}static lc_name(){return"HumanMessagePromptTemplate"}},Pvn=class extends Cnt{static _messageClass(){return mr}static lc_name(){return"AIMessagePromptTemplate"}},nke=class extends Cnt{static _messageClass(){return Ag}static lc_name(){return"SystemMessagePromptTemplate"}};bO=class eke extends Snt{constructor(n){super(n);A(this,"promptMessages");A(this,"validateTemplate",!0);A(this,"templateFormat","f-string");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){let r=new Set;for(let l of this.promptMessages)if(!(l instanceof Ml))for(let c of l.inputVariables)r.add(c);let o=this.inputVariables,i=new Set(this.partialVariables?o.concat(Object.keys(this.partialVariables)):o),s=new Set([...i].filter(l=>!r.has(l)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are not used in any of the prompt messages.`);let a=new Set([...r].filter(l=>!i.has(l)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async _parseImagePrompts(n,r){return typeof n.content=="string"||(n.content=await Promise.all(n.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"&&(i=o.image_url.url);let s=await aC.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url?o.image_url.url=s:o.image_url=s,o}))),n}async formatMessages(n){let r=await this.mergePartialAndUserVariables(n),o=[];for(let i of this.promptMessages)if(i instanceof Ml)o.push(await this._parseImagePrompts(i,r));else{let s;this.templateFormat==="mustache"?s={...r}:s=i.inputVariables.reduce((l,c)=>{if(!(c in r)&&!(ODr(i)&&i.optional))throw LE(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return l[c]=r[c],l},{});let a=await i.formatMessages(s);o=o.concat(a)}return o}async partial(n){let r=this.inputVariables.filter(s=>!(s in n)),o={...this.partialVariables??{},...n},i={...this,inputVariables:r,partialVariables:o};return new eke(i)}static fromTemplate(n,r){let o=new rF({prompt:aC.fromTemplate(n,r)});return this.fromMessages([o])}static fromMessages(n,r){let o=n.reduce((a,l)=>a.concat(l instanceof eke?l.promptMessages:[MDr(l,r)]),[]),i=n.reduce((a,l)=>l instanceof eke?O
- Key concepts and main ideas
- Important facts, names, and dates
- Technical details relevant for Q&A
Keep the summary concise but information-dense. Output only the summary.
`);if(n.get(l.id)===d)return;let p=(r.get(l.id)??Promise.resolve()).catch(()=>{}).then(async()=>{o||(await Wzr(t.modelManagement,l,u),n.set(l.id,d))}).catch(m=>{W(`[AgentMode] model discovery enroll failed for ${l.id}`,m)}).finally(()=>{r.get(l.id)===p&&r.delete(l.id)});r.set(l.id,p)},s=()=>{if(!o)for(let l of Is())i(l)},a=e.subscribeModelCache(s);return s(),()=>{o=!0,a()}}async function Wzr(t,e,n){let r=e.id,o=n.map(d=>d.wireId),i=e.id==="opencode"?Vzr(t,o):o,s={},a={};for(let d of n)d.name&&(s[d.wireId]=d.name),d.description&&(a[d.wireId]=d.description);if(i.length===0){H(`[AgentMode] model discovery: empty model list for ${r} — skipping enroll/sync (transient or fully-suppressed probe)`);return}if(t.providerRegistry.listByOrigin("agent").find(d=>d.origin.kind==="agent"&&d.origin.agentType===r)){await t.setup.agent.syncAgentModels({agentType:r,wireModelIds:i,fallbackDisplayNames:s,fallbackDescriptions:a});return}let c=e.id==="opencode"?i.slice(0,jzr):void 0,u=await t.setup.agent.registerAgentProvider({agentType:r,providerType:Bzr[r],displayName:e.displayName,apiKey:null,wireModelIds:i,autoEnrollModelIds:c,fallbackDisplayNames:s,fallbackDescriptions:a});H(`[AgentMode] model discovery: first enrollment for ${r} — ${u.configuredModelIds.length} model(s) configured, ${c?.length??u.configuredModelIds.length} enabled`)}function Vzr(t,e){let n=[...t.providerRegistry.listByOrigin("byok"),...t.providerRegistry.listByOrigin("copilot-plus")],r=DSn(n);return fbe(e,r)}function DSn(t){let e=new Set;for(let n of t){if(n.origin.kind==="agent")continue;let r=Px(n);r&&e.add(r.id)}return e}function qzr(t){return t?.availableModels?t.availableModels.map(e=>({wireId:e.baseModelId,name:e.name,description:e.description})):null}var Bzr,jzr,FSn=b(()=>{ge();Xm();Bzr={claude:"anthropic",codex:"openai-compatible",opencode:"openai-compatible"},jzr=3});var Kzr={};Vo(Kzr,{default:()=>LTe});module.exports=qSn(Kzr);ot();eMe();xG();De();ge();vt();var zpt=require("obsidian");function Upt(t,e,n,r){let o=!0,i;return rMe().then(s=>{if(!o||!s||s.version===n||!$oe(s.version,e))return;let a=t.workspace.containerEl.doc.win.createFragment(),l=a.createDiv({cls:"copilot-release-notice"});l.createDiv({text:`Copilot ${s.version} is available`}),l.createEl("button",{text:"View release notes",cls:X(qTe({variant:"secondary",size:"sm"}),"tw-max-w-full tw-whitespace-normal")}).addEventListener("click",()=>{o&&(i?.hide(),new hz(t,s).open())}),i=new zpt.Notice(a,15e3),r(s.version)}).catch(s=>V("Copilot update check failed",s)),()=>{o=!1,i?.hide()}}var Bpt=require("@codemirror/state"),jpt=require("@codemirror/view"),Hpt=jpt.EditorView.domEventHandlers({blur(t,e){let n=e.state.selection,r=n.main;r.empty&&r.assoc!==0&&e.dispatch({selection:n.replaceRange(Bpt.EditorSelection.cursor(r.head,0,r.bidiLevel??void 0,r.goalColumn))})}});kG();Ov();Ma();Ma();vC();xt();xt();ge();var NE=class{static convert(e,n={}){let{includeSystemMessage:r=!0,mergeUserContent:o=!0,debug:i=!1}=n,s=[],a=e.layers.find(f=>f.id==="L1_SYSTEM"),l=e.layers.find(f=>f.id==="L2_PREVIOUS"),c=e.layers.find(f=>f.id==="L3_TURN"),u=e.layers.find(f=>f.id==="L4_STRIP"),d=e.layers.find(f=>f.id==="L5_USER");if(r&&a&&a.text){let f=[a.text];l&&l.text&&(f.push(`
## Context Library
The following notes are available for reference:
`+l.text),i&&H("[LayerToMessagesConverter] Added L2 (cumulative context) to system")),s.push({role:"system",content:f.join(`
`)}),i&&H("[LayerToMessagesConverter] Added L1 (System) + L2 (Cumulative) as stable prefix")}if(u&&u.text&&i&&H("[LayerToMessagesConverter] L4 (Strip) found but skipped (using LangChain memory)"),o){let f=[];if(c&&c.segments.length>0&&l){let p=new Set(l.segments.map(g=>g.id)),m=[],h=[];for(let g of c.segments)p.has(g.id)?m.push(g.id):h.push(g);if(m.length>0||h.length>0){let g=[];m.length>0&&g.push(`Context attached to this message:
`+m.map(w=>`- ${w}`).join(`
`)+`
Find them in the Context Library in the system prompt above.`),h.length>0&&g.push(h.map(w=>w.content).join(`
`)),f.push(g.join(`
`)),i&&H(`[LayerToMessagesConverter] Added L3: ${m.length} references, ${h.length} new items`)}}else c&&c.text&&(f.push(c.text),i&&H("[LayerToMessagesConverter] Added L3 (all new context)"));f.length>0&&d&&d.text&&f.push(`---
`)})}else c&&c.text&&s.push({role:"user",content:c.text}),d&&d.text&&s.push({role:"user",content:d.text});return i&&(H(`[LayerToMessagesConverter] Converted envelope to ${s.length} messages`),s.forEach((f,p)=>{let m=f.content.substring(0,100);H(` Message ${p+1} [${f.role}]: ${m}...`)})),s}};ge();vt();xt();ge();vt();LIe();var jH=class{constructor(e){this.chainManager=e}async handleResponse(e,n,r,o,i,s,a,l){if((e||l?.wasTruncated)&&!(r.signal.aborted&&r.signal.reason==="new-chat")){let p=n.contextEnvelope?.layers.find(w=>w.id==="L5_USER")?.text||n.originalMessage||n.message,m=a||e||"[Response truncated - no content generated]";await this.chainManager.memoryManager.saveContext({input:p},{output:m});let g={message:e||(l?.wasTruncated?"_[The model stopped at its maximum response length before generating any content.]_":""),sender:bl,isVisible:!0,timestamp:Ta(new Date),sources:s,responseMetadata:l};o(g),i("")}else r.signal.reason==="new-chat"&&i("");let u=this.chainManager.memoryManager.getMemory().chatHistory.messages;H(`Chat memory updated:
`,{turns:Array.isArray(u)?u.length:0});let d=2e3;try{let{parseToolCallMarkers:f}=await Promise.resolve().then(()=>(W6e(),PZt)),m=f(e).segments.map(g=>g.type==="text"?g.content:"").join("").trim();m||(m=e||"");let h=m.length>d?m.slice(0,d)+"... (truncated)":m;H(`Final AI response (truncated):
`,h)}catch{let f=typeof e=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;H(`Final AI response (truncated):
`,p)}return e}async handleError(e,n){let r=Dt(e);W("Error during LLM invocation:",r);let o=soe(e);if(o){n(o);return}let i=e?.response?.data?.error||r,s=i?.code||r,a="";e?.message?.includes("Invalid license key")?a="Invalid Copilot Plus license key. Please check your license key in settings.":s==="model_not_found"?a="You do not have access to this model or the model does not exist, please check with your API provider.":a=`${s}`,W(i),n(this.enhancedErrorMsg(a,r,e))}enhancedErrorMsg(e,n,r){let o=e.search("Troubleshooting URL");return e=o!==-1?e.slice(0,o):e,this.isAuthenticationError(r,n)&&(e=`Something went wrong. Please check if you have set your API key.
Path: Settings > Copilot > BYOK.
Or check model config
Error Details: `+e),e}isAuthenticationError(e,n){let r=e?.response,o=r?.data?.error??e?.error,i=r?.status??o?.status,s=typeof i=="string"?Number.parseInt(i,10):i,a=typeof o=="object"&&o!==null?o:void 0,l=(typeof a?.message=="string"?a.message:n).toLowerCase(),c=typeof a?.code=="string"?a.code.toLowerCase():"",u=typeof a?.type=="string"?a.type.toLowerCase():"";return s===401?!0:["api key","apikey","unauthorized","authentication","invalid authentication"].some(f=>l.includes(f)||c.includes(f)||u.includes(f))}};ge();function mvr(t){let e=[];for(let n of t){if(!n)continue;let r=n;if(typeof r.type=="string"){let o=r.type;o==="human"?e.push({role:"user",content:r.content}):o==="ai"&&e.push({role:"assistant",content:r.content})}else if(r.content!==void 0){let o=hvr(r);o&&e.push({role:o,content:r.content})}}return e}function hvr(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}async function WH(t,e){let r=(await t.loadMemoryVariables({})).history||[],o=r.length?mvr(r):[];for(let l of o)e.push({role:l.role,content:l.content});let i=0;for(let l of e)typeof l.content=="string"&&l.role==="system"&&(i+=l.content.length);let s=0;for(let l of o)typeof l.content=="string"&&(s+=l.content.length);let a=i+s;return a>2e6&&H("[Token Budget] Large payload detected (excluding user message):",{"L1+L2 (system)":`${Math.round(i/4e3)}k tokens`,"L4 (history)":`${Math.round(s/4e3)}k tokens (${o.length} msgs)`,total:`${Math.round(a/4e3)}k tokens`}),o}RE();function qen(t){let e=t.response_metadata||{};return e.finish_reason==="length"?{wasTruncated:!0,message:"Response truncated due to token limit"}:e.stop_reason==="max_tokens"?{wasTruncated:!0,message:"Response truncated due to max_tokens limit"}:e.finishReason==="MAX_TOKENS"||e.finish_reason==="MAX_TOKENS"?{wasTruncated:!0,message:"Response truncated due to MAX_TOKENS limit"}:{wasTruncated:!1,message:null}}function Ken(t){let e=t.response_metadata||{};if(e.tokenUsage){let n=e.tokenUsage;return{inputTokens:n.promptTokens,outputTokens:n.completionTokens,totalTokens:n.totalTokens}}if(e.usage){let n=e.usage;return{inputTokens:n.input_tokens||n.inputTokens||n.inputTokenCount||n.prompt_tokens,outputTokens:n.output_tokens||n.outputTokens||n.outputTokenCount||n.completion_tokens,totalTokens:n.total_tokens||n.totalTokens||(n.input_tokens||n.inputTokenCount||0)+(n.output_tokens||n.outputTokenCount||0)}}return t.usage_metadata?{inputTokens:t.usage_metadata.input_tokens,outputTokens:t.usage_metadata.output_tokens,totalTokens:t.usage_metadata.total_tokens}:null}function gvr(t){return`<errorChunk>${t}</errorChunk>`}function Sbe(t,e){let n=gvr(t);return e?`${e}
${n}`:`
${n}`}ei();ge();function L8e(t,e,n){return new Pg({content:n,tool_call_id:t,name:e})}function gxe(){let t=Date.now(),e=Math.random().toString(36).substring(2,11);return`call_${t}_${e}`}function _an(t,e){let n=e.index??0,r=t.get(n)||{name:"",args:""};e.id&&(r.id=e.id);let o=e.name??e.functionCall?.name;o&&(r.name+=o),e.args&&(r.args+=e.args),t.set(n,r)}function yxe(t){let e=[];for(let n of t.values()){if(!n.name)continue;let r={};if(n.args)try{r=JSON.parse(n.args)}catch{W(`[ToolCall] Failed to parse args for tool "${n.name}": ${n.args}`),r={}}e.push({id:n.id||gxe(),name:n.name,args:r})}return e}ge();var B0r=["<|im_end|>","<|im_start|>","<|eot_id|>","<|start_header_id|>","<|end_header_id|>","<end_of_turn>","<start_of_turn>","<|end|>","<|assistant|>","<|user|>","<|system|>","</s>","[INST]","[/INST]","<|endoftext|>","<|end▁of▁sentence|>","<|END_OF_TURN_TOKEN|>","<|START_OF_TURN_TOKEN|>"],j0r=new RegExp(B0r.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");function D8e(t){return t.replace(j0r,"")}var Qb=class{constructor(e,n=!1){this.updateCurrentAiMessage=e;this.excludeThinking=n;this.hasOpenThinkBlock=!1;this.fullResponse="";this.errorResponse="";this.wasTruncated=!1;this.tokenUsage=null;this.hasHandledTextLevelThinkTag=!1;this.excludedThinkBlockStart=-1;this.toolCallChunks=new Map;H(`[ThinkBlockStreamer] Created with excludeThinking=${n}`)}handleTextLevelThinkTags(){if(this.excludeThinking){this.handleExcludedThinkTags();return}let e=this.fullResponse.includes("</think>"),n=this.fullResponse.includes("<think>");e&&!n&&!this.hasHandledTextLevelThinkTag&&(this.hasHandledTextLevelThinkTag=!0,V("Detected </think> closing tag without opening <think> tag. This may indicate a misconfigured chat template in LM Studio. Adding opening tag."),this.fullResponse="<think>"+this.fullResponse)}handleExcludedThinkTags(){if(this.excludedThinkBlockStart>=0){let r=this.fullResponse.indexOf("</think>",this.excludedThinkBlockStart);if(r!==-1){let o=this.fullResponse.substring(0,this.excludedThinkBlockStart),i=this.fullResponse.substring(r+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,this.excludedThinkBlockStart);return}let e=this.fullResponse.indexOf("<think>");if(e!==-1){this.excludedThinkBlockStart=e;let r=this.fullResponse.indexOf("</think>",e);if(r!==-1){let o=this.fullResponse.substring(0,e),i=this.fullResponse.substring(r+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,e);return}let n=this.fullResponse.indexOf("</think>");n!==-1&&(this.fullResponse=this.fullResponse.substring(n+8).trimStart())}handleClaudeChunk(e){let n="",r=!1;for(let o of e)switch(o.type){case"text":n+=o.text;break;case"thinking":if(r=!0,this.excludeThinking)break;this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.delta.reasoning),!0):(typeof e.content=="string"&&e.content&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),typeof e.content=="string"&&e.content&&(this.fullResponse+=e.content),!1)}handleToolCallChunks(e){let n=e.tool_call_chunks;if(!(!n||!Array.isArray(n)))for(let r of n){let o=r.index??0,i=this.toolCallChunks.get(o)||{name:"",args:""};r.id&&(i.id=r.id),r.name&&(i.name+=r.name),r.args&&(i.args+=r.args),this.toolCallChunks.set(o,i)}}processChunk(e){qen(e).wasTruncated&&(this.wasTruncated=!0);let r=Ken(e);r&&(this.tokenUsage=r),this.handleToolCallChunks(e);let o=Array.isArray(e.content)||e.additional_kwargs?.delta?.reasoning||e.additional_kwargs?.reasoning_details&&Array.isArray(e.additional_kwargs.reasoning_details)&&e.additional_kwargs.reasoning_details.length>0||e.additional_kwargs?.reasoning_content;this.hasOpenThinkBlock&&!o&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),Array.isArray(e.content)?this.handleClaudeChunk(e.content):e.additional_kwargs?.reasoning_content?this.handleDeepseekChunk(e):o?this.handleOpenRouterChunk(e):this.handleDeepseekChunk(e),this.handleTextLevelThinkTags(),this.updateCurrentAiMessage(this.fullResponse)}processErrorChunk(e){this.errorResponse=Sbe(e)}getToolCalls(){return yxe(this.toolCallChunks)}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>"),this.handleTextLevelThinkTags(),this.errorResponse&&(this.fullResponse+=this.errorResponse),this.updateCurrentAiMessage(this.fullResponse),{content:this.fullResponse,wasTruncated:this.wasTruncated,tokenUsage:this.tokenUsage}}};var DQ=class extends jH{async constructMessages(e){if(!e.contextEnvelope)throw new Error("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");H("[LLMChainRunner] Using envelope-based context");let n=NE.convert(e.contextEnvelope,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),r=[],o=n.find(a=>a.role==="system");o&&r.push(o);let i=this.chainManager.memoryManager.getMemory();await WH(i,r);let s=n.find(a=>a.role==="user");if(s)if(e.content&&Array.isArray(e.content)){let a=e.content.map(l=>l.type==="text"?{...l,text:s.content}:l);r.push({role:"user",content:a})}else r.push(s);return r}async run(e,n,r,o,i){let s=!1,a=this.chainManager.chatModelManager.getActiveModel();a?s=!a.capabilities?.includes("reasoning"):H("Could not determine model capabilities, defaulting to include thinking blocks");let l=new Qb(r,s);try{let d=await this.constructMessages(e),p=this.chainManager.chatModelManager.getChatModel()?.modelName;zH({messages:d,modelName:p,contextEnvelope:e.contextEnvelope}),H(`Final Request to AI:
`,d);let m=await fv(()=>this.chainManager.chatModelManager.getChatModel().stream(d,{signal:n.signal}));for await(let h of m){if(n.signal.aborted){H("Stream iteration aborted",{reason:n.signal.reason});break}l.processChunk(h)}}catch(d){(d instanceof Error?d.name:"")==="AbortError"||n.signal.aborted?H("Stream aborted by user",{reason:n.signal.reason}):await this.handleError(d,p=>l.processErrorChunk(p))}let c=l.close(),u={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};return n.signal.aborted&&n.signal.reason==="new-chat"?(r(""),""):(await this.handleResponse(c.content,e,n,o,r,void 0,void 0,u),c.content)}};Lye();xt();ge();vt();u1();var CD=require("obsidian"),DS=class{static async isImageUrl(e,n){try{let r,o=!1;try{let i=new URL(e),s=i.pathname,a=s.lastIndexOf("."),l=s.lastIndexOf("/");if(a>l&&a>-1&&(r=s.substring(a+1).toLowerCase()),r&&!this.IMAGE_EXTENSIONS.some(u=>u.toLowerCase()===`.${r}`))return W(`Unsupported image format from URL path: .${r}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;try{let u=(await Loe(e,{method:"HEAD",headers:{}})).headers.get("content-type");return u?.startsWith("image/")?!0:(V(`HEAD request succeeded for ${e} but Content-Type (${u}) is not image/*.`),!1)}catch(c){V(`HEAD request failed for URL: ${e}. Proceeding to heuristic check.`,c);let u=i.searchParams,f=[u.has("w")||u.has("width"),u.has("h")||u.has("height"),u.has("format"),u.has("fit"),u.has("quality"),i.pathname.includes("/image/"),i.pathname.includes("/images/"),i.pathname.includes("/img/"),u.has("auto"),u.has("crop")].filter(Boolean).length;return f>=2?(W(`Identified as image based on URL heuristics (indicator count: ${f}): ${e}`),!0):!1}}catch{o=!0;let i=e.lastIndexOf(".");if(i>-1)r=e.substring(i+1).toLowerCase();else return!1}if(o)if(r&&this.IMAGE_EXTENSIONS.some(i=>i.toLowerCase()===`.${r}`)){let i=n.getAbstractFileByPath(e);return i instanceof CD.TFile?i.stat.size>this.MAX_IMAGE_SIZE?(W(`Vault file too large: ${i.stat.size} bytes for path: ${e}`),!1):!0:(W(`File with image extension not found in vault: ${e}.`),!1)}else return r&&W(`Unsupported image format for potential vault path: .${r}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;return W(`Could not determine image status for URL/path: ${e}`),!1}catch(r){return W(`Unexpected error in isImageUrl for "${e}":`,r),!1}}static async handleVaultImage(e,n){try{if(e.stat.size>this.MAX_IMAGE_SIZE)return W(`Image too large: ${e.stat.size} bytes, skipping: ${e.path}`),null;let r=await n.readBinary(e),o=await this.getMimeType(r,e.extension);if(!o.startsWith("image/"))return W(`Invalid MIME type: ${o}, skipping: ${e.path}`),null;let i=vd(r);return`data:${o};base64,${i}`}catch(r){return W("Error processing vault image:",r),null}}static async handleWebImage(e){try{let n=await Loe(e,{method:"GET",headers:{}});if(!n.ok)return W(`Failed to fetch image: ${n.statusText}, URL: ${e}`),null;let r=n.headers.get("content-type");if(!r?.startsWith("image/"))return W(`Invalid content type: ${r}, URL: ${e}`),null;let o=await n.arrayBuffer();if(o.byteLength>this.MAX_IMAGE_SIZE)return W(`Image too large: ${o.byteLength} bytes, URL: ${e}`),null;let i=vd(o);return`data:${r};base64,${i}`}catch(n){return W("Error converting web image to base64:",n),null}}static async handleLocalImage(e,n){try{let r=decodeURIComponent(e.replace("app://","")),o=n.getAbstractFileByPath(r);if(!o||!(o instanceof CD.TFile))return W(`Local image not found: ${r}`),null;if(o.stat.size>this.MAX_IMAGE_SIZE)return W(`Image too large: ${o.stat.size} bytes, path: ${r}`),null;let i=await n.readBinary(o),s=await this.getMimeType(i,o.extension);if(!s.startsWith("image/"))return W(`Invalid MIME type: ${s}, path: ${r}`),null;let a=vd(i);return`data:${s};base64,${a}`}catch(r){return W("Error processing local image:",r),null}}static async imageToBase64(e,n){if(e.startsWith("data:"))return e;if(e.startsWith("attachment:")){let o=e.substring(11),i=n.getAbstractFileByPath(o);return i instanceof CD.TFile?await this.handleVaultImage(i,n):(V(`Could not find attachment file in vault: ${o}`),null)}if(e.startsWit
${e.join(`
`)}`)}};ge();Bl();Ee();rw();xt();ge();uP();async function TD(t){let e=vz(),n=imt().find(r=>r.title===e);return n?n.content:Dj(t,"")}function LW(t){if(TR())return t;let n=Zot;return t?`${n}
<user_custom_instructions>
${t}
</user_custom_instructions>`:n}async function $Q(t,e){let n=LW(e);if(!t)return H("No UserMemoryManager provided to getSystemPromptWithMemory"),n;let r=await t.getUserMemoryPrompt();return r?`${r}
The path must end with explicit file extension, such as .md or .canvas .
Prefer to create new files in existing folders or root folder unless the user's request specifies otherwise.
The path must be relative to the root of the vault.`),content:an([j(),J({}).loose()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions.
You MUST include ALL parts of the file, even if they haven't been modified.
# For string content
* Use when writing text files like .md, .txt, etc.
# For object content
* Use when writing structured data files like .json, .canvas, etc.
* The object will be automatically converted to JSON string format
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
}`),confirmation:an([ro(),j()]).optional().describe("(Optional) Hint for confirmation preference. Note: preview is always shown unless the user has enabled auto-accept in settings.")}),Ixe=t=>Ii({name:"writeFile",description:`Request to write content to a file at the specified path and show the changes in a Change Preview UI.
# Steps to find the the target path
1. Extract the target file information from user message and find out the file path from the context.
2. If target file is not specified, use the active note as the target file.
3. If still failed to find the target file or the file path, ask the user to specify the target file.
`,schema:ckr,func:async({path:e,content:n,confirmation:r=!0})=>{let o=LPe(e);o!==e&&(V(`Filename too long, truncated for filesystem compatibility: "${e}" → "${o}"`),e=o);let i=typeof n=="string"?n:JSON.stringify(n,null,2);if(le().autoAcceptEdits)try{let c=await Wan(t,e);return await t.vault.modify(c,i),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."}}catch(c){return{result:"failed",message:`Error writing to file without preview: ${c instanceof Error?c.message:String(c)}`}}let l=await Van(t,e,i);return{result:l,message:`File change result: ${l}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}}),ukr=J({path:j().describe("(Required) The path of the file to modify (relative to the root of the vault and include the file extension)."),oldText:j().describe(`(Required) The exact text to find and replace. Must match the file content exactly, including whitespace and indentation.
Fuzzy matching handles minor differences like trailing spaces or smart quotes, but the overall structure must be correct.
To make the match unique, include enough surrounding context lines (not just the changed line).`),newText:j().describe("(Required) The new text to replace the old text with. Can be empty string to delete the old text.")});function J8e(t){return t.replace(/\r\n/g,`
`)),o&&(m="\uFEFF"+m),{ok:!0,content:m}}var qan=t=>Ii({name:"editFile",description:"Request to make a targeted change to an existing file by specifying the exact text to find and its replacement. Use this tool for precise, surgical edits to specific parts of a file.",schema:ukr,func:async({path:e,oldText:n,newText:r})=>{let o=LPe(e),i=t.vault.getAbstractFileByPath(o);if(!i||!(i instanceof $W.TFile))return{result:"failed",message:`File not found at path: ${o}. Please check the file path and try again.`};try{let s=await t.vault.read(i),a=pkr(s,n,r);if(!a.ok)return a.reason==="NOT_FOUND"?{result:"failed",message:`Could not find the specified text in ${o}. The oldText must match the file content — try including more surrounding context lines to locate the right spot.`}:{result:"failed",message:`Found ${a.occurrences} occurrences of the search text in ${o}. The text must be unique — add more surrounding context to make it unambiguous.`};let l=a.content;if(s===l)return{result:"accepted",message:`No changes made to ${o}. The replacement produced identical content. Use writeFile if the file needs a broader rewrite.`};if(le().autoAcceptEdits)return await t.vault.modify(i,l),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."};let u=await Van(t,o,l,!0);return{result:u,message:`File change result: ${u}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}catch(s){return{result:"failed",message:`Error modifying ${o}: ${s}. Please check the file path and try again.`}}}});Nye();Dwe();$H();Ee();var Kan=require("obsidian"),mkr="obsidian",hkr=["/Applications/Obsidian.app/Contents/MacOS/obsidian","/Applications/Obsidian.app/Contents/MacOS/Obsidian"],gkr=15e3,ykr=1048576;function X8e(){let t=Kan.Platform;return!!(t.isDesktopApp??t.isDesktop)}function wkr(){let t=window;if(typeof t.require!="function")throw new Error("Node require is unavailable in this runtime. Obsidian CLI commands require the desktop app.");return t.require}function vkr(){let e=wkr()("child_process");if(typeof e.execFile!="function")throw new Error("Failed to resolve child_process.execFile");return e.execFile}function bkr(t){return t.replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function _kr(){let e=window.process?.env;return e?[e.OBSIDIAN_CLI_BINARY,e.OBSIDIAN_CLI_PATH].map(r=>r?.trim()||"").filter(Boolean):[]}function xkr(t){let e=t?.trim();if(e)return[e];let n=[..._kr(),mkr,...hkr];return Array.from(new Set(n.map(r=>r.trim()).filter(Boolean)))}function Skr(t){let e=[],n=t.vault?.trim();n&&e.push(`vault=${n}`),e.push(t.command);let r=Object.entries(t.params||{});r.sort(([o],[i])=>o.localeCompare(i));for(let[o,i]of r)if(i!=null){if(typeof i=="boolean"){i&&e.push(o);continue}e.push(`${o}=${bkr(String(i))}`)}return e}function Ckr(t){return typeof t=="number"?t:null}async function kkr(t,e,n,r,o,i,s){let a=Date.now();return await new Promise(l=>{t(n,r,{timeout:o,maxBuffer:i,windowsHide:!0},(c,u,d)=>{let f=Date.now()-a;if(c){l({command:e,args:r,binary:n,attemptedBinaries:[...s],ok:!1,stdout:u||"",stderr:d||"",exitCode:Ckr(c.code),errorCode:c.code??null,signal:c.signal??null,durationMs:f});return}l({command:e,args:r,binary:n,attemptedBinaries:[...s],ok:!0,stdout:u||"",stderr:d||"",exitCode:0,errorCode:null,signal:null,durationMs:f})})})}async function CT(t){let e=t.command?.trim();if(!e)throw new Error("Obsidian CLI command is required");if(!X8e())throw new Error("Obsidian CLI commands are only supported in desktop Obsidian.");let n=Skr({...t,command:e}),r=t.timeoutMs??gkr,o=t.maxBufferBytes??ykr,i=vkr(),s=xkr(t.binary),a=[],l=null;for(let c of s){a.push(c);let u=await kkr(i,e,c,n,r,o,a);if(l=u,u.ok||u.errorCode!=="ENOENT")return u}if(l)return l;throw new Error("Obsidian CLI execution failed before process spawn.")}async function Gan(t){return await CT({command:"daily:read",vault:t})}async function Zan(t){return await CT({command:"random:read",vault:t})}Id();wm();function Tkr(t){return typeof t=="
* The root object has a key "vault" which contains a FileTreeNode object.
* Each FileTreeNode has these properties:
* files: An array of filenames in the current directory (if any files exist)
* subFolders: An object mapping folder names to their FileTreeNode objects (if any subfolders exist)
* extensionCounts: An object with counts of file extensions in this folder and all subfolders
`,o=JSON.stringify(n);if(o.length>5e5){let i=Q8e(t,e,!1);return r+JSON.stringify(i)}return r+o}});wm();var FW=require("obsidian");ge();Ee();ia();vt();ei();var lM=class{constructor(e){this.recentConversationsContent="";this.savedMemoriesContent="";this.isUpdatingMemory=!1;this.app=e}async loadMemory(){try{let e=A2(),n=this.app.vault.getAbstractFileByPath(this.getRecentConversationFilePath(e));n instanceof FW.TFile?this.recentConversationsContent=await this.app.vault.read(n):(this.recentConversationsContent="",H("[UserMemoryManager] Recent Conversations file not found, skipping memory load"));let r=this.app.vault.getAbstractFileByPath(this.getSavedMemoriesFilePath(e));r instanceof FW.TFile?this.savedMemoriesContent=await this.app.vault.read(r):(this.savedMemoriesContent="",H("[UserMemoryManager] Saved Memories file not found, skipping saved memory load"))}catch(e){W("[UserMemoryManager] Error reading memory files:",e),this.recentConversationsContent="",this.savedMemoriesContent=""}}addRecentConversation(e,n){if(!le().enableRecentConversations){V("[UserMemoryManager] Recent history referencing is disabled, skipping analysis");return}if(e.length===0){V("[UserMemoryManager] No messages to analyze for user memory");return}this.updateMemory(e,n).catch(o=>{W("[UserMemoryManager] Background user memory operation failed:",o)})}async updateSavedMemory(e,n){if(!le().enableSavedMemory)return{error:"Saved memory is disabled, skipping save"};if(!e||e.trim()==="")return{error:"No content provided for saved memory"};if(!n)return{error:"No chat model available, skipping save"};try{let o=A2();await this.ensureMemoryFolderExists(o);let i=this.getSavedMemoriesFilePath(o);return{...await this.updateSavedMemoryFile(i,e,n),filePath:i}}catch(o){return{error:"Error saving memory: "+(o instanceof Error?o.message:String(o))}}}async getUserMemoryPrompt(){await this.loadMemory();try{let e=le(),n="";return e.enableRecentConversations&&this.recentConversationsContent&&(n+=`<recent_conversations>
${this.recentConversationsContent}
</recent_conversations>
The current time is ${this.getTimestamp()}.
<recent_conversations> are the recent conversations between you and the user.
You can use it to provide more context for your responses.
Only use the recent conversations if they are relevant to the current conversation.`),e.enableSavedMemory&&this.savedMemoriesContent&&(n+=`<saved_memories>
${this.savedMemoriesContent}
</saved_memories>
<saved_memories> are important memories that the user explicitly asked you to remember.
Use these memories to provide more personalized and contextually relevant responses.`),n.length>0?n:null}catch(e){return W("[UserMemoryManager] Error reading user memory content:",e),null}}getTimestamp(){let e=new Date,n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0");return`${n}-${r}-${o} ${i}:${s}`}async createConversationSection(e,n){let{title:r,summary:o}=await this.extractTitleAndSummary(e,n),i=this.getTimestamp(),s=`## ${r}
`;return s+=`**Time:** ${i}
`,s+=`**Summary:** ${o}
`,s}async updateMemory(e,n){if(this.isUpdatingMemory){H("[UserMemoryManager] Memory update already in progress, skipping.");return}this.isUpdatingMemory=!0;try{if(!n){W("[UserMemoryManager] No chat model available, skipping memory update");return}if(e.length===0){H("[UserMemoryManager] No messages available, skipping memory update");return}let r=await this.createConversationSection(e,n),o=A2();await this.ensureMemoryFolderExists(o),await this.addToRecentConversationsFile(this.getRecentConversationFilePath(o),r)}catch(r){W("[UserMemoryManager] Error analyzing chat messages for user memory:",r)}finally{this.isUpdatingMemory=!1}}async ensureMemoryFolderExists(e){await Fo(this.app.vault,e)}getRecentConversationFilePath(e=A2()){return`${e}/Recent Conversations.md`}getSavedMemoriesFilePath(e=A2()){return`${e}/Saved Memories.md`}async updateSavedMemoryFile(e,n,r){let o=this.app.vault.getAbstractFileByPath(e),i=o instanceof FW.TFile?await this.app.vault.read(o):"";if(!r)return{error:"No chat model available, skipping memory update"};let s=`You maintain a user's long-term personal memory list as concise bullet points.
You task is to update the user's memory list with the new statement.
Rules:
- Keep only stable, evergreen facts or preferences that will help future conversations.
- Remove duplicates and near-duplicates by merging them into one concise statement.
- If the new statement conflicts with older ones, keep the most recent truth and remove obsolete/conflicting entries.
- Prefer short, specific, and unambiguous phrasing.
- Preserve the language used in the input memories.
- Output only the memory content with each as a bullet point.
# OUTPUT FORMAT
Return the updated memory list with each as a bullet point.
- memory item 1
- memory item 2
- memory item 3
...
`,a=`<current_memories>
${i.trim()}
</current_memories>
<new_statement>
${n.trim()}
</new_statement>
`,l=[new Ag(s),new Zs(a)],c=null;try{c=(await r.invoke(l)).text??""}catch(u){return{error:"LLM call failed while updating saved memories: "+(u instanceof Error?u.message:String(u))}}return c==null||c.trim()===""?{error:"Empty content returned from LLM"}:(o instanceof FW.TFile?await this.app.vault.modify(o,c):await this.app.vault.create(e,c),{content:c})}async addToRecentConversationsFile(e,n){let r=this.app.vault.getAbstractFileByPath(e);if(r instanceof FW.TFile){let o=await this.app.vault.read(r),i;if(o.trim()==="")i=`${n.trim()}
`),o=`Your task is to analyze a conversation and generate both a title and a summary.
# OUTPUT FORMAT
You must return your response in the following JSON format:
{
"title": "Brief 2-8 word title capturing the main user intent",
"summary": "2-3 sentence summary at most including key details (e.g. user facts mentioned entities), and key conclusions if there are any."
}
# RULES
* Use the same language as the conversation`,i=`<conversation_text>
${r}
</conversation_text>
Generate a title and summary for this conversation:`,s=[new Ag(o),new Zs(i)];try{let l=(await n.invoke(s)).text,c=this.extractJsonFromResponse(l);try{let u=JSON.parse(c);return{title:u.title||"Untitled Conversation",summary:u.summary||"No summary available"}}catch(u){return W("[UserMemoryManager] Failed to parse LLM response as JSON:",u),{title:"Untitled Conversation",summary:"Summary generation failed"}}}catch(a){return W("[UserMemoryManager] Failed to extract title and summary:",a),{title:"Untitled Conversation",summary:"Summary generation failed"}}}};ge();W3();var yNr=J({statement:j().min(1).describe("The user statement for explicitly updating saved memories")}),m0e=t=>Ii({name:"updateMemory",description:"Update the user memory when the user explicitly asks to update the memory",schema:yNr,func:async({statement:e})=>{try{let n=new lM(t),r=qw.getInstance().getChatModel(),o=await n.updateSavedMemory(e,r);return o.error?{success:!1,message:o.error}:{success:!0,message:`Memory updated successfully into ${o.filePath}: ${o.content}`}}catch(n){return W("[updateMemoryTool] Error updating memory:",n),{success:!1,message:`Failed to save memory: ${n instanceof Error?n.message:String(n)}`}}}});var Jte=require("obsidian");wm();ge();var vtt=200;function h0e(t){return t.replace(/\\/g,"/").toLowerCase()}function wNr(t){return t.replace(/\.[^/.]+$/,"")}function vNr(t,e){if(e.length===0)return!1;let r=h0e(t).split("/").filter(Boolean);if(r.length<e.length)return!1;let o=r.slice(-e.length);for(let i=0;i<e.length;i+=1){let s=e[i];if(!s)return!1;let a=o[i];if(i===o.length-1){let l=wNr(a);if(!a.includes(s)&&!l.includes(s))return!1}else if(!a.includes(s))return!1}return!0}function btt(t){return/\.[^/]+$/.test(t)}async function bNr(t,e){let n=v=>{let _=t.vault.getAbstractFileByPath(v);return _ instanceof Jte.TFile?_:null},r=e.trim(),o=r.match(/^\s*\[\[([\s\S]+?)\]\]\s*$/),s=(o?o[1]:r).trim(),[a]=s.split("|"),[l]=a.split("#"),c=l.trim(),u=Array.from(new Set([r,s,c].map(v=>v.trim()).filter(Boolean)));for(let v of u){let _=n(v);if(_)return{type:"resolved",file:_};if(!btt(v))for(let S of[".md",".canvas"]){let k=n(`${v}${S}`);if(k)return{type:"resolved",file:k}}}let d=t.metadataCache,f=c.trim();if(d&&f){let v=new Set([f]);if(!btt(f))for(let _ of[".md",".canvas"])v.add(`${f}${_}`);for(let _ of v){let S=d.getFirstLinkpathDest?.(_,"");if(S instanceof Jte.TFile)return{type:"resolved",file:S}}}if(!f)return{type:"not_found"};let p=t.vault.getMarkdownFiles?.()??[];if(p.length===0)return{type:"not_found"};let m=h0e(f),h=new Set([m]);if(!btt(f))for(let v of[".md",".canvas"])h.add(h0e(`${f}${v}`));for(let v of p){let _=h0e(v.path);if(h.has(_))return{type:"resolved",file:v}}let g=f.split("/").pop();if(g){let v=g.toLowerCase(),_=p.filter(S=>S.basename.toLowerCase()===v);if(_.length===1)return{type:"resolved",file:_[0]};if(_.length>1)return{type:"not_unique",matches:_}}let w=m.split("/").filter(Boolean);if(w.length===0)return{type:"not_found"};let y=p.filter(v=>vNr(v.path,w));return y.length===1?{type:"resolved",file:y[0]}:y.length>1?{type:"not_unique",matches:y}:{type:"not_found"}}async function _Nr(t,e){try{return await t.vault.read(e)}catch(n){return V(`readNote: failed to read ${e.path}`,n),""}}function xNr(t){let e=new Map,n=t.vault.getMarkdownFiles?.()??[];for(let r of n)if(r instanceof Jte.TFile){let o=e.get(r.basename)??[];o.push(r),e.set(r.basename,o)}return e}function SNr(t,e,n,r){let o=e.trim();if(!o)return[];let i=new Map,s=t.metadataCache.getFirstLinkpathDest?.(o,n);if(s instanceof Jte.TFile&&i.set(s.path,s),!/\.[^./]+$/.test(o)){let a=o.split("/").pop()??o,l=r.get(a)??[];for(let c of l)i.set(c.path,c)}return Array.from(i.values())}function CNr(t,e,n){if(!e)return[];let r=/\[\[([^\]]+)\]\]/g,o=new Map,i=null,s;for(;(s=r.exec(e))!==null;){if(s.index>0&&e[s.index-1]==="!")continue;let a=s[1]?.trim();if(!a)continue;let[l,c]=a.split("|"),[u,d]=l.split("#"),f=u?.trim();if(!f)continue;let p=`${f}|${c??""}|${d??""}`;if(o.has(p))continue;i||(i=xNr(t));let m=SNr(t,f,n.path,i);o.set(p,{linkText:f,displayText:c?.trim()||f,section:d?.trim()||void 0,candidat
`).trimEnd(),heading:d})}return i}var TNr=t=>{if(t===void 0)return 0;let e=typeof t=="string"?Number(t.trim()):t;return!Number.isInteger(e)||e<0?null:e},INr=J({notePath:j().min(1).describe("Full path to the note (relative to the vault root) that needs to be read, such as 'Projects/plan.md'."),chunkIndex:an([zt().int().min(0),j()]).optional().describe("0-based chunk index to read. Omit to read the first chunk.")}),gyn=t=>Ii({name:"readNote",description:"Read a single note in search v3 sized chunks. Use only when you already know the exact note path and need its contents.",schema:INr,func:async({notePath:e,chunkIndex:n})=>{let r=TNr(n),o=e.trim();if(o.startsWith("/"))return{notePath:o,status:"invalid_path",message:"Provide the note path relative to the vault root without a leading slash."};if(r===null)return{notePath:o,status:"invalid_chunk_index",message:"chunkIndex must be a non-negative integer (0-based). Omit it to read the first chunk."};let i=await bNr(t,o);if(i.type==="not_found")return V(`readNote: note not found or not a file (${o})`),{notePath:o,status:"not_found",message:`Note "${o}" was not found or is not a readable file.`};if(i.type==="not_unique")return V(`readNote: ambiguous note path "${o}" matched multiple files`,i.matches.map(m=>m.path)),{notePath:o,status:"not_unique",message:`Multiple notes match "${o}". Provide a more specific path.`,candidates:i.matches.map(m=>({path:m.path,title:m.basename}))};let s=i.file,a=s.path,l=await _Nr(t,s),c=kNr(s,l),u=c.length;if(u===0)return{notePath:a,status:"empty",message:`No readable content was found in "${a}".`};if(r>=u)return{notePath:a,status:"out_of_range",message:`Chunk index ${r} exceeds available chunks (last index ${u-1}).`,totalChunks:u};let d=c[r];H(`readNote: returning chunk ${d.chunkIndex} of ${u} for ${a}`);let f=d.chunkIndex<u-1,p=CNr(t,d.content,s);return{notePath:a,noteTitle:s.basename,heading:d.heading,chunkId:d.id,chunkIndex:d.chunkIndex,totalChunks:u,hasMore:f,nextChunkIndex:f?d.chunkIndex+1:null,content:d.content,mtime:s.stat.mtime,linkedNotes:p.length>0?p:void 0}}});wm();function g0e(t,e,n,r){let o=t.trim();return o.length>0?o:n==="ENOENT"?`CLI binary not found. Tried: ${r.length>0?r.join(", "):"unknown"}. Ensure Obsidian CLI is installed or set OBSIDIAN_CLI_BINARY/OBSIDIAN_CLI_PATH.`:n!==null?`Obsidian CLI failed with error code ${String(n)}`:e!==null?`Obsidian CLI failed with exit code ${e}`:"Obsidian CLI command failed for an unknown reason"}function G$(t){throw new Error(g0e(t.stderr,t.exitCode,t.errorCode,t.attemptedBinaries))}var A7i=Ii({name:"obsidianDailyRead",description:"Read the current daily note via Obsidian CLI and return the note content as plain text.",schema:J({vault:j().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await Gan(t);if(!e.ok)throw new Error(`Failed to read daily note via Obsidian CLI: ${g0e(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_daily_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}}),yyn=Ii({name:"obsidianRandomRead",description:"Read a random note via Obsidian CLI and return the note content as plain text.",schema:J({vault:j().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await Zan(t);if(!e.ok)throw new Error(`Failed to read random note via Obsidian CLI: ${g0e(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_random_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}});wm();function V3(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e!=="command"&&e!=="vault"&&n!==void 0))}var PNr=J({command:ym(["daily","daily:read","daily:path"]).describe("daily — create today's daily note (applies configured template). daily:read — read today's daily note content. daily:path — get the vault-relative file path."),vault:j().optional().describe("Optional vault name to
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
If there's nothing in the chat history, just return the follow up question.
`);return await fv(async()=>{let o=YT.instance.getCurrentChainManager().chatModelManager.getChatModel(),i="",s=await o.stream([{role:"user",content:n.replace("{chat_history}",r).replace("{question}",t)}]);for await(let l of s)i+=k2(l.content);let a=NPe(i);return Bat(a)})}xt();Ov();ge();Bl();Ee();vt();tn();var LNr="https://api.firecrawl.dev/v2/search",DNr="https://api.perplexity.ai/chat/completions",$Nr="https://api.parallel.ai/v1/search",FNr=200,zNr=5e3,UNr="https://api.exa.ai/search",Tyn="https://api.supadata.ai/v1/transcript",BNr=64*1024,jNr=2e3,kyn=6e4;function Iyn(t=hS,e=_tt,n=xtt){let r=null,o=null,i=null,s=!1,a=async c=>{if(!t())throw new Error("Self-host web search is not available for this session.");if(!e())throw new Error("Add an API key for the selected self-host search provider.");return n(c)},l=()=>{let c=Te("http"),d=Te("crypto").randomBytes(32).toString("hex");return new Promise((f,p)=>{let m=!1,h=y=>{m||(m=!0,i=null,p(y))},g=y=>{m||(m=!0,i=null,f(y))};i=h;let w=c.createServer((y,v)=>{HNr(y,v,d,a)});r=w,w.once("error",h),w.listen(0,"127.0.0.1",()=>{if(s){w.close(),h(new Error("Self-host web search channel is closed."));return}let y=w.address();w.on("error",v=>{W("[AgentMode] Self-host web search channel failed",v)}),w.unref(),g(Object.freeze({url:`http://127.0.0.1:${y.port}/search`,token:d}))})})};return Object.freeze({getChannel(){return s?Promise.reject(new Error("Self-host web search channel is closed.")):(o??(o=l()),o)},dispose(){s=!0,i?.(new Error("Self-host web search channel is closed.")),r?.close(),r=null,o=null}})}async function HNr(t,e,n,r){if(t.method!=="POST"||t.url!=="/search"){Xte(e,404,{error:"Not found."});return}if(t.headers.authorization!==`Bearer ${n}`){Xte(e,401,{error:"Unauthorized."});return}try{let o=await WNr(t);if(!o.trim()){Xte(e,400,{error:"A non-empty query is required."});return}Xte(e,200,await r(o))}catch(o){let i=o instanceof Error?o.message:String(o);Xte(e,i==="Request body is too large."?413:500,{error:i})}}async function WNr(t){t.setEncoding("utf8");let e="";for await(let n of t)if(e+=n,e.length>BNr)throw new Error("Request body is too large.");return e}function Xte(t,e,n){t.writeHead(e,{"Content-Type":"application/json; charset=utf-8"}),t.end(JSON.stringify(n))}function Pyn(t,e){if(!Array.isArray(t))return{content:"",citations:[]};let n=[],r=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,s=typeof i.title=="string"&&i.title.trim()?i.title.trim():"Untitled",a=typeof i.url=="string"?i.url.trim():"",l=Array.isArray(i[e])?i[e].filter(u=>typeof u=="string"&&u.trim().length>0):[],c=[`### ${s}`,l.join(`
`),a?`Source: ${a}`:""].filter(Boolean).join(`
`);n.push(c),a&&r.push(a)}return{content:n.join(`
`),citations:r}}function _tt(){let t=le();switch(t.selfHostSearchProvider){case"parallel":return!!t.parallelApiKey;case"exa":return!!t.exaApiKey;case"perplexity":return!!t.perplexityApiKey;case"firecrawl":default:return!!t.firecrawlApiKey}}async function VNr(t,e){let n=Date.now(),r=await Ja(LNr,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({query:t,limit:5})});if(!r.ok){let u=await r.text();throw new Error(`Firecrawl search failed (${r.status}): ${u}`)}let i=(await r.json())?.data,s=Array.isArray(i)?i:Array.isArray(i?.web)?i.web:[],a=[],l=[];for(let u of s){let d=u.title||"Untitled",f=u.description||"",p=u.url||"";a.push(`### ${d}
${f}
Source: ${p}`),p&&l.push(p)}let c=Date.now()-n;return H(`[selfHostWebSearch] Firecrawl: ${s.length} results in ${c}ms`),{content:a.join(`
`),citations:l}}async function qNr(t,e){let n=await Ja(DNr,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({model:"sonar",messages:[{role:"user",content:t}]})});if(!n.ok){let s=await n.text();throw new Error(`Perplexity Sonar search failed (${n.status}): ${s}`)}let r=await n.json(),o=r?.choices?.[0]?.message?.content??"",i=Array.isArray(r?.citations)?r.citations:[];return{content:o,citations:i}}async function KNr(t,e){let n=await Ja($Nr,{method:"POST",headers:{"x-api-key":e,"Content-Type":"application/json"},body:JSON.stringify({objective:t.slice(0,zNr),search_queries:[t.slice(0,FNr)]})});if(!n.ok){let o=await n.text();throw new Error(`Parallel search failed (${n.status}): ${o}`)}let r=await n.json();return Pyn(r?.results,"excerpts")}async function GNr(t,e){let n=await Ja(UNr,{method:"POST",headers:{"x-api-key":e,"Content-Type":"application/json"},body:JSON.stringify({query:t,numResults:5,contents:{highlights:!0}})});if(!n.ok){let o=await n.text();throw new Error(`Exa search failed (${n.status}): ${o}`)}let r=await n.json();return Pyn(r?.results,"highlights")}async function xtt(t){let e=le();switch(e.selfHostSearchProvider){case"parallel":return KNr(t,e.parallelApiKey);case"exa":return GNr(t,e.exaApiKey);case"perplexity":return qNr(t,e.perplexityApiKey);case"firecrawl":default:return VNr(t,e.firecrawlApiKey)}}async function y0e(t){let e=Date.now(),n=le().supadataApiKey,r=`${Tyn}?url=${encodeURIComponent(t)}&mode=auto&text=true`,o=await Ja(r,{method:"GET",headers:{"x-api-key":n,Accept:"application/json"}});if(o.status===200){let s=await o.json(),a=Date.now()-e;return H(`[selfHostYoutube4llm] transcript received in ${a}ms`),{response:{transcript:s.content||""},elapsed_time_ms:a}}if(o.status===201||o.status===202){let a=(await o.json()).job_id;if(!a)throw new Error("Supadata returned async status but no job_id");return await ZNr(a,n,e)}let i=await o.text();throw new Error(`Supadata transcript request failed (${o.status}): ${i}`)}async function ZNr(t,e,n){let r=Date.now()+kyn,o=`${Tyn}/${t}`;for(;Date.now()<r;){await new Promise(a=>window.setTimeout(a,jNr));let i=await Ja(o,{method:"GET",headers:{"x-api-key":e,Accept:"application/json"}});if(i.status===200){let a=await i.json(),l=Date.now()-n;return H(`[selfHostYoutube4llm] async transcript completed in ${l}ms`),{response:{transcript:a.content||""},elapsed_time_ms:l}}if(i.status===202)continue;let s=await i.text();throw W(`[selfHostYoutube4llm] poll failed (${i.status}): ${s}`),new Error(`Supadata poll failed (${i.status}): ${s}`)}throw new Error(`Supadata transcript timed out after ${kyn}ms`)}ge();Bl();ge();dp();Ee();pr();Ayn();Wu();var Stt=class extends Lo{constructor(){super(...arguments);A(this,"lc_namespace",["langchain_core","documents","transformers"])}invoke(e,n){return this.transformDocuments(e)}};pr();QE();IS();Wu();var w0e=class extends Lo{constructor(e){super(e);A(this,"callbacks");A(this,"tags");A(this,"metadata");A(this,"verbose");this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,n){throw new Error("Not implemented!")}async invoke(e,n){let r=uo(YL(n)),o=await(await Hu.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{let i=await this._getRelevantDocuments(e,o);return await o?.handleRetrieverEnd(i),i}catch(i){throw await o?.handleRetrieverError(i),i}}};ge();s0();dp();Id();Ee();var YNr=20,Eyn=1e3,v0e=class extends w0e{constructor(n,r){super();this.app=n;this.options=r;this.lc_namespace=["miyo_semantic_retriever"];this.client=new Su,this.returnAll=!!r.returnAll,this.finalK=r.maxK>0?r.maxK:YNr,this.minSimilarityScore=r.minSimilarityScore??.1}async getRelevantDocuments(n,r){let o=await this.searchMiyo(n),i=this.deduplicateResults(o),a=this.filterByCopilotPatterns(i).slice(0,this.finalK);return le().debug&&this.logDebugInfo(n,o,a),a}filterByCopilotPatterns(n){let r=n4t(this.app),o=[],i=[];for(l
which is longer than the specified ${this.chunkSize}`),o.length>0)){let c=this.joinDocs(o,n);for(c!==null&&r.push(c);i>this.chunkOverlap||i+l+o.length*n.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(a),i+=l}let s=this.joinDocs(o,n);return s!==null&&r.push(s),r}};var ktt=class Ctt extends Myn{constructor(n){super(n);A(this,"separators",[`
`,`
`," ",""]);this.separators=n?.separators??this.separators,this.keepSeparator=n?.keepSeparator??!0}static lc_name(){return"RecursiveCharacterTextSplitter"}async _splitText(n,r){let o=[],i=r[r.length-1],s;for(let u=0;u<r.length;u+=1){let d=r[u];if(d===""){i=d;break}if(n.includes(d)){i=d,s=r.slice(u+1);break}}let a=this.splitOnSeparator(n,i),l=[],c=this.keepSeparator?"":i;for(let u of a)if(await this.lengthFunction(u)<this.chunkSize)l.push(u);else{if(l.length){let d=await this.mergeSplits(l,c);o.push(...d),l=[]}if(!s)o.push(u);else{let d=await this._splitText(u,s);o.push(...d)}}if(l.length){let u=await this.mergeSplits(l,c);o.push(...u)}return o}async splitText(n){return this._splitText(n,this.separators)}static fromLanguage(n,r){return new Ctt({...r,separators:Ctt.getSeparatorsForLanguage(n)})}static getSeparatorsForLanguage(n){if(n==="cpp")return[`
- These terms determine search ranking - must be from original query
ALTERNATIVE QUERIES (for recall - specific alternative phrasings):
- Alternative phrasings of the query (specific enough to be useful for search)
Example: "find my piano notes"
- Salient (from original): piano, notes
- Queries: "piano lesson notes", "piano practice sheets"
Example: "查找我的学习笔记"
- Salient (from original): 学习, 笔记
- Queries: "个人笔记文档"
Format:
<salient>
<term>word_from_original_query</term>
</salient>
<queries>
<query>alternative query</query>
</queries>`;var A0e=E0e;ge();Id();var G3=class G3{constructor(e){this.app=e}async batchCachedReadGrep(e,n){let{inclusions:r,exclusions:o}=Ua(),s=this.app.vault.getMarkdownFiles().filter(h=>Ks(this.app,h,r,o)),a=G3.CONFIG.BATCH_SIZE,l=e.map(h=>h.toLowerCase()).filter(h=>this.isGrepWorthy(h)),c=[],u=G3.CONFIG.YIELD_INTERVAL;for(let h=0;h<s.length;h++){let g=s[h],w=g.path.toLowerCase(),y=0;for(let v of l)w.includes(v)&&y++;y>0&&c.push({path:g.path,matchCount:y}),h>0&&h%u===0&&await new Promise(v=>window.setTimeout(v,0))}c.sort((h,g)=>g.matchCount-h.matchCount);let d=new Set(c.map(h=>h.path)),f=Math.max(0,n-d.size),p=new Set;if(f>0)for(let h=0;h<s.length&&p.size<f;h+=a){let g=s.slice(h,h+a);await Promise.all(g.map(async w=>{if(!(p.size>=f)&&!d.has(w.path))try{let v=(await this.app.vault.cachedRead(w)).toLowerCase();for(let _ of l)if(v.includes(_)){p.add(w.path);break}}catch(y){H(`GrepScanner: Skipping file ${w.path}: ${y}`)}})),h%G3.CONFIG.YIELD_INTERVAL===0&&await new Promise(w=>window.setTimeout(w,0))}let m=[...d,...p].slice(0,n);if(m.length>0){let h=Math.min(d.size,n),g=m.length-h;H(` Grep: ${m.length} files match (${h} path, ${g} content) [${e.slice(0,3).join(", ")}${e.length>3?"...":""}]`)}return m}async grep(e,n=200){return this.batchCachedReadGrep([e],n)}isGrepWorthy(e){return!(!e||e.length<=1)}};G3.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};var M0e=G3;ge();function w_(t){let e=t.lastIndexOf("#");return e===-1?t:t.substring(0,e)}var l1r={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},O0e=class{constructor(e){this.config=l1r;this.app=e||null}setConfig(e){this.config={...this.config,...e}}applyBoosts(e){if(!this.config.enabled||e.length===0)return e;let n=this.calculateFolderStats(e);return this.logBoostedFolders(n),e.map(r=>{let o=w_(r.id),i=this.extractFolder(o),s=n.get(i);if(s){let a=r.score*s.boostFactor;return{...r,score:a,explanation:r.explanation?{...r.explanation,folderBoost:{folder:s.folderPath,documentCount:s.documentCount,totalDocsInFolder:s.totalDocsInFolder,relevanceRatio:s.relevanceRatio,boostFactor:s.boostFactor},finalScore:a}:void 0}}return r})}calculateFolderStats(e){let n=new Map;for(let s of e){let a=w_(s.id),l=this.extractFolder(a);n.has(l)||n.set(l,new Set),n.get(l).add(a)}let r=new Map;for(let[s,a]of n.entries())r.set(s,a.size);let o=this.getTotalDocsPerFolder(),i=new Map;for(let[s,a]of r.entries()){let l=o.get(s)||a,c=a/l;if(a>=this.config.minDocsForBoost&&c>=this.config.minRelevanceRatio){let d=1+(1+Math.log2(a+1)-1)*Math.sqrt(c),f=Math.min(d,this.config.maxBoostFactor);i.set(s,{folderPath:s,documentCount:a,totalDocsInFolder:l,relevanceRatio:c,boostFactor:f})}}return i}getTotalDocsPerFolder(){let e=new Map;if(!this.app)return e;let n=this.app.vault.getMarkdownFiles();for(let r of n){let o=this.extractFolder(r.path);e.set(o,(e.get(o)||0)+1)}return e}extractFolder(e){return e.substring(0,e.lastIndexOf("/"))||""}logBoostedFolders(e){let n=Array.from(e.values()).sort((r,o)=>o.relevanceRatio-r.relevanceRatio);n.length>0&&(H(`Folder boost: Boosting ${n.length} folders with significant relevance`),n.slice(0,5).forEach(r=>{let o=(r.relevanceRatio*100).toFixed(1);H(` ${r.folderPath||"(root)"}: ${r.documentCount}/${r.totalDocsInFolder} docs (${o}% relevant, ${r.boostFactor.toFixed(2)}x boost)`)}))}getFolderBoosts(e){return this.config.enabled?this.calculateFolderStats(e):new Map}};ge();var Hyn=require("obsidian");var c1r={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},R0e=class{constructor(e,n={}){this.metadataCache=e.metadataCache,this.config={...c1r,...n}}applyBoost(e){if(!this.config.enabled||e.length===0)return e;let n=this.filterCandidates(e);if(n.length<2)return e;let r=new Set(n.map(a=>w_(a.id))),o=new Map;for(let a of r){let l=this.calculateConnections(a,r);o.set(a,l)}let i=e.map(a=>{let l=w_(a.id),c=o.get(l);return!c||c.boostMultiplier===1?a:{...a,score:a.score*c.boostMultiplier,explanation:a.explanation?{...a.explanation,graphConnections:{backlinks:c.backlinks.length,coCitations:c.coCitations.l
* totalUniqueTags: number of unique tags indexed across the vault
* returnedTagCount: number of tag entries included in this response
* totalOccurrences: total tag occurrences across included sources
* includedSources: sources represented in the counts (frontmatter, inline)
* truncated: whether the list was shortened due to limits
* tags: array of tag objects { tag, occurrences, frontmatterOccurrences, inlineOccurrences }
${JSON.stringify(t)}`}var ewn=t=>Ii({name:"getTagList",description:"Get the list of tags in the vault with occurrence statistics.",schema:_1r,func:async e=>{let n=x1r(t),r=e?.includeInline??!0,o=e?.maxEntries??b1r;if(!n)return Qyn({totalUniqueTags:0,returnedTagCount:0,totalOccurrences:0,includedSources:r?["frontmatter","inline"]:["frontmatter"],truncated:!1,tags:[],note:"Metadata cache is unavailable. Try again after the vault finishes indexing."});let i=S1r(n,r,o),s=C1r(i);return Qyn(s)}});var own=R(twn(),1),rne=R(uO(),1);var Ho;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(Ho||(Ho={}));var cc;(function(t){t[t.SUNDAY=0]="SUNDAY",t[t.MONDAY=1]="MONDAY",t[t.TUESDAY=2]="TUESDAY",t[t.WEDNESDAY=3]="WEDNESDAY",t[t.THURSDAY=4]="THURSDAY",t[t.FRIDAY=5]="FRIDAY",t[t.SATURDAY=6]="SATURDAY"})(cc||(cc={}));var Xg;(function(t){t[t.JANUARY=1]="JANUARY",t[t.FEBRUARY=2]="FEBRUARY",t[t.MARCH=3]="MARCH",t[t.APRIL=4]="APRIL",t[t.MAY=5]="MAY",t[t.JUNE=6]="JUNE",t[t.JULY=7]="JULY",t[t.AUGUST=8]="AUGUST",t[t.SEPTEMBER=9]="SEPTEMBER",t[t.OCTOBER=10]="OCTOBER",t[t.NOVEMBER=11]="NOVEMBER",t[t.DECEMBER=12]="DECEMBER"})(Xg||(Xg={}));function nwn(t,e){e=e.add(1,"day"),J$(t,e),Y3(t,e)}function v_(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function z0e(t,e){t.assign("hour",e.hour()),t.assign("minute",e.minute()),t.assign("second",e.second()),t.assign("millisecond",e.millisecond()),t.get("hour")<12?t.assign("meridiem",Ho.AM):t.assign("meridiem",Ho.PM)}function J$(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function Y3(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var Gtt=R(uO(),1);var k1r={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:t=>rwn(t,Xg.MARCH,cc.SUNDAY,2),dstEnd:t=>rwn(t,Xg.OCTOBER,cc.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:t=>dO(t,Xg.MARCH,cc.SUNDAY,2,2),dstEnd:t=>dO(t,Xg.NOVEMBER,cc.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:t=>dO(t,Xg.MARCH,cc.SUNDAY,2,2),dstEnd:t=>dO(t,Xg.NOVEMBER,cc.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:t=>dO(t,Xg.MARCH,cc.SUNDAY,2,2),dstEnd:t=>dO(t,Xg.NOVEMBER,cc.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:t=>dO(t,Xg.MARCH,cc.SUNDAY,2,2),dstEnd:t=>dO(t,Xg.NOVEMBER,cc.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEK
IMPORTANT: This tool is typically used as the first step before localSearch when searching notes by time.
EXAMPLE WORKFLOW:
1. User: "what did I do last week"
2. First call getTimeRangeMs with timeExpression: "last week"
3. Then use the returned time range with localSearch`)}),func:async({timeExpression:t})=>{let e=HLr(t);return e||{error:`Unable to parse time expression: ${t}`}}});function VLr(t){let e=t.toString().length===10?t*1e3:t,n=jn.fromMillis(e);return WLr(n)}var Qwn=Ii({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:J({epoch:zt().describe("Unix timestamp in seconds or milliseconds")}),func:async({epoch:t})=>VLr(t)});async function qLr(t,e,n){let r=ant(e),o=ant(n);try{let i=jn.now().setZone(r),s=Zwn(t,i.toJSDate());if(!s)throw new Error(`Could not parse time: ${t}`);let a=jn.fromJSDate(s,{zone:r}),l=a.setZone(o);if(!l.isValid)throw new Error("Invalid timezone conversion");let c=l.toJSDate(),u=l.offset;return{epoch:Math.floor(c.getTime()),isoString:c.toISOString(),userLocaleString:l.toLocaleString(jn.DATETIME_FULL),localDateString:l.toISODate()||"",timezoneOffset:u,timezone:l.offsetNameShort||o,originalTime:a.toLocaleString(jn.TIME_SIMPLE)+" "+a.offsetNameShort,convertedTime:l.toLocaleString(jn.TIME_SIMPLE)+" "+l.offsetNameShort}}catch(i){throw new Error(`Failed to convert time: ${i.message}`)}}var evn=Ii({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:J({time:j().describe(`Time to convert. Supports various formats:
- 12-hour: "6pm", "3:30 PM", "11:45 am"
- 24-hour: "18:00", "15:30", "23:45"
- Relative: "noon", "midnight"`),fromOffset:j().describe(`Source UTC offset. Must be numeric, not timezone name.
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:j().describe(`Target UTC offset. Must be numeric, not timezone name.
Examples: "+9" for Tokyo, "-5" for NY, "+5:30" for Mumbai
EXAMPLE USAGE:
- "what time is 6pm PT in Tokyo" → time: "6pm", fromOffset: "-8", toOffset: "+9"
- "convert 3:30 PM EST to London time" → time: "3:30 PM", fromOffset: "-5", toOffset: "+0"
- "what is 9am Beijing time in New York" → time: "9am", fromOffset: "+8", toOffset: "-5"`)}),func:async({time:t,fromOffset:e,toOffset:n})=>qLr(t,e,n)});$H();Ov();Bl();Ee();vt();wm();ge();var tvn=5e4,nvn=Ii({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:J({_userMessageContent:j().optional().describe("Internal: user message content injected by the system")}),func:async t=>{let{_userMessageContent:e}=t;if(typeof e!="string")return{success:!1,message:"Invalid input: User message must be a string"};if(e.length>tvn)return{success:!1,message:`Input too long: Maximum allowed length is ${tvn} characters`};let n=zat(e);if(n.length===0)return{success:!1,message:"No YouTube URLs found in the user prompt. URLs must be in the user prompt instead of the context notes."};let r=await Promise.all(n.map(async i=>{try{let s=hS()&&le().supadataApiKey?await y0e(i):await ua.getInstance().youtube4llm(i);return s.response.transcript?{url:i,success:!0,transcript:s.response.transcript,elapsed_time_ms:s.elapsed_time_ms}:{url:i,success:!1,message:"Transcript not available. Only English videos with auto transcript enabled are supported"}}catch(s){return W(`Error transcribing YouTube video ${i}:`,s),{url:i,success:!1,message:"An error occurred while transcribing the YouTube video"}}}));return{success:r.some(i=>i.success),results:r,total_urls:n.length}}});function KLr(t){return[{tool:$0e(t),metadata:{id:"localSearch",displayName:"Vault Search",description:"Search through your vault notes",category:"search",copilotCommands:["@vault"],customPromptInstructions:`For localSearch (searching notes based on their contents in the vault):
- You MUST always provide both "query" (string) and "salientTerms" (array of strings)
- salientTerms MUST be extracted from the user's original query - never invent new terms
- They are keywords used for BM25 full-text search to find notes containing those exact words
- Treat every token that begins with "#" as a high-priority salient term. Keep the leading "#" and the full tag hierarchy (e.g., "#project/phase1").
- Include tagged terms alongside other meaningful words; never strip hashes or rewrite tags into plain words.
- Extract meaningful content words from the query (nouns, verbs, names, etc.)
- Exclude common words like "what", "I", "do", "the", "a", etc.
- Exclude time expressions like "last month", "yesterday", "last week"
- Preserve the original language - do NOT translate terms to English
Evaluating search results and re-searching:
- Results include a relevance quality summary: high (score ≥0.7), medium (0.3-0.7), low (<0.3)
- If most results are low relevance or miss key concepts from the user's question:
1. Try searching again with synonyms or related terms
2. Use more specific phrasing if query was too broad
3. Use more general phrasing if query was too narrow
- Example: "machine learning algorithms" returned low results → try "ML models", "neural networks", or "AI techniques"
For time-based searches (e.g., "what did I do last week"):
1. First call getTimeRangeMs with timeExpression: "last week"
2. Then use localSearch with the returned timeRange, query matching the user's question, and salientTerms: [] (empty for generic time queries)
For time-based searches with meaningful terms (e.g., "python debugging notes from yesterday"):
1. First call getTimeRangeMs with timeExpression: "yesterday"
2. Then use localSearch with the returned timeRange, query: "python debugging notes", salientTerms: ["python", "debugging", "notes"]
For broad searches:
- If the user wants a comprehensive list, use getFileTree to get all note titles as reference. This helps verify search completeness and identify notes the search may have missed.`}},{tool:F0e,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",category:"search",copilotCommands:["@websearch","@web"],customPromptInstructions:`For webSearch:
- ONLY use when the user's query contains explicit web-search intent like:
* "Google", "search online", "look up online", "search the web"
- Always provide an empty chatHistory array
Example: "search the web for python tutorials" → query: "python tutorials", chatHistory: []`}},{tool:Ywn,metadata:{id:"getCurrentTime",displayName:"Get Current Time",description:"Get the current time in any timezone",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time queries (IMPORTANT: Always use UTC offsets, not timezone names):
- If the user mentions a specific city, country, or timezone name (e.g., "Tokyo", "Japan", "JST"), you MUST convert it to the correct UTC offset and pass it via the timezoneOffset parameter (e.g., "+9").
- Only omit timezoneOffset when the user asks for the current local time without naming any location or timezone.
- If you cannot confidently determine the offset from the user request, ask the user to clarify before calling the tool.
Examples:
- "what time is it" (local time) → call with no parameters
- "what time is it in Tokyo" (UTC+9) → timezoneOffset: "+9"
- "what time is it in New York" (UTC-5 or UTC-4 depending on DST) → timezoneOffset: "-5"`}},{tool:Qwn,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:Xwn,metadata:{id:"getTimeRangeMs",displayName:"Get Time Range",description:"Convert time expressions to date ranges",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time-based queries:
- Use this tool to convert time expressions like "last week", "yesterday", "last month" to proper time ranges
- This is typically the first step before using localSearch with a time range
Example: For "last week" → timeExpression: "last week"`}},{tool:evn,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:
Example: "what time is 6pm PT in Tokyo" (PT is UTC-8 or UTC-7, Tokyo is UTC+9) → time: "6pm", fromOffset: "-8", toOffset: "+9"`}},{tool:gyn(t),metadata:{id:"readNote",displayName:"Read Note",description:"Read a specific note in sequential chunks using its own line-chunking logic.",category:"file",requiresVault:!0,isAlwaysEnabled:!0,customPromptInstructions:`For readNote:
- Decide based on the user's request: only call this tool when the question requires reading note content.
- If the user asks about a note title that is already mentioned in the current or previous turns of the conversation, or linked in <active_note> or <note_context> blocks, call readNote directly—do not use localSearch to look it up. Even if the note title mention is partial but similar to what you have seen in the context, try to infer the correct note path from context. Skip the tool when a note is irrelevant to the user query.
- If the user asks about notes linked from that note, read the original note first, then follow the "linkedNotes" paths returned in the tool result to inspect those linked notes.
- Always start with chunk 0 (omit chunkIndex or set it to 0). Only request the next chunk if the previous chunk did not answer the question.
- Pass vault-relative paths without a leading slash. If a call fails, adjust the path (for example, add ".md" or use an alternative candidate) and retry only if necessary.
- Every tool result may include a "linkedNotes" array. If the user needs information from those linked notes, call readNote again with one of the provided candidate paths, starting again at chunk 0. Do not expand links you don't need.
- Stop calling readNote as soon as you have the required information.
- Always call getFileTree to get the exact note path if it is not provided in the context before calling readNote.
Examples:
- First chunk: notePath: "Projects/launch-plan.md" (chunkIndex omitted or 0)
- Next chunk: notePath: "Projects/launch-plan.md", chunkIndex: 1`}},{tool:Ixe(t),metadata:{id:"writeFile",displayName:"Write to File",description:"Create or rewrite files in your vault",category:"file",requiresVault:!0,timeoutMs:0,copilotCommands:["@composer"],customPromptInstructions:`For writeFile:
- NEVER display the file content directly in your response
- Always pass the complete file content to the tool
- Include the full path to the file
- You MUST explicitly call writeFile for any intent of updating or creating files
- Do not call writeFile tool again if the result is not accepted
- Do not call writeFile tool if no change needs to be made
- Always create new notes in root folder or folders the user explicitly specifies
- When creating a new note in a folder, you MUST use getFileTree to get the exact folder path first
Examples:
- Basic: path: "path/to/note.md", content: "FULL CONTENT OF THE NOTE"
- Skip confirmation: path: "path/to/note.md", content: "FULL CONTENT", confirmation: false`}},{tool:qan(t),metadata:{id:"editFile",displayName:"Edit File",description:"Make a targeted, single-match edit to an existing file",category:"file",requiresVault:!0,timeoutMs:0,customPromptInstructions:`For editFile:
- Use for targeted edits; use writeFile for major rewrites or new files
- oldText must uniquely identify the location — include surrounding context lines if needed
- The tool automatically handles minor whitespace/quote differences (fuzzy matching)
- Call once per edit; for multiple edits call the tool multiple times
Example: Add "Bob Johnson" to attendees in notes/meeting.md:
path: "notes/meeting.md"
oldText: "## Attendees\\n- John Smith\\n- Jane Doe"
newText: "## Attendees\\n- John Smith\\n- Jane Doe\\n- Bob Johnson"`}},{tool:nvn,metadata:{id:"youtubeTranscription",displayName:"YouTube Transcription",description:"Get transcripts from YouTube videos",category:"media",isPlusOnly:!0,requiresUserMessageContent:!0,customPromptInstructions:`For youtubeTranscription:
- Use when user provides YouTube URLs
- No parameters needed - the tool will process URLs from the conversation`}}]}function GLr(t){Md.getInstance().register({tool:Yan(t,t.vault.getRoot()),metadata:{id:"getFileTree",displayName:"File Tree",description:"Browse vault file structure",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getFileTree:
- Use to browse the vault's file structure including paths of notes and folders
- Always call this tool to explore the exact path of notes or folders when you are not given the exact path.
- DO NOT use this tool to look up note contents or metadata - use localSearch or readNote instead.
- No parameters needed
Example queries that should use getFileTree:
- "Create a new note in the projects folder" → call getFileTree to get the exact folder path
- "Create a new note using the quick note template" → call getFileTree to look up the template path
- "How many files are in the projects folder" → call getFileTree to list all files`}})}function ZLr(t){Md.getInstance().register({tool:ewn(t),metadata:{id:"getTagList",displayName:"Tag List",description:"List vault tags with occurrence statistics",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getTagList:
- Use to inspect existing tags before suggesting new ones or reorganizing notes.
- Omit parameters to include both frontmatter and inline tags.
- Set includeInline to false when you only need frontmatter-defined tags.
- Use maxEntries to limit output for very large vaults.
Examples:
- Default (all tags): call with no parameters
- Frontmatter only: includeInline: false`}})}function YLr(t){Md.getInstance().register({tool:m0e(t),metadata:{id:"updateMemory",displayName:"Update Memory",description:"Save information to user memory when the user explicitly asks to remember something or update the memory",category:"memory",copilotCommands:["@memory"],isAlwaysEnabled:!0,customPromptInstructions:`For updateMemory:
- Use this tool to update the memory when the user explicitly asks to update the memory
- DO NOT use for general information - only for personal facts, preferences, or specific things the user wants stored
Example: statement: "I'm studying Japanese and I'm preparing for JLPT N3"`}})}function JLr(){let t=Md.getInstance();t.register({tool:wyn,metadata:{id:"obsidianDailyNote",displayName:"Daily Note",description:"Create or read today's daily note, or get its path",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianDailyNote:
- Use for daily note operations: creating, reading content, or getting the file path.
- Use readNote for reading specific notes by path. Use obsidianDailyNote only for today's daily note.
- daily — create today's daily note. Applies the user's configured daily note template automatically. Use this when the user asks to create or set up today's daily note.
- daily:read — read today's daily note content.
- daily:path — get the vault-relative file path (useful for follow-up readNote calls).
- For past or future daily notes (e.g. "yesterday's daily note"): NEVER ask the user for the date — use the time tools. Workflow: (1) call getCurrentTime to resolve the date, (2) call daily:path to discover the date format and folder, (3) call obsidianTemplates with command=templates to list available template names, then call template:read with the name that matches (e.g. "Daily Note Template"), (4) use writeFile to create the note at the resolved path with the template content, replacing variables like {{date}} with the target date. If templates returns an error or no daily template is found, ask the user for their template path and use readNote to read it.
- To add content to a daily note, use writeFile or editFile.
- Use \\n for newlines and \\t for tabs in content strings.
- For arbitrary file writes beyond daily notes, use writeFile or editFile instead.
- If the user names a specific vault, pass it using the vault parameter.`}}),t.register({tool:yyn,metadata:{id:"obsidianRandomRead",displayName:"Random Note",description:"Read a random note using the official Obsidian CLI",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianRandomRead:
- Use when the user explicitly asks for a random note or random note content.
- If the user names a specific vault, pass it using the vault parameter.
- Do not use when the user asks for a specific note; use readNote/getFileTree for specific targets.`}}),t.register({tool:vyn,metadata:{id:"obsidianProperties",displayName:"Properties",description:"Read frontmatter properties from notes or list all property names in the vault",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianProperties:
- Use to inspect frontmatter properties across the vault or within a specific note.
- properties (no file/path): list all property names used vault-wide. Add counts=true for occurrence counts. Add sort=count to sort by frequency.
- properties with file= or path=: list that note's key-value property pairs.
- property:read: read a single property value from a specific note. Requires name parameter.
- file= resolves like a wikilink (name only, no path or extension). path= uses exact vault-relative path.
- Do not use for full note content — use readNote for that.
- To modify properties, use writeFile or editFile to update the frontmatter YAML.`}}),t.register({tool:byn,metadata:{id:"obsidianTasks",displayName:"Tasks",description:"List tasks across the vault with filters for status, file, and daily note",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTasks:
- ALWAYS use this tool when the user asks about tasks, todos, or checkboxes. Do NOT use localSearch for task queries.
- Use to list and filter tasks across the vault.
- todo=true: show only incomplete tasks. done=true: show only completed tasks.
- status="x": filter by specific status character (e.g., "/" for in-progress, "x" for done, " " for open).
- daily=true: show tasks from today's daily note only.
- verbose=true: group tasks by file with line numbers.
- total=true: return only the task count.
- file= resolves like a wikilink (name only). path= uses exact vault-relative path.
- For time-based task queries (e.g. "tasks from last month"): use verbose=true to get tasks grouped by file, then filter results by file dates or daily note filenames to match the time range.`}}),t.register({tool:_yn,metadata:{id:"obsidianLinks",displayName:"Links",description:"Query the vault link graph: backlinks, outgoing links, orphans, unresolved",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianLinks:
- Use to explore the vault's link graph.
- backlinks: list notes that link TO a given file. Use file= or path= to target a note. Add counts=true for link counts.
- links: list outgoing links FROM a given file. Use file= or path= to target a note.
- orphans: list all notes with no incoming links. Use total=true for just the count. Add all=true to include non-markdown files.
- unresolved: list wikilinks that don't resolve to any existing file. Use counts=true for occurrence counts, verbose=true to see source files.
- file= resolves like a wikilink (name only). path= uses exact vault-relative path. Without either, targets the active file.`}}),t.register({tool:xyn,metadata:{id:"obsidianTemplates",displayName:"Templates",description:"List available templates or read template content",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTemplates:
- Use 'templates' to list all available templates when you need to find the right template for a task.
- Use 'template:read' with a template name to get its content with variables resolved. Requires name parameter.
- This is useful for creating daily notes from templates — read the template first, then use writeFile to populate the note.`}}),t.register({tool:Syn,metadata:{id:"obsidianBases",displayName:"Bases",description:"List Base files, views, query data, or create new items in Obsidian Bases",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianBases:
- Use to explore and manage structured data in Obsidian Base (.base) database files.
- bases: list all Base files in the vault. Use total=true for just the count.
- base:views: list the views defined in a Base file. Requires file= or path=.
- base:query: query data from a specific Base view. Requires file= or path=, optionally view= and format= (e.g., format=csv).
- base:create: create a new item (row) in a Base. Requires file= or path=. Optional: view= (target view), name= (file name for the item), content= (initial note content).
- The created item appears as a new note that matches the Base's filter criteria.
- Use base:query first to understand the Base's structure and existing data before creating items.
- If the Base filters by a specific tag or folder, ensure the new item will match those filters.
Base file YAML reference (for creating new .base files with writeFile):
- filters: MUST be either a single string OR an object with and/or/not keys. NEVER use a bare YAML list.
- Embed in notes with ![[MyBase.base]] or ![[MyBase.base#View Name]].
- VALIDATION: After creating or editing a .base file, ALWAYS call obsidianBases with base:views to verify it parses correctly. If it returns an error, fix the YAML with writeFile and re-validate. Do not stop until validation passes.`}})}function rq(t){let e=Md.getInstance(),n=le(),r=e.getToolMetadata("getFileTree")!==void 0,o=t!==void 0,i=e.getToolMetadata("updateMemory")!==void 0,s=n.enableSavedMemory;(e.getAllTools().length===0||r!==o||i!==s)&&(e.clear(),t&&(e.registerAll(KLr(t)),GLr(t),ZLr(t),n.enableSavedMemory&&YLr(t)),X8e()&&JLr())}vt();vt();Dwe();var K0e=class{constructor(e,n){this.toolManager=e;this.writeFileTool=n;this.buffer=""}findCompleteBlock(e){let n=/<writeFile>[\s\S]*?<\/writeFile>/,r=e.match(n);return!r||r.index===void 0?null:{block:r[0],endIdx:r.index+r[0].length}}async*processChunk(e){let n="";if(Array.isArray(e.content))for(let o of e.content)o.type==="text"&&o.text!=null&&(n+=typeof o.text=="string"?o.text:"");else e.content!=null&&(n=typeof e.content=="string"?e.content:"");n&&(this.buffer+=n),yield e;let r=this.findCompleteBlock(this.buffer);for(;r;){let{block:o,endIdx:i}=r,s=o.match(/<path>([\s\S]*?)<\/path>/),a=o.match(/<content>([\s\S]*?)<\/content>/),l=s?s[1].trim():void 0,c=a?a[1].trim():void 0;try{let u=await this.toolManager.callTool(this.writeFileTool,{path:l,content:c}),d=Zk.format("writeFile",u);yield{...e,content:`
${d}
`}}catch(u){yield{...e,content:`
Error: ${u?.message??String(u)}
`}}this.buffer=this.buffer.substring(i),r=this.findCompleteBlock(this.buffer)}}};rX();ge();rX();function rvn(t){if(!Array.isArray(t)||t.length===0)return{high:0,medium:0,low:0,total:0,averageScore:0};let e=0,n=0,r=0,o=0;for(let i of t){let s=i.rerank_score??i.score??0;o+=s,s>=.7?e++:s>=.3?n++:r++}return{high:e,medium:n,low:r,total:t.length,averageScore:o/t.length}}function ovn(t){let e=[];return t.high>0&&e.push(`${t.high} high`),t.medium>0&&e.push(`${t.medium} medium`),t.low>0&&e.push(`${t.low} low`),e.length===0?"[Relevance: no results]":`[Relevance: ${e.join(", ")}]`}function lnt(t){if(!Array.isArray(t))return"";let e=t.filter(r=>r.includeInContext!==!1);return e.length===0?"No relevant documents found.":e.map((r,o)=>{let i=r.title||"Untitled",s=r.path||"",a=r.__sourceId||r.collection_name||r.source_id||o+1,l=null;if(r.mtime){let c=new Date(r.mtime);isNaN(c.getTime())||(l=c.toISOString())}return`<document>
`);return`<additionalMatches count="${t.length}" note="These results contain titles and metadata only. To read the full content of a note, call the readNote tool with its path.">
`||t==="\r"}RE();NZ();ei();var vO=class extends jH{constructor(){super(...arguments);this.lastCitationSources=null}getAvailableToolsForPlanning(){let n=Md.getInstance();return n.getAllTools().length===0&&rq(this.chainManager.app),n.getAllTools().map(o=>o.tool).filter(o=>o.name==="getCurrentTime"||o.name==="convertTimeBetweenTimezones"||o.name==="getTimeInfoByEpoch"||o.name==="getTimeRangeMs"||o.name==="getFileTree")}async planToolCalls(n,r,o=!1){let i=this.getAvailableToolsForPlanning(),s=r;if(typeof s.bindTools!="function")return V("[CopilotPlus] Model does not support native tool calling, skipping tool planning"),{toolCalls:[],salientTerms:this.extractSalientTermsFromQuery(n)};let a=s.bindTools(i),c=`You are a helpful AI assistant. Analyze the user's message and determine if any tools should be called.
Guidelines:
- Use tools when the user's request requires external information or computation
- For time-related queries, use getTimeRangeMs to convert time expressions to timestamps
- Use getFileTree ONLY when the user wants to discover or list notes/folders in the vault — not to read content already in context${o?`
- The user has an active note attached in this turn. Its content is already available; do NOT call getFileTree merely because the user says 'this note' or 'this file'. Only call getFileTree when the user explicitly wants to discover OTHER notes, list folders, or verify paths.`:""}
- If no tools are needed, respond with your analysis
After analyzing, extract key search terms from the user's message that would be useful for searching notes:
- Extract meaningful nouns, topics, and specific concepts
- Preserve the EXACT words and language from the user's message (works for any language)
- Exclude time expressions (those are handled by tools)
Include your extracted terms as: [SALIENT_TERMS: term1, term2, term3]`,u=[{role:RPe(r),content:c},{role:"user",content:n}];H("[CopilotPlus] Requesting tool planning with native tool calling...");let d;{let g=await fv(()=>a.stream(u)),w;for await(let y of g)w=w?w.concat(y):y;if(!w)throw new Error("[CopilotPlus] Received empty response from planning model");d=new mr({content:w.content,tool_calls:w.tool_calls,additional_kwargs:w.additional_kwargs})}let f=d.tool_calls||[],p=typeof d.content=="string"?d.content:JSON.stringify(d.content);H("[CopilotPlus] Native tool calls:",f.length);let{salientTerms:m}=this.extractPlanningFieldsFromResponse(p,n),h=[];for(let g of f){let w=i.find(y=>y.name===g.name);w?(h.push({tool:w,args:g.args}),H(`[CopilotPlus] Tool call: ${g.name}`,g.args)):V(`[CopilotPlus] Tool '${g.name}' not found in available tools`)}return{toolCalls:h,salientTerms:m}}extractPlanningFieldsFromResponse(n,r){let o,i=n.match(/\[SALIENT_TERMS:\s*([^\]]+?)\s*\]/i);if(i){let s=i[1].split(",").map(a=>a.trim()).filter(a=>a.length>0);o=s.length>0?s:this.extractSalientTermsFromQuery(r)}else o=this.extractSalientTermsFromQuery(r);return{salientTerms:o}}extractSalientTermsFromQuery(n){return n.split(/[\s\p{P}]+/u).filter(r=>r.length>=3).slice(0,10)}async processAtCommands(n,r,o){let i=n.toLowerCase(),s=this.removeAtCommands(n),a=[...r];if(i.includes("@vault")&&(a.some(c=>c.tool.name==="localSearch")||a.push({tool:$0e(this.chainManager.app),args:{query:s,salientTerms:o.salientTerms,timeRange:o.timeRange}})),(i.includes("@websearch")||i.includes("@web"))&&!a.some(c=>c.tool.name==="webSearch")){let u=await YT.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=Oat(u);a.push({tool:F0e,args:{query:s,chatHistory:d}})}return i.includes("@memory")&&(a.some(c=>c.tool.name==="updateMemory")||a.push({tool:m0e(this.chainManager.app),args:{statement:s}})),a}removeAtCommands(n){return n.split(" ").filter(r=>!eH.includes(r.toLowerCase())).join(" ").trim()}async processImageUrls(n){let r=[],o=await kD.processUrlBatch(n,r,this.chainManager.app.vault);return kD.showFailedImagesNotice(r),o}async processChatInputImages(n){let r=[],o=await kD.processChatImageBatch(n,r,this.chainManager.app.vault);return kD.showFailedImagesNotice(r),o}async extractImagesFromContextBlock(n,r){let i=new RegExp(`<${r.tagName}>([\\s\\S]*?)<\\/${r.tagName}>`).exec(n);if(!i)return[];let s=i[1],l=/<content>([\s\S]*?)<\/content>/.exec(s),c=l?jLt(l[1]):"";if(!c)return[];let d=new RegExp(`<${r.identifierTag}>(.*?)<\\/${r.identifierTag}>`).exec(s),f=d?d[1]:void 0;H(`[CopilotPlus] Extracting images from ${r.displayName}:`,f||`no ${r.identifierTag}`);let p=r.useForResolution?f:void 0;return this.extractEmbeddedImages(c,p)}async extractEmbeddedImages(n,r){let o=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,i=[],s=[...n.matchAll(o)];for(let l of s){let c=l[1];if(r){let u=this.chainManager.app.metadataCache.getFirstLinkpathDest(c,r);u?i.push(u.path):(V(`Could not resolve embedded image: ${c} from source: ${r}`),i.push(c))}else i.push(c)}let a=hvn(n);for(let l of a){if(!l)continue;if(l.match(/^https?:\/\//)){i.push(l);continue}let c=l.replace(/^\.\//,"").replace(/^\//,"");if(r){let u=this.chainManager.app.metadataCache.getFirstLinkpathDest(c,r);u?i.push(u.path):i.push(c)}else i.push(c)}return i}async buildMessageContent(n,r){let o=[],i=[],s=le(),a=[];if(s.passMarkdownImages){let d=r.contextEnvelope;if(!d)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot extract images.");let f=d.layers.find(p=>p.id==="L3_TURN");if(f){let p=[{tagName:"active_note",identifierTag:"path",displayName:"active note",useForResolution:!0},{tagName:"active_web_tab",identifierTag:"url",displayName:"active web tab",useForResolution:!1}];for(let m of p){let h=await this.extractImagesFromContextBlock(f.text,m);h.length>0&&a.push({urls:h,type:"embedded"})}}}for(let d of a){let f=await this.processImageUrls(d.urls);i.push(...f.successfulImages),o.push(...f.failureDescriptions)}let l=r.content;if(l&&l.length>0){let d=await this.processChatInput
`+C[0])}let x=d?await this.buildMessageContent(_,r):_;f.push({role:"user",content:x})}H("Final request to AI",{messages:f.length});let w=u?.modelName;zH({messages:f,modelName:w,contextEnvelope:r.contextEnvelope});let y=new K0e($k,Ixe(this.chainManager.app)),v=await fv(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:i.signal}));for await(let _ of v){if(i.signal.aborted){H("CopilotPlus multimodal stream iteration aborted",{reason:i.signal.reason});break}for await(let S of y.processChunk(_))s.processChunk(S)}}async run(n,r,o,i,s){let{updateLoadingMessage:a}=s,l=this.chainManager.chatModelManager.getChatModel(),u=!this.hasCapability(l,"reasoning"),d=new Qb(o,u),f=[];if(!await eh(this.chainManager.app,{trigger:"legacy_chat_turn",isCopilotPlus:!0})){await this.handleError(new Error("Invalid license key"),_=>d.processErrorChunk(_));let v=d.close().content;return this.handleResponse(v,n,r,i,o,void 0)}try{H("==== Step 1: Planning tools ====");let v,_=n.contextEnvelope;if(!_)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");let k=_.layers.find(D=>D.id==="L5_USER")?.text||n.originalMessage||"";try{let D=this.chainManager.chatModelManager.getChatModel(),q=!!_.layers.find(ne=>ne.id==="L3_TURN")?.segments?.some(ne=>ne.metadata?.source==="current_turn"&&/<active_note[\s>]/.test(ne.content)),Z=await this.planToolCalls(k,D,q),re,ce=Z.toolCalls.find(ne=>ne.tool.name==="getTimeRangeMs");if(ce){let ne=await $k.callTool(ce.tool,ce.args),G=ue=>ue?.startTime?.epoch!==void 0&&ue?.endTime?.epoch!==void 0?{startTime:ue.startTime.epoch,endTime:ue.endTime.epoch}:ue;if(typeof ne=="string")try{let ue=JSON.parse(ne);ue.error||(re=G(ue))}catch{V("[CopilotPlus] Failed to parse getTimeRangeMs result:",ne)}else if(ne){let ue=ne;ue.error||(re=G(ue))}H("[CopilotPlus] Executed getTimeRangeMs, result:",re)}let oe=Z.toolCalls.filter(ne=>ne.tool.name==="getTimeRangeMs"&&re?(H("Skipping getTimeRangeMs - already executed during planning"),!1):!0);v=await this.processAtCommands(k,oe,{salientTerms:Z.salientTerms,timeRange:re})}catch(D){return this.handleResponse(Eat(D),n,r,i,o)}let x=n.contextEnvelope?.layers.find(D=>D.id==="L5_USER")?.text,C=this.removeAtCommands(x||n.originalMessage||n.message),{toolOutputs:T,sources:I}=await this.executeToolCalls(v,a);f=I;let M=T.filter(D=>D.output!=null),O=this.appendComposerInstructionsIfNeeded(C,n);H("Invoking LLM with envelope-based context construction"),await this.streamMultimodalResponse(O,n,M,r,d,C,a)}catch(v){a?.(bh.DEFAULT),v instanceof Error&&v.name==="AbortError"||r.signal.aborted?H("CopilotPlus stream aborted by user",{reason:r.signal.reason}):await this.handleError(v,_=>d.processErrorChunk(_))}if(r.signal.aborted&&r.signal.reason==="new-chat")return o(""),"";let m=d.close(),h=m.content,g={wasTruncated:m.wasTruncated,tokenUsage:m.tokenUsage??void 0},w=le(),y=this.lastCitationSources&&this.lastCitationSources.length>0?this.lastCitationSources:(f||[]).map(v=>({title:v.title,path:v.path}));return h=LZt(h,y,w.enableInlineCitations),await this.handleResponse(h,n,r,i,o,f,void 0,g),h}async executeToolCalls(n,r){let o=[],i=[],s=n.some(a=>a.tool.name==="localSearch");for(let a of n){if(a.tool.name==="getFileTree"&&s){H("Skipping getFileTree since localSearch is already active");continue}H(`Step 2: Calling tool: ${a.tool.name}`),a.tool.name==="localSearch"?r?.(bh.READING_FILES):a.tool.name==="webSearch"?r?.(bh.SEARCHING_WEB):a.tool.name==="getFileTree"&&r?.(bh.READING_FILE_TREE);let l;try{l=await $k.callTool(a.tool,a.args)}catch(c){if(a.tool.name!=="localSearch")throw c;let u=this.processLocalSearchResult({result:Dt(c),success:!1});o.push({tool:a.tool.name,output:u.formattedForLLM});continue}if(a.tool.name==="localSearch"){let u={result:typeof l=="string"?l:JSON.stringify(l),success:l!=null},d=this.getTimeExpression(n),f=this.processLocalSearchResult(u,d);i.push(...f.sources),o.push({tool:a.tool.name,output:f.formattedForLLM})}else o.push({tool:a.tool.name,output:l})}return{toolOutputs:o,sources:Z3(i)}}getTimeExpression(n){let r=n.fi
${cnt(f)}`):c&&H(`Tag-only search: ${f.length} notes (metadata-only)`);let _=h.slice(0,Math.min(20,h.length)).map(I=>({title:I.title||I.path||"Untitled",path:I.path||I.title||""})),S=FZt(_);this.lastCitationSources=h.slice(0,Math.min(20,h.length)).map(I=>({title:I.title||I.path||"Untitled",path:I.path||void 0}));let k=RZt(S,o.enableInlineCitations).trim(),C=dvn("Answer the question based only on the following context:",v),T=k?`${l}
</localSearch>`,s="Search results were in an unexpected format.",{formattedForLLM:i,formattedForDisplay:s,sources:o};uvn(l),o=svn(l),i=this.prepareLocalSearchResult(l,r||""),s=Zk.format("localSearch",i)}catch(a){V("Failed to parse localSearch results:",a);let l=ivn(n.result);i=r?`<localSearch timeRange="${r}">
`)}var Q$=class{constructor(e){this.modelName=e}buildToolSpecificInstructions(e){let n=[];for(let o of e)o.customPromptInstructions&&n.push(o.customPromptInstructions);let r=this.buildCopilotCommandInstructions(e);return r&&n.push(r),n.length>0?n.join(`
`):""}buildCopilotCommandInstructions(e){let n=[];for(let r of e)if(!(!r.copilotCommands||r.copilotCommands.length===0))for(let o of r.copilotCommands)n.push(`- ${o}: call the tool named ${r.id}`);return n.length===0?null:["When the user explicitly includes a Copilot command alias (e.g., @vault) in their message, treat it as a direct request to call the mapped tool before proceeding.","Honor these aliases exactly (case-insensitive):",...n,"If the referenced tool is unavailable, explain that the command cannot be fulfilled instead of ignoring it."].join(`
You are the user's personal knowledge assistant. Always ground your answers in real sources rather than your own training data. Follow this priority chain:
1. **Explicit context first.** If the user has attached notes, documents, URLs, YouTube transcripts, tweets, or any other content to the conversation, use that content as your primary source. The user added it for a reason.
2. **Vault second.** For any question that could plausibly be answered by the user's notes, search the vault (localSearch). The user's own writing, meeting notes, journal entries, and saved references are highly valuable.
3. **Web third.** If the vault has no relevant results, or the question is about external/current information the vault is unlikely to contain, search the web.
4. **Your own knowledge last.** Only fall back on your training data when all of the above have been exhausted or are clearly inapplicable (e.g., explaining a general concept, writing code, or creative tasks that don't need source material).
When in doubt, search the vault. It is always better to check and find nothing than to skip the search and miss relevant notes.
## General Guidelines
- NEVER mention tool names like "localSearch", "webSearch", etc. in your responses. Use natural language like "searching your vault", "searching the web", etc.
You can use multiple tools in sequence. After each tool execution, you'll receive the results and can decide whether to use more tools or provide your final response.
Always explain your reasoning before using tools. Be conversational and clear about what you're doing.
When you've gathered enough information, provide your final response without any tool calls.
## Citation Integrity (CRITICAL)
- ONLY cite sources from tools you ACTUALLY called and received results from
- NEVER fabricate or hallucinate search results, web searches, or any tool outputs
- If you did not call a tool, do not claim you did or cite results from it
- Each citation must correspond to a real document or result returned by a tool in this conversation`}),l}enhanceUserMessage(e,n){return e}needsSpecialHandling(){return!1}},dnt=class extends Q${isGPT5Model(){return this.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o),s=r||[],a=s.includes("writeFile")||s.includes("editFile"),l=[];this.isGPT5Model()?l.push(`GPT-5 SPECIFIC RULES:
- Use maximum 2 tool calls initially, then provide an answer
- Call each tool ONCE per unique query
- For optional parameters: OMIT them entirely if not needed (don't pass empty strings/null)
- For localSearch: OMIT timeRange if not doing time-based search`):l.push("CRITICAL FOR GPT MODELS: You MUST use tools when the user's request requires them. Do not just describe what you plan to do - actually call the tools."),a&&l.push(`🚨 FILE EDITING WITH COMPOSER TOOLS 🚨
When user asks you to edit or modify a file, you MUST:
1. Determine if it's a small edit (use editFile) or major rewrite (use writeFile)
2. Call the tool immediately - do not just describe what you plan to do
For editFile, pass the exact text to find and its replacement:
- path: vault-relative file path
- oldText: exact text to find (include surrounding context lines to make it unique)
- newText: replacement text (empty string to delete)
❌ WRONG: "I'll help you add item 4 to the list. Let me update that for you." [No tool call = FAILURE]
✅ CORRECT: Actually call editFile or writeFile with proper parameters`),l.push("FINAL REMINDER FOR GPT MODELS: If the user asks you to search, find, edit, or modify anything, you MUST call the appropriate tool immediately. Do not wait for another turn.");let c=l.join(`
🚨 GPT REMINDER: Use editFile for small edits (oldText/newText parameters) or writeFile for full rewrites.`:e}needsSpecialHandling(){return!0}},fnt=class extends Q${isThinkingModel(){return this.modelName.includes("claude-3-7-sonnet")||this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-3.7-sonnet")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-opus-4")}isClaudeSonnet4(){return this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o);if(!this.isThinkingModel())return i;let s=[`IMPORTANT FOR CLAUDE THINKING MODELS:
- You are a thinking model with internal reasoning capability
- Your thinking process will be automatically wrapped in <think> tags - do not manually add thinking tags
- Call tools AFTER your thinking is complete
- Do not provide final answers before using tools - use tools first, then provide your response based on the results
CORRECT FLOW FOR THINKING MODELS:
1. Think through the problem (this happens automatically)
2. Use tools to gather information
3. Wait for tool results
4. Provide final response based on gathered information
INCORRECT: Providing a final answer before using tools
CORRECT: Using tools first, then providing answer based on results`];return this.isClaudeSonnet4()&&s.push(`🚨 CRITICAL INSTRUCTIONS FOR CLAUDE SONNET 4 - AUTONOMOUS AGENT MODE 🚨
⚠️ WARNING: You have a specific tendency to write complete responses immediately after tool calls. This BREAKS the autonomous agent pattern!
🔄 CORRECT AUTONOMOUS AGENT ITERATION PATTERN:
1. User asks question
2. Brief sentence about what you'll do (1 sentence max)
3. Use tools to gather information
4. ✋ STOP after tool calls - Do not write anything else
5. Wait for tool results (system provides them)
6. Evaluate results and either: Use more tools OR provide final answer
✅ IDEAL RESPONSE FLOW:
- Brief action statement (1 sentence)
- Tool calls
- STOP (wait for results)
- Brief transition statement (1 sentence)
- More tool calls OR final answer
🎯 CORRECT PATTERN:
I'll search your vault for piano practice information.
[Call localSearch tool]
[RESPONSE ENDS HERE - NO MORE TEXT]
❌ WRONG PATTERN (DO NOT DO THIS):
[Call tool]
Based on the search results, here's a complete practice plan...
[This is FORBIDDEN - you haven't received results yet!]
🔑 KEY UNDERSTANDING FOR CLAUDE 4:
- Brief 1-sentence explanations BEFORE tool calls are good
- Each response is ONE STEP in a multi-step process
- After tool calls, STOP and wait for the system to provide results
- Your thinking is automatically handled in <think> blocks
⚡ AUTONOMOUS AGENT RULES FOR CLAUDE 4:
1. If you need tools: Brief sentence + tool calls, then STOP
2. If you receive tool results: Evaluate if you need more tools
3. If you need more tools: Brief sentence + more tool calls, then STOP
4. If you have enough info: THEN provide your final response
REMEMBER: One brief sentence before tools is perfect. Nothing after tool calls.`),i.push({id:"claude-thinking-guidelines",label:"Claude thinking model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#ClaudeModelAdapter.buildSystemPromptSections",content:s.join(`
You MUST use tools to complete tasks. DO NOT ask the user questions about how to proceed.
${(r||[]).includes("localSearch")?`
When the user mentions "my notes" or "my vault", use the localSearch tool.
❌ WRONG:
"Let's start by searching your notes. What kind of information should I look for?"
✅ CORRECT: Call localSearch immediately with the user's topic as the query`:""}`.trim()];return l.push(`GEMINI SPECIFIC RULES:
1. When user mentions "my notes" about X → use localSearch with query "X"
2. DO NOT ask clarifying questions about search terms
3. DO NOT wait for permission to use tools
4. Use tools based on the user's request
🚨 CRITICAL: SEQUENTIAL vs PARALLEL TOOL CALLS 🚨
When one tool's OUTPUT is needed as INPUT to another tool, you MUST make them in SEPARATE responses:
1. Call the FIRST tool
2. STOP and wait for the result
3. In the NEXT response, use the result from step 1 in the SECOND tool call
❌ WRONG (DO NOT DO THIS):
User: "Recap my last week"
- Call getTimeRangeMs AND localSearch together with made-up timeRange values
- This is WRONG because you're hallucinating the timeRange values!
✅ CORRECT (DO THIS):
User: "Recap my last week"
- FIRST: Call getTimeRangeMs with timeExpression "last week"
- WAIT for result
- SECOND: Call localSearch using the actual timeRange from the result
RULE: NEVER make up or guess parameter values. If you need a tool's output, call that tool FIRST, then WAIT for the result.
Remember: The user has already told you what to do. Execute it NOW with the available tools.`),i.push({id:"gemini-specific-guidelines",label:"Gemini-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GeminiModelAdapter.buildSystemPromptSections",content:l.join(`
`)}),i}enhanceUserMessage(e,n){return n?`${e}
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},mnt=class extends Q${buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o);return i.push({id:"copilot-plus-guidelines",label:"Copilot Plus model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#CopilotPlusModelAdapter.buildSystemPromptSections",content:`🚨 CRITICAL: NO HALLUCINATED TOOL CALLS OR SOURCES 🚨
You are a Copilot Plus model. You MUST follow these rules strictly:
## Tool Call Integrity
- You can ONLY reference results from tools you have ACTUALLY called in this conversation
- NEVER claim to have performed a web search unless you called the webSearch tool AND received results
- NEVER claim to have searched notes unless you called localSearch AND received results
- If you want to search the web, you MUST call the webSearch tool first - do not make up results
## Citation Rules
- Every citation [1], [2], etc. MUST correspond to a real source returned by a tool
- Do NOT invent sources like "General web search results for X" unless webSearch was actually called
- If you only called localSearch, your citations can ONLY reference notes from that search
- Count your actual tool calls - if you only made 1 tool call, you cannot have citations from multiple different tools
## Before Writing Citations
Ask yourself: "Did I actually call this tool and receive this result?"
- If YES: You may cite it
- If NO: Do NOT cite it or claim you did
REMEMBER: It is better to say "I only searched your notes, not the web" than to fabricate web search results.
## Formatting Guidelines
- AVOID using markdown tables - they often render poorly in chat interfaces
- Instead of tables, use bullet points, numbered lists, or simple formatted text
- Only use tables when the user explicitly requests tabular format`}),i}needsSpecialHandling(){return!0}},Y0e=class{static createAdapter(e){let n=(e.modelName||e.model||"").toLowerCase();if(H(`Creating model adapter for: ${n}`),n.includes("gpt")){let r=new dnt(n);return r.isGPT5Model()?H("Using GPTModelAdapter with GPT-5 specific enhancements"):H("Using GPTModelAdapter"),r}return n.includes("claude")?(H("Using ClaudeModelAdapter"),new fnt(n)):n.includes("gemini")||n.includes("google/gemini")?(H("Using GeminiModelAdapter"),new pnt(n)):n.includes("copilot-plus")?(H("Using CopilotPlusModelAdapter"),new mnt(n)):(H("Using BaseModelAdapter (default)"),new Q$(n))}};RE();$we();function lDr(t,e){let n=new Set(t.toLowerCase().split(/\s+/).filter(Boolean)),r=new Set(e.toLowerCase().split(/\s+/).filter(Boolean));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let o=0;for(let l of n)r.has(l)&&o++;let i=n.size+r.size-o,s=o/i,a=o/Math.min(n.size,r.size);return Math.max(s,a)}function hnt(t,e,n=.6){for(let r of e)if(lDr(t,r)>=n)return r;return null}var cDr=/^(user|assistant|system)\s*$/;function yvn(t){return t&&t.split(`
`).filter(e=>!cDr.test(e)).join(`
`)}var uDr=`## Agent Behavior
- You have a limited number of tool calls. Use them wisely.
- NEVER search for the same or very similar query twice. If results were insufficient, try substantially different terms.
- After 1-2 searches, synthesize an answer from the results you have. Do not keep searching unless the results are clearly insufficient.
- If you have enough information to answer, respond directly without calling any more tools.`,Rne=class extends vO{constructor(){super(...arguments);this.llmFormattedMessages=[];this.lastDisplayedContent="";this.reasoningState=AZt();this.reasoningTimerInterval=null;this.accumulatedContent="";this.allReasoningSteps=[];this.abortHandledByTimer=!1}getAvailableTools(){let n=le(),r=Md.getInstance();r.getAllTools().length===0&&rq(this.chainManager.app);let o=new Set(n.autonomousAgentEnabledToolIds||[]);return r.getEnabledTools(o,!!this.chainManager.app?.vault)}startReasoningTimer(n,r){this.reasoningState={status:"reasoning",startTime:Date.now(),elapsedSeconds:0,steps:[]},this.accumulatedContent="",this.allReasoningSteps=[],this.abortHandledByTimer=!1;let o=["Understanding your question","Analyzing your request","Processing your query","Thinking about this","Considering your question","Working on this","Pondering the possibilities","Diving into your request","Let me think about this","Exploring your question","Getting my thoughts together","Examining the details","Looking into this","Mulling this over","On it","Firing up the neurons","Connecting the dots","Brewing some ideas","Spinning up the gears","Warming up the engines","Crunching the details","Putting on my thinking cap","Consulting my notes","Gathering my thoughts","Rolling up my sleeves"],i=o[Math.floor(Math.random()*o.length)];this.addReasoningStep(i),this.reasoningTimerInterval=window.setInterval(()=>{if(r?.signal.aborted&&this.reasoningState.status==="reasoning"){this.stopReasoningTimer(),this.reasoningState.status="complete",this.abortHandledByTimer=!0;let s=this.buildReasoningBlockMarkup(),a="The response was interrupted.",l=s?s+`
`+this.accumulatedContent:""):this.accumulatedContent;n(a)}},100)}addReasoningStep(n,r,o=!1){let i={timestamp:Date.now(),summary:n,toolName:r};this.allReasoningSteps.push(i),!o&&(this.reasoningState.steps.push(i),this.reasoningState.steps.length>4&&this.reasoningState.steps.shift())}stopReasoningTimer(){this.reasoningTimerInterval&&(window.clearInterval(this.reasoningTimerInterval),this.reasoningTimerInterval=null),this.reasoningState.status="collapsed"}buildReasoningBlockMarkup(){if(this.reasoningState.status==="complete"||this.reasoningState.status==="collapsed"){let n={...this.reasoningState,steps:this.allReasoningSteps};return V6e(n)}return V6e(this.reasoningState)}applyCiCOrderingToLocalSearchResult(n,r){return pvn(n,r)}async run(n,r,o,i,s){this.llmFormattedMessages=[],this.lastDisplayedContent="";let a=await eh(this.chainManager.app,{trigger:"legacy_chat_turn",isAutonomousAgent:!0}),l=this.chainManager.chatModelManager.getChatModel(),c=Y0e.createAdapter(l),u=new Qb(o,!0);if(!a){await this.handleError(new Error("Invalid license key"),h=>u.processErrorChunk(h));let m=u.close().content;return this.handleResponse(m,n,r,i,o,void 0)}let d=l?.modelName;if(!n.contextEnvelope)throw new Error("[Agent] Context envelope is required but not available. Cannot proceed with autonomous agent.");H("[Agent] Using native tool calling with ReAct pattern");let p=await this.prepareAgentConversation(n,l,s.updateLoadingMessage);try{this.startReasoningTimer(o,r);let m=await this.runReActLoop({boundModel:p.loopDeps.boundModel,chatModel:l,tools:p.loopDeps.availableTools,messages:p.messages,originalPrompt:p.originalUserPrompt,abortController:r,updateCurrentAiMessage:o,processLocalSearchResult:p.loopDeps.processLocalSearchResult,applyCiCOrderingToLocalSearchResult:p.loopDeps.applyCiCOrderingToLocalSearchResult,adapter:c});if(this.abortHandledByTimer)return this.lastDisplayedContent="","";let h=Z3(m.sources);return p.messages.length>0&&zH({messages:[...p.messages],modelName:d,contextEnvelope:n.contextEnvelope}),await this.handleResponse(m.finalResponse,n,r,i,o,h.length>0?h:void 0,this.llmFormattedMessages.join(`
`),m.responseMetadata),this.lastDisplayedContent="",m.finalResponse}catch(m){if(this.stopReasoningTimer(),m.name==="AbortError"||r.signal.aborted)return H("Autonomous agent stream aborted by user",{reason:r.signal.reason}),"";W("Autonomous agent failed, falling back to regular Plus mode:",m);try{return await new vO(this.chainManager).run(n,r,o,i,s)}catch(h){W("Fallback to regular Plus mode also failed:",h),this.lastDisplayedContent&&u.processChunk({content:this.lastDisplayedContent});let g=Dt(m),w=`
Fallback to regular Plus mode also failed: `+Dt(h);await this.handleError(new Error(g+w),v=>u.processErrorChunk(v));let y=u.close().content;return this.handleResponse(y,n,r,i,o,void 0,y)}}}async prepareAgentConversation(n,r,o){let i=[],s=this.getAvailableTools(),a=r.modelName||r.model||"unknown";if(typeof r.bindTools!="function")throw new Error(`Model ${a} does not support native tool calling (bindTools not available). Agent mode requires a model with tool calling support.`);let l=r.bindTools(s),c={availableTools:s,boundModel:l,processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},u=n.contextEnvelope,d=NE.convert(u,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),f=this.chainManager.memoryManager.getMemory(),p=d.find(x=>x.role==="system"),m=Md.getInstance(),g=s.map(x=>m.getToolMetadata(x.name)).filter(x=>x!==void 0).filter(x=>x.customPromptInstructions).map(x=>`For ${x.displayName}: ${x.customPromptInstructions}`).join(`
`),w=[p?.content||"",g?`
## Tool Guidelines
${g}`:"",uDr].filter(Boolean).join(`
`);w&&i.push(new Ag({content:w}));let _=u.layers.find(x=>x.id==="L5_USER")?.text||""||n.originalMessage||n.message,S=[];await WH(f,S);for(let x of S)x.role==="user"?i.push(new Zs(x.content)):i.push(new mr(x.content));let k=d.find(x=>x.role==="user");if(k){let C=this.isMultimodalModel(r)?await this.buildMessageContent(k.content,n):k.content;i.push(new Zs(C))}return{messages:i,collectedSources:[],originalUserPrompt:_,loopDeps:c}}async runReActLoop(n){let{boundModel:r,tools:o,messages:i,originalPrompt:s,abortController:a,updateCurrentAiMessage:l,processLocalSearchResult:c,applyCiCOrderingToLocalSearchResult:u}=n,d=32,f=[],p=Date.now(),m=[],h=0,g=0,w;for(;g<d&&!a.signal.aborted;){let x=Date.now()-p;if(x>=sIe){V(`Agent loop timed out after ${Math.round(x/1e3)}s`);break}g++;let{content:C,aiMessage:T,streamingResult:I}=await this.streamModelResponse(r,i,a,l);w={wasTruncated:I.wasTruncated,tokenUsage:I.tokenUsage??void 0};let M=C?.trim();H(`[Agent] Iteration ${g} model output:`,M?M.slice(0,200):"(empty)");let O=T.tool_calls||[];if(H(`[Agent] Iteration ${g}: ${O.length} tool call(s)`),O.length===0){H(`[Agent] Iteration ${g}: Final response (no tool calls)`),this.stopReasoningTimer(),this.reasoningState.status="complete",i.push(T);let ce=C;if(!ce||ce.trim()===""){let L=T.tool_call_chunks??[];V(`[Agent] Empty response detected (iteration ${g}). Content length: ${C?.length??0}, tool_call_chunks from model: ${L.length}, parsed tool_calls: ${O.length}. This may indicate tool calls were dropped or the model produced only thinking tokens.`),ce="The model did not produce a response. Please try again or switch to a different model."}let oe=this.buildReasoningBlockMarkup(),ne=20,G=5,ue="";for(let L=0;L<ce.length&&!a.signal.aborted;L+=ne){ue+=ce.slice(L,L+ne);let z=oe?oe+`
`+ue:ue;l(z),L+ne<ce.length&&await new Promise(E=>window.setTimeout(E,G))}let B=oe?oe+`
`+ce:ce;return l(B),{finalResponse:B,sources:f,responseMetadata:w}}let D=yvn(C),F=new mr({content:D,tool_calls:T.tool_calls});if(i.push(F),g>1&&D&&D.trim().length>0){let ce=MZt(D);ce&&this.addReasoningStep(ce)}let q=[],Z=[],re=[];for(let ce of O){if(ce.name==="localSearch"){let oe=ce.args?.query;if(oe){let ne=hnt(oe,m)??hnt(oe,Z);if(ne){H(`[Agent] Dedup: "${oe}" (similar to: "${ne}")`),i.push(L8e(ce.id||gxe(),ce.name,`You already searched for a similar query: "${ne}". Synthesize your answer from existing results.`));continue}Z.push(oe),re.push(oe)}else re.push(null)}else re.push(null);q.push(ce)}for(let ce=0;ce<q.length;ce++){let oe=q[ce];if(a.signal.aborted)break;let ne={name:oe.name,args:oe.args},G=q6e(oe.name,ne.args);this.addReasoningStep(G,oe.name),Kyn(ne,g);let ue=await Vyn(ne,o,s),B;if(oe.name==="localSearch"&&ue.success){let E=c(ue);f.push(...E.sources),B={titles:E.sources.map(N=>N.title),count:E.sources.length},ue.result=u(E.formattedForLLM,s||"")}if(Gyn(oe.name,ue),oe.name==="localSearch"&&ue.success){let E=re[ce];E&&m.push(E)}let L=EZt(oe.name,ue,B,ne.args);(!ue.success||B)&&this.addReasoningStep(L,oe.name);let z=L8e(oe.id||gxe(),oe.name,ue.result);i.push(z)}if(q.length===0&&O.length>0){if(h++,H(`[Agent] All ${O.length} tool call(s) skipped as duplicates (${h} consecutive)`),h>=2){H("[Agent] Model stuck in search loop, forcing synthesis without tools"),this.addReasoningStep("Synthesizing answer from search results"),i.push(new Zs(`You have already searched and found relevant results. Do not call any tools. Answer the following question now based ONLY on the search results above:
`+s));let ce=await this.streamModelResponse(n.chatModel,i,a,l);w={wasTruncated:ce.streamingResult.wasTruncated,tokenUsage:ce.streamingResult.tokenUsage??void 0},this.stopReasoningTimer(),this.reasoningState.status="complete";let oe=this.buildReasoningBlockMarkup(),ne=ce.content||"Unable to synthesize a response from the search results.",G=oe?oe+`
`+ne:ne;return l(G),{finalResponse:G,sources:f,responseMetadata:w}}}else h=0}this.stopReasoningTimer(),this.reasoningState.status="complete";let y=this.buildReasoningBlockMarkup();if(a.signal.aborted){if(H("Agent reasoning interrupted by user"),this.abortHandledByTimer)return{finalResponse:"",sources:f,responseMetadata:w};let x="The response was interrupted.";return{finalResponse:y?y+`
`+x:x,sources:f,responseMetadata:w}}let v=Date.now()-p,_=v>=sIe;_?V(`Agent loop timed out after ${Math.round(v/1e3)}s`):V(`Agent reached max iterations (${d})`);let S=_?"I've reached the time limit for reasoning. Here's what I found so far based on the search results.":"I've reached the maximum number of tool calls. Here's what I found so far based on the search results.";return{finalResponse:y?y+`
`+S:S,sources:f,responseMetadata:w}}async streamModelResponse(n,r,o,i){let s=new Map,a=new Qb(()=>{},!0),l="";try{let c=await fv(()=>n.stream(r,{signal:o.signal}));for await(let g of c){if(o.signal.aborted)break;let w=g;if(w.response_metadata?.finish_reason==="MALFORMED_FUNCTION_CALL")throw V("Backend returned MALFORMED_FUNCTION_CALL - falling back to non-agent mode"),new Error("MALFORMED_FUNCTION_CALL: Model does not support native tool calling");let v=w.tool_call_chunks;if(v&&Array.isArray(v))for(let S of v)_an(s,S);let _=typeof w.content=="string"?w.content:"";_&&(l+=_),a.processChunk(w)}let u=a.close(),d=u.content,f=l.trim(),p=d.trim();f&&!p&&H(`[Agent] Model produced content that was entirely stripped (likely think blocks): ${f.slice(0,300)}`);let m=yxe(s),h=new mr({content:d,tool_calls:m.map(g=>({id:g.id,name:g.name,args:g.args,type:"tool_call"}))});return{content:d,aiMessage:h,streamingResult:u}}catch(c){if(W(`Stream error: ${c.message}`),c.name==="AbortError"||o.signal.aborted){let u=a.close();return{content:u.content,aiMessage:new mr({content:u.content}),streamingResult:u}}throw c}}};ge();Ee();vt();Tm();ZO();Bne();W3();var uq=[{tag:"note_context",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"active_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"embedded_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"vault_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"retrieved_document",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"url_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"web_tab_context",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"active_web_tab",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"youtube_video_context",sourceType:"youtube",recoverable:!0,sourceExtractor:"url"},{tag:"twitter_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"embedded_pdf",sourceType:"pdf",recoverable:!0,sourceExtractor:"name"},{tag:"selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"web_selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"localSearch",sourceType:"note",recoverable:!0,sourceExtractor:null}],rke=new Map;for(let t of uq)rke.set(t.tag,t);function oF(t){return rke.get(t)?.sourceType??"unknown"}function oke(t){return rke.get(t)?.recoverable??!1}function dq(t,e){let n=rke.get(e);if(!n?.sourceExtractor)return"";let r=n.sourceExtractor;return new RegExp(`<${r}>([^<]+)</${r}>`).exec(t)?.[1]??""}function jne(t){let e=/<content>([\s\S]*?)<\/content>/.exec(t);return e?e[1]:t}var ey={previewCharsPerSection:500,maxSections:20,verbatimThreshold:5e3};function iF(t,e=500,n=20){let r=t.split(/(?=^#{1,6}\s+)/m).filter(a=>a.trim());if(r.length<=1)return knt(t,e*4);let o=r.slice(0,n),i=r.length>n,s=o.map(a=>{let l=a.trim().split(`
[${o.length} search results - use localSearch to re-query]
${s}
</prior_context>`}function zDr(t,e={}){let{content:n,notePath:r,noteTitle:o,...i}=t;if(!n||typeof n!="string")return t;let s=e.previewCharsPerSection??ey.previewCharsPerSection,a=e.maxSections??ey.maxSections,l=iF(n,s,a);return{...i,notePath:r,noteTitle:o,content:`[COMPACTED - use readNote to get full content]
${l}`,_wasCompacted:!0}}ge();Ee();Bne();pr();xL();rh();UE();ei();var UDr=class extends yw{addUserMessage(t){return this.addMessage(new Zs(t))}addAIMessage(t){return this.addMessage(new mr(t))}async addMessages(t){for(let e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},Tnt=class extends UDr{constructor(e){super(...arguments);A(this,"lc_namespace",["langchain","stores","message","in_memory"]);A(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};pr();var ske=class{},Rvn=(t,e)=>{if(e!==void 0)return t[e];let n=Object.keys(t);if(n.length===1)return t[n[0]]},ake=(t,e)=>{let n=Rvn(t,e);if(!n){let r=Object.keys(t);throw new Error(`input values have ${r.length} keys, you must specify an input key or pass only 1 key as input`)}return n},Int=(t,e)=>{let n=Rvn(t,e);if(!n&&n!==""){let r=Object.keys(t);throw new Error(`output values have ${r.length} keys, you must specify an output key or pass only 1 key as output`)}return n};var eI=class extends ske{constructor(e){super();A(this,"chatHistory");A(this,"returnMessages",!1);A(this,"inputKey");A(this,"outputKey");this.chatHistory=e?.chatHistory??new Tnt,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}async saveContext(e,n){await this.chatHistory.addUserMessage(ake(e,this.inputKey)),await this.chatHistory.addAIMessage(Int(n,this.outputKey))}async clear(){await this.chatHistory.clear()}};Pnt();ei();ei();ei();var Ant=class extends eI{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});A(this,"humanPrefix","Human");A(this,"aiPrefix","AI");A(this,"memoryKey","history");this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:n}:{[this.memoryKey]:nh(n,this.humanPrefix,this.aiPrefix)}}};ei();var Ent=class extends eI{constructor(e){super({returnMessages:e?.returnMessages??!1,chatHistory:e?.chatHistory,inputKey:e?.inputKey,outputKey:e?.outputKey});A(this,"humanPrefix","Human");A(this,"aiPrefix","AI");A(this,"memoryKey","history");A(this,"k",5);this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.k=e?.k??this.k}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:n.slice(-this.k*2)}:{[this.memoryKey]:nh(n.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};Pnt();xL();ei();ei();ei();var Hne=class t{constructor(){this.initMemory(),si(()=>{let e=this.memory?.chatHistory;this.initMemory(e)})}static getInstance(){return t.instance||(t.instance=new t),t.instance}initMemory(e){let n=le().contextTurns;this.memory=new Ent({k:n*2,memoryKey:"history",inputKey:"input",returnMessages:!0,chatHistory:e}),this.debug&&H("Memory initialized with context turns:",n)}getMemory(){return this.memory}async clearChatMemory(){this.debug&&H("Clearing chat memory"),await this.memory.clear()}async loadMemoryVariables(){let e=await this.memory.loadMemoryVariables({});return this.debug&&H("Loaded memory variables:",e),e}async saveContext(e,n){let r=typeof n=="string"?pq(n):{...n,output:pq(n.output)};this.debug&&H("Saving to memory - Input:",e,"Output (compacted):",r),await this.memory.saveContext(e,r)}};var Wne=class{constructor(e,n){this.pendingModelError=null;this.app=e,this.modelManagement=n,this.memoryManager=Hne.getInstance(),this.chatModelManager=qw.getInstance(),this.userMemoryManager=new lM(e),this.initialize().catch(r=>W("ChainManager initialize failed",r)),si(()=>{this.createChainWithNewModel().catch(r=>W("createChainWithNewModel failed",r))}),n.providerRegistry.subscribe(()=>{this.createChainW
`,a||e.originalMessage||e.message),this.validateChatModel();let l=this.chatModelManager.getChatModel();if(s||z5(l)){let u=bO.fromMessages([new nF("history"),rF.fromTemplate("{input}")]);z5(l)&&(u=bO.fromMessages([[Un,LW(await TD(this.app))],u])),this.createChainWithNewModel({prompt:u},!1).catch(d=>W("createChainWithNewModel failed",d))}return await this.getChainRunner().run(e,n,r,o,i)}};var YT=class t{constructor(e,n){this.chainMangerInstance=new Wne(e,n),Zpt(()=>{this.getCurrentChainManager().createChainWithNewModel()}),Ypt(()=>{this.getCurrentChainManager().createChainWithNewModel()})}static getInstance(e,n){return t.instance||(t.instance=new t(e,n)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}};Ma();JO();ge();xy();var lke=class t{constructor(e){this.memoryCache=new Map;this.cacheDir=e}static getInstance(e=".copilot/file-content-cache"){return t.instance||(t.instance=new t(e)),t.instance}async ensureCacheDir(e){await e.adapter.exists(this.cacheDir)||(H("Creating file cache directory:",this.cacheDir),await e.adapter.mkdir(this.cacheDir))}getCacheKey(e,n){let r=`${e.path}:${e.stat.size}:${e.stat.mtime}${n?`:${n}`:""}`;return df(r)}getCachePath(e){return`${this.cacheDir}/${e}.md`}async get(e,n){try{let r=this.memoryCache.get(n);if(r)return H("Memory cache hit for file:",n),r.content;let o=this.getCachePath(n);if(await e.adapter.exists(o)){H("File cache hit:",n);let i=await e.adapter.read(o),s,a=i.trim();if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{s=JSON.parse(i)}catch{s=i}else s=i;let l={content:s,timestamp:Date.now()};return this.memoryCache.set(n,l),l.content}return H("Cache miss for file:",n),null}catch(r){return W("Error reading from file cache:",r),null}}async set(e,n,r){try{await this.ensureCacheDir(e);let o=this.getCachePath(n),i=Date.now(),s={content:r,timestamp:i};this.memoryCache.set(n,s);let a;typeof r=="string"?a=r:a=JSON.stringify(r,null,2),await e.adapter.write(o,a),H("Cached file content:",n)}catch(o){W("Error writing to file cache:",o)}}async clear(e){try{if(this.memoryCache.clear(),await e.adapter.exists(this.cacheDir)){let n=await e.adapter.list(this.cacheDir);H("Clearing file cache, removing files:",n.files.length);for(let r of n.files)await e.adapter.remove(r)}}catch(n){W("Error clearing file cache:",n)}}};ge();RE();var Fvn=require("obsidian");ot();Vl();tce();EP();tA();var mi=R(U());Qa();De();Le();ge();var lC=R(U());function $vn(){return lC.default.createElement("ul",{className:"tw-m-0 tw-px-4 tw-text-sm"},lC.default.createElement("li",null,lC.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{}")," represents the selected text."),lC.default.createElement("li",null,lC.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{[[Note Title]]}")," represents a note."),lC.default.createElement("li",null,lC.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{activeNote}")," represents the active note."),lC.default.createElement("li",null,lC.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{#tag1, #tag2}")," represents ALL notes with ANY of the specified tags in their property (an OR operation)."))}pg();Mnt();function HDr({commands:t,command:e,onConfirm:n,onCancel:r}){let{options:o,resolveSelectionId:i}=uke(),[s,a]=(0,mi.useState)(()=>({...e,modelKey:e.modelKey?i(e.modelKey)||e.modelKey:""})),[l,c]=(0,mi.useState)({}),u=(f,p)=>{a(m=>({...m,[f]:p})),c(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=ywe(s.title,t,e.title);if(p&&(f.title=p),s.content.trim()||(f.content="Prompt is required"),Object.keys(f).length>0){c(f);return}n(s)};return mi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},mi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},mi.default.createElement(Ny,{htmlFor:"title"},"Name"),mi.default.createElement(Tr,{id:"title",value:s.title,onChange:f=>u("title",f.target.value),placeholder:"Enter command name"}),l.title&&mi.default.createElement("div",{className:"tw-text-sm tw-text-error"},l.title)),mi.default.cre
You are an AI assistant designed to execute user instructions with precision. Your responses should be:
- Direct and focused: Address only what is explicitly requested
- Concise: Avoid unnecessary elaboration unless the user asks for details
- Context-aware: When text is selected or highlighted, treat it as the primary target for any requested action
- Action-oriented: Prioritize completing the task over explaining the process
Key principles:
- Follow instructions literally and completely
- Assume selected/highlighted text is the focus unless told otherwise
- Use all provided context: Consider any additional information, examples, or constraints the user provides to better complete the task
- Add explanations only when explicitly requested or when clarification is essential
- Maintain the user's preferred format and style
Response format: Match the format implied by the user's request (e.g., if they ask for a list, provide a list; if they ask for a rewrite, provide only the rewritten text).
${f.transcript}`;await navigator.clipboard.writeText(S),new wq.Notice("Transcript copied to clipboard!")}catch(S){W("Failed to copy to clipboard:",S),new wq.Notice("Failed to copy to clipboard")}},y=async()=>{if(f)try{let S=`# YouTube Video Transcript
${e}`;return await t.create(l,c),l}async function o$r(t,e,n){try{let r=await t.read(e),o=uy(r,{trimStart:!1}),i=Wnt(o).replace(/^\n+/,""),s=Wnt(n).replace(/^\n+/,"");return i!==s?(V(`Migration verification failed: content mismatch. Expected ${s.length} chars, got ${i.length} chars`),!1):!0}catch(r){return W("Migration verification failed: unable to read back file",r),!1}}async function Vnt(t){let e=t.vault,r=le().userSystemPrompt;if(!r||r.trim().length===0)return H("No legacy userSystemPrompt to migrate"),null;try{H("Migrating legacy userSystemPrompt from settings to file system");let o=cC();await Fo(e,o);let i=r$r(lbn,e),s=Bnt(i,o);i!==lbn&&H(`Default name already exists, using unique name: "${i}"`);let a=Date.now(),l=Wnt(r),c={title:i,content:l,createdMs:a,modifiedMs:a,lastUsedMs:0};await e.create(s,l);let u=e.getAbstractFileByPath(s);if(!(u instanceof ubn.TFile))throw new Error("File not found after creation");if(await Gne(t,u,c),await o$r(e,u,r)){Gt("defaultSystemPromptTitle",i);try{await Kne(t)}catch(f){V("Failed to reload prompts after migration:",f)}return Gt("userSystemPrompt",""),H("Cleared legacy userSystemPrompt field"),{id:"system-prompt",title:"System prompt",status:"success",summary:`Migrated "${i}" and set it as the default system prompt.`,details:[`Stored in ${s}.`]}}else{let f=await cbn(e,r,"content verification mismatch");try{await Kne(t)}catch(p){V("Failed to reload prompts after failed migration:",p)}return Gt("userSystemPrompt",""),H("Cleared legacy userSystemPrompt field (saved to unsupported)"),{id:"system-prompt",title:"System prompt",status:"action-required",summary:"The prompt was preserved, but its migrated content could not be verified.",details:[`Review ${f}, then move it to ${o} to make the prompt available.`]}}}catch(o){let i=o instanceof Error?o.message:String(o);W("Failed to migrate legacy userSystemPrompt:",o);try{let s=await cbn(e,r,i);return Gt("userSystemPrompt",""),H("Cleared legacy userSystemPrompt field (saved to unsupported after error)"),{id:"system-prompt",title:"System prompt",status:"action-required",summary:"The prompt migration failed, but the original content was preserved.",details:[`Review ${s}, then move it to ${cC()} to make the prompt available.`]}}catch(s){return W("Failed to save to unsupported folder:",s),V("Preserving userSystemPrompt in settings for manual recovery"),{id:"system-prompt",title:"System prompt",status:"error",summary:"The prompt could not be migrated. It remains in settings and will be retried.",details:[i,`Check folder permissions and available disk space for ${cC()}.`]}}}}ge();Ma();vC();ot();$v();Ble();Le();var yh=R(U());function dbn({selectedChain:t,isPaidUser:e,onModeChange:n,onPlusUpsell:r,defaultOpen:o}){return yh.default.createElement(wU,{defaultOpen:o},yh.default.createElement(vU,{asChild:!0},yh.default.createElement(ie,{variant:"ghost2",size:"fit",className:"tw-ml-1 tw-text-sm tw-text-muted"},t==="llm_chain"?"chat (free)":yh.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},yh.default.createElement(vc,{className:"tw-size-4"}),"copilot plus"),yh.default.createElement(is,{className:"tw-mt-0.5 tw-size-5"}))),yh.default.createElement(tl,{align:"start"},yh.default.createElement(Jr,{onSelect:()=>n("llm_chain")},"chat (free)"),e?yh.default.createElement(Jr,{onSelect:()=>n("copilot_plus")},yh.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},yh.default.createElement(vc,{className:"tw-size-4"}),"copilot plus")):yh.default.createElement(Jr,{onSelect:r},"copilot plus",yh.default.createElement(iP,{className:"tw-size-3"}))))}ot();$v();lx();Lc();Bl();Ee();Ble();Le();var oi=R(U());nHe();e3e();var Pn=R(U());no();ot();Ux();tce();var uF=R(U());De();Le();function fbn({options:t,placeholder:e,containerClassName:n,className:r,...o}){return uF.default.createElement("div",{className:X("tw-group tw-relative tw-w-full",n)},uF.default.createElement("select",{className:X("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-t
`));let St={notes:mc,urls:nd(m)?xn||[]:[],tags:na||[],folders:_a||[],selectedTextContexts:E,webTabs:pc||[]};v(""),oe([]),S.current=`msg-${zr()}`,z.setLoading(!0),z.setLoadingMessage(bh.DEFAULT);let ut=await i.sendMessage(gi,St,m,F,Y,xa.length>0?xa:void 0,z.setLoadingMessage);y&&n(y),a.autosaveChat&&await Pe();let wt=i.getLLMMessage(ut);wt&&await Gnt(wt,t,k,z.setCurrentAiMessage,x,{debug:a.debug,updateLoadingMessage:z.setLoadingMessage}),a.autosaveChat&&await Pe()}catch(xa){W("Error sending message:",xa),new dc.Notice("Failed to send message. Please try again.")}finally{z.setLoading(!1),z.setLoadingMessage(bh.DEFAULT),S.current=null}},Pe=(0,hn.useCallback)(async()=>{if(!ee){W("App instance is not available.");return}try{await i.saveChat(f)}catch(Ue){W("Error saving chat as note:",Dt(Ue)),new dc.Notice("Failed to save chat as note. Check console for details.")}},[ee,i,f]),Fe=(0,hn.useCallback)(Ue=>{_.current&&(H(`stopping generation..., reason: ${Ue}`),_.current.abort(Ue),z.setLoading(!1),z.setLoadingMessage(bh.DEFAULT))},[z]);(0,hn.useEffect)(()=>(ue.current=!0,()=>{ue.current=!1,_.current&&_.current.abort("component-unmount")}),[]);let Ye=(0,hn.useCallback)(async Ue=>{if(Ue<=0){new dc.Notice("Cannot regenerate the first message.");return}let xn=c[Ue];if(!xn){new dc.Notice("Message not found.");return}z.setCurrentAiMessage(""),S.current=`msg-${zr()}`,z.setLoading(!0);try{await i.regenerateMessage(xn.id,z.setCurrentAiMessage,k)?a.debug&&H("Message regenerated successfully"):new dc.Notice("Failed to regenerate message. Please try again."),a.autosaveChat&&await Pe()}catch(br){W("Error regenerating message:",br),new dc.Notice("Failed to regenerate message. Please try again.")}finally{z.setLoading(!1),S.current=null}},[c,i,a.debug,a.autosaveChat,Pe,k,z]),Oe=(0,hn.useCallback)(async(Ue,xn)=>{let br=c[Ue];if(!(!br||br.message===xn))try{if(!await i.editMessage(br.id,xn,m,!1)){new dc.Notice("Failed to edit message. Please try again.");return}if(br.sender===Un){let _a=Ue<c.length-1;if(await i.truncateAfterMessageId(br.id),_a){S.current=`msg-${zr()}`,z.setLoading(!0);try{let pc=i.getLLMMessage(br.id);pc&&await Gnt(pc,t,k,z.setCurrentAiMessage,x,{debug:a.debug,updateLoadingMessage:z.setLoadingMessage})}catch(pc){W("Error regenerating AI response:",pc),new dc.Notice("Failed to regenerate AI response. Please try again.")}finally{z.setLoading(!1),S.current=null}}}a.autosaveChat&&await Pe()}catch(na){W("Error editing message:",na),new dc.Notice("Failed to edit message. Please try again.")}},[c,i,m,k,t,a.debug,a.autosaveChat,Pe,z,x]);(0,hn.useEffect)(()=>{e&&e(Pe)},[e,Pe]);let Kt=(0,hn.useCallback)(Ue=>{let br=t0().find(na=>na.id===Ue);wse(Ue),br?.sourceType==="web"&&o.suppressCurrentWebSelection(br.url)},[o]);(0,hn.useEffect)(()=>{o.chatSelectionHighlightController.clearIfNoNoteContexts(E)},[E,o]),(0,hn.useEffect)(()=>{let Ue=()=>{s.focusInput()};return l?.addEventListener(rs.CHAT_IS_VISIBLE,Ue),()=>{l?.removeEventListener(rs.CHAT_IS_VISIBLE,Ue)}},[l,s]),(0,hn.useEffect)(()=>{let Ue=l instanceof ry?l:null,xn=na=>{Ue?.consumePendingInsertText();let _a=na.detail?.text;typeof _a=="string"&&s.insertTextWithPills(_a,!0)};l?.addEventListener(rs.INSERT_TEXT_TO_CHAT,xn);let br=Ue?.consumePendingInsertText();return typeof br=="string"&&s.insertTextWithPills(br,!0),()=>{l?.removeEventListener(rs.INSERT_TEXT_TO_CHAT,xn)}},[l,s]);let Ke=(0,hn.useCallback)(async Ue=>{let xn=c[Ue];if(!xn){new dc.Notice("Message not found.");return}try{await i.deleteMessage(xn.id)||new dc.Notice("Failed to delete message. Please try again.")}catch(br){W("Error deleting message:",br),new dc.Notice("Failed to delete message. Please try again.")}},[c,i]),$e=(0,hn.useCallback)(async()=>{if(UH(),await bu.clear(),Fe("new-chat"),a.enableRecentConversations)try{let xn=t.chatModelManager.getChatModel();o.userMemoryManager.addRecentConversation(i.getMessages(),xn)}catch(xn){H("Failed to analyze chat messages for memory:",xn)}a.autosaveChat&&await Pe(),i.clearMessages(),mMe(),z.setCurrentAiMessage(""),D([]);let Ue=E.find(xn=>xn.sourceType==="web")?.url;PG(),o.chatSelectionHighli
</user_custom_instructions>`):n===r?o:(H("[ChatManager] Could not locate <user_custom_instructions> block for injection; returning original system prompt."),n)}replaceSystemPromptWithoutMemoryInBasePrompt(e){let{basePromptWithMemory:n,systemPromptWithoutMemory:r,processedSystemPromptWithoutMemory:o}=e;return n.endsWith(r)?`${n.slice(0,n.length-r.length)}${o}`:(H("[ChatManager] basePromptWithMemory does not end with systemPromptWithoutMemory; returning original base prompt."),n)}async getSystemPromptForMessage(e,n,r){let o=await TD(this.plugin.app),i=[],s=await $Q(this.chainManager.userMemoryManager,o),a=LW(o),l=s;if(o){let c=await this.processSystemPromptTemplates(o,n,r),u=this.injectProcessedUserCustomPromptIntoSystemPrompt({systemPromptWithoutMemory:a,userCustomPrompt:o,processedUserCustomPrompt:c.processedPrompt}),d=this.replaceSystemPromptWithoutMemoryInBasePrompt({basePromptWithMemory:s,systemPromptWithoutMemory:a,processedSystemPromptWithoutMemory:u});d!==s&&i.push(...c.includedFiles),l=d}return{processedPrompt:l,includedFiles:i}}async sendMessage(e,n,r,o=!1,i=!1,s,a){try{H(`[ChatManager] Sending message: "${e}"`);let l=this.plugin.app.workspace.getActiveFile(),c=Wwe(e,zu()).text,u={...n};if(o&&l){let v=n.notes||[],_=v.some(S=>S.path===l.path);u.notes=_?v:[...v,l]}let f=!((u.selectedTextContexts||[]).length>0)&&(i||c.includes(xC));u.webTabs=Vwe(this.plugin.app,u.webTabs||[],f);let p=this.messageRepo.addMessage(c,c,Un,u,s);this.onMessageCreatedCallback&&this.onMessageCreatedCallback(p);let m=this.messageRepo.getMessage(p);if(!m)throw new Error(`Failed to retrieve message ${p}`);let{processedPrompt:h,includedFiles:g}=await this.getSystemPromptForMessage(r,this.plugin.app.vault,l),{processedContent:w,contextEnvelope:y}=await this.contextManager.processMessageContext(this.plugin.app,m,this.fileParserManager,this.plugin.app.vault,r,o,l,this.messageRepo,h,g,a);return this.messageRepo.updateProcessedText(p,w,y),H(`[ChatManager] Successfully sent message ${p}`),p}catch(l){throw H("[ChatManager] Error sending message:",l),l}}async editMessage(e,n,r,o=!1){try{if(H(`[ChatManager] Editing message ${e}: "${n}"`),!this.messageRepo.editMessage(e,n))return!1;let s=this.plugin.app.workspace.getActiveFile(),{processedPrompt:a,includedFiles:l}=await this.getSystemPromptForMessage(r,this.plugin.app.vault,s);return await this.contextManager.reprocessMessageContext(this.plugin.app,e,this.messageRepo,this.fileParserManager,this.plugin.app.vault,r,o,s,a,l),await this.updateChainMemory(),H(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return H(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,n,r,o){try{if(H(`[ChatManager] Regenerating message ${e}`),!this.messageRepo.getMessage(e))return H(`[ChatManager] Message not found: ${e}`),!1;let s=this.messageRepo.getDisplayMessages(),a=s.findIndex(h=>h.id===e);if(a<=0)return H("[ChatManager] Cannot regenerate first message or no user message found"),!1;let l=s[a-1];if(l.sender!==Un)return H("[ChatManager] Previous message is not from user"),!1;if(this.messageRepo.truncateAfter(a-1),o&&o(),await this.updateChainMemory(),!l.id)return H("[ChatManager] User message has no ID for regeneration"),!1;let c=this.messageRepo.getLLMMessage(l.id);if(!c)return H("[ChatManager] LLM message not found for regeneration"),!1;let u=IG(),d=this.plugin.app.workspace.getActiveFile(),{processedPrompt:f,includedFiles:p}=await this.getSystemPromptForMessage(u,this.plugin.app.vault,d);await this.contextManager.reprocessMessageContext(this.plugin.app,l.id,this.messageRepo,this.fileParserManager,this.plugin.app.vault,u,!1,d,f,p),c=this.messageRepo.getLLMMessage(l.id);let m=new AbortController;return await this.chainManager.runChain(c,m,n,r,{debug:le().debug}),H(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return H(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return H(`[ChatManager] Deleting message ${e}`),this.messageRepo.deleteMessage(e)?(await this.updateChainMemory(),H(`[ChatManager] Successfully deleted message ${e}`)
`});let s=e.nodes.filter(a=>a.type==="group"?!1:!Array.from(n.values()).flat().some(l=>l.id===a.id));return s.length>0&&(o+=`Elements outside of groups:
`,s.forEach(a=>{o+=i(a)})),o+=`
When describing this canvas, please:
`,o+=`- Use the actual titles/names of elements instead of their IDs
`,o+=`- Pay attention to the content and relationships between elements
`,o+=`- Describe files by their names, links by their URLs, and text nodes by their content
`,o}};xTe=new WeakSet,qxn=function(e,n){let r=e.filter(o=>o.type==="group");for(let o of r)for(let i of e){if(i.id===o.id)continue;let s=i.x+i.width/2,a=i.y+i.height/2;s>=o.x&&a>=o.y&&s<=o.x+o.width&&a<=o.y+o.height&&n.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}};var szr=new Set(["pdf","epub"]);function $rt(t){return szr.has(t.extension.toLowerCase())}async function STe(t,e,n){let r=le().convertedDocOutputFolder??"";await jxn(t,e,n,r)}var CTe=class{constructor(){this.miyoClient=new Su}async parseDoc(e,n){let r=le();if(!$rt(e))return null;try{let o=await this.miyoClient.resolveBaseUrl(Zo(r)),i=n.getName(),s=await this.miyoClient.parseDoc(o,i,e.path);return typeof s.text!="string"||s.text.trim().length===0?{error:"Miyo parse-doc returned empty text"}:(H(`[SelfHostDocParser] Parsed document via Miyo: ${e.path}`),{content:s.text})}catch(o){let i=o instanceof Error?o.message:String(o);return V(`[SelfHostDocParser] Failed to parse ${e.path} via Miyo parse-doc: ${i}`),{error:i}}}},Nrt=class{constructor(){this.supportedExtensions=["md","base"]}async parseFile(e,n){return await n.read(e)}},kTe=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=bTe.getInstance(),this.selfHostDocParser=new CTe}async parseFile(e,n){try{H("Parsing PDF file:",e.path);let r=await this.pdfCache.get(n,e);if(r)return H("Using cached PDF content for:",e.path),await STe(e,r.response,n),r.response;let o=le(),i=$rt(e)?await bMe(o):"plus";if(i==="miyo-unavailable")return V(`[PDFParser] Miyo unavailable for ${e.path}; not falling back to cloud`),`[Error: Could not extract content from PDF ${e.basename}. Miyo (local document processor) is unavailable — reconnect it or switch the Document Processor to Plus in settings.]`;if(i==="miyo"){let l=await this.selfHostDocParser.parseDoc(e,n);if(l&&"content"in l)return await this.pdfCache.set(n,e,{response:l.content,elapsed_time_ms:0}),await STe(e,l.content,n),l.content;if(l&&"error"in l)return V(`[PDFParser] Miyo parse failed for ${e.path}: ${l.error}`),`[Error: Could not extract content from PDF ${e.basename}. ${l.error}]`}let s=await n.readBinary(e);H("Calling pdf4llm API for:",e.path);let a=await this.brevilabsClient.pdf4llm(s);return await this.pdfCache.set(n,e,a),await STe(e,a.response,n),a.response}catch(r){return W(`Error extracting content from PDF ${e.path}:`,r),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(e){H("Clearing PDF cache"),await this.pdfCache.clear(e)}},Lrt=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,n){try{H("Parsing Canvas file:",e.path);let r=new _Te(n),o=await r.load(e);return r.buildPrompt(o)}catch(r){return W(`Error parsing Canvas file ${e.path}:`,r),`[Error: Could not parse Canvas file ${e.basename}]`}}},azr=["pdf","602","abw","cgm","cwk","doc","docx","docm","dot","dotm","hwp","key","lwp","mw","mcw","pages","pbd","ppt","pptm","pptx","pot","potm","potx","rtf","sda","sdd","sdp","sdw","sgl","sti","sxi","sxw","stw","sxg","txt","uof","uop","uot","vor","wpd","wps","xml","zabw","epub","jpg","jpeg","png","gif","bmp","svg","tiff","webp","web","htm","html","xlsx","xls","xlsm","xlsb","xlw","csv","dif","sylk","slk","prn","numbers","et","ods","fods","uos1","uos2","dbf","wk1","wk2","wk3","wk4","wks","123","wq1","wq2","wb1","wb2","wb3","qpw","xlr","eth","tsv","mp3","mp4","mpeg","mpga","m4a","wav","webm"],ure=class ure{constructor(){this.supportedExtensions=[...azr];this.selfHostDocParser=new CTe}async parseFile(e,n){try{H(`[Docs4LLMParser] Parsing ${e.extension} file: ${e.path}`);let r=$rt(e)?await bMe():"plus";if(r==="miyo-unavailable")throw new Error(`Miyo (local document processor) is unavailable for ${e.basename}; not falling back to cloud. Reconnect Miyo or switch the Document Processor to Plus.`);if(r==="miyo"){let o=await this.selfHostDocParser.parseDoc(e,n);if(o&&"content"in o)return await STe(e,o.content,n),H(`[Docs4LLMParser] Parsed document via Miyo: ${e.path}`),o.content;if(o&&"error"in o)throw new Error(`Miyo failed to parse ${e.basename}: ${o.error}`)}throw new
`))throw new Error(`Refusing to append to non-ledger file: ${Eq}`);let s=r&&!/[\r\n]$/.test(o)?`
`:"";await t.adapter.append(Eq,`${r?s:`${Yrt}
`}| ${n} |
`)}xy();var LSn=require("obsidian"),$zr="Add a Copilot Plus license key in Settings before publishing with OpenArtifacts.",Fzr="An OpenArtifacts action is already in progress for this note.";async function zzr(){return le().plusLicenseKey.trim()}async function Uzr(t,e,n){let r=new LSn.Component;r.load();try{return await ESn(t,e,r,n)}finally{r.unload()}}function Qrt(t,e){return e instanceof oI||e instanceof Aq?{kind:"failure",action:t,message:e.message,accessNotice:!1,retryable:!1}:e instanceof MO?{kind:"failure",action:t,message:e.message,accessNotice:!1,retryable:!1}:e instanceof S_?{kind:"failure",action:t,message:e.message,accessNotice:e.status===401&&e.code==="unauthorized",retryable:e.retryable}:{kind:"failure",action:t,message:"Copilot could not complete this OpenArtifacts action.",accessNotice:!1,retryable:!0}}function eot(t){return{kind:"failure",action:t,message:"This note's OpenArtifacts identity changed. Close and reopen this dialog before trying again.",accessNotice:!1,retryable:!1}}var NTe=class{constructor(e,n={}){this.app=e;this.inFlightFiles=new Set;this.blockedPublishResults=new Map;this.modals=new Set;this.disposed=!1;this.client=n.client??new ETe,this.loadLicenseKey=n.loadLicenseKey??zzr,this.buildDocument=n.buildDocument??((r,o)=>Uzr(this.app,r,o)),this.createModal=n.createModal??(r=>new ATe(this.app,r)),this.recordLedger=n.recordLedger??(r=>NSn(this.app.vault,r))}async open(e){if(this.disposed)return;let n=null,r=this.blockedPublishResults.get(e);if(!r)try{n=await AF(this.app,e)}catch(s){if(!(s instanceof oI)&&!(s instanceof Aq))throw s;r=Qrt("publish",s)}if(this.disposed)return;let o=r,i;i=this.createModal({fileName:e.basename,docId:n,initialResult:o,onConfirm:o?()=>Promise.resolve(o):(s,a)=>this.execute(e,n,s,a),onClosed:()=>this.modals.delete(i)}),this.modals.add(i);try{i.open()}catch(s){throw this.modals.delete(i),s}}dispose(){this.disposed=!0;for(let e of[...this.modals])e.close();this.modals.clear(),this.blockedPublishResults.clear()}async execute(e,n,r,o){let i=n?"update":"publish",s=r==="delete",a=s?"delete":i;return this.withFileLock(e,a,async()=>{if(this.disposed)return{kind:"failure",action:a,message:"OpenArtifacts publishing is no longer available.",accessNotice:!1,retryable:!1};let l=this.blockedPublishResults.get(e);if(l)return l;let c;try{c=await AF(this.app,e)}catch(f){return Qrt(a,f)}if(c!==n)return eot(a);let u=s?"delete":c?"update":"publish",d;try{d=await this.loadLicenseKey()}catch{d=""}if(!d)return{kind:"failure",action:u,message:$zr,accessNotice:!0,retryable:!1};if(u==="delete"&&!c)return{kind:"failure",action:u,message:"This note no longer has a valid OpenArtifacts link.",accessNotice:!1,retryable:!1};try{if(u==="delete")return await AF(this.app,e)!==c?eot(u):(await this.client.delete(c,d),await this.recordLedgerSafely({docId:c,status:"unpublished",notePath:e.path,url:null,publishedAt:null,version:null,contentHash:null}),await this.removeLocalIdentity(e,c));let f=await this.buildDocument(e,o);if(await AF(this.app,e)!==c)return eot(u);if(!c){let w=await this.client.publish(f,d);return await this.recordPublishedReceipt(e,f,w),await this.savePublishedIdentity(e,w)}let m=await this.client.update(c,f,d);await this.recordPublishedReceipt(e,f,m);let h=!1,g;try{g=await AF(this.app,e),g===c&&(h=await qrt(this.app,e,m))}catch{}if(!h){let w={kind:"persistence",action:"update",message:"The original page was updated, but this note’s OpenArtifacts identity changed or could not be verified. Its current identity was left unchanged.",receipt:m};return g||this.blockedPublishResults.set(e,w),w}return{kind:"success",action:"update",receipt:m}}catch(f){let p=Qrt(u,f);return f instanceof S_&&f.code==="ambiguous_publish"&&this.blockedPublishResults.set(e,p),p}})}async recordPublishedReceipt(e,n,r){await this.recordLedgerSafely({docId:r.docId,status:"published",notePath:e.path,url:r.url,publishedAt:new Date().toISOString(),version:r.version,contentHash:K_(n.html)})}async recordLedgerSafely(e){try{await this.recordLedger(e)}catch(n){V("Could not append an OpenArtifacts receipt to the recoverable led