Files
my-vault/.obsidian/plugins/copilot/main.js
T

3351 lines
5.2 MiB
JavaScript
Raw Normal View History

2026-01-05 13:03:55 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
// Polyfill for import.meta in CommonJS context
if (typeof import_meta === 'undefined') {
var import_meta = {
url: typeof __filename !== 'undefined' ? 'file://' + __filename : 'file:///obsidian-plugin'
};
}
2026-02-24 07:55:02 +08:00
var Hcn=Object.create;var IQ=Object.defineProperty;var Wcn=Object.getOwnPropertyDescriptor;var Jcn=Object.getOwnPropertyNames;var Kcn=Object.getPrototypeOf,Gcn=Object.prototype.hasOwnProperty;var lCt=t=>{throw TypeError(t)};var Xcn=(t,e,r)=>e in t?IQ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),En=(t,e)=>{for(var r in e)IQ(t,r,{get:e[r],enumerable:!0})},cCt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Jcn(e))!Gcn.call(t,o)&&o!==r&&IQ(t,o,{get:()=>e[o],enumerable:!(n=Wcn(e,o))||n.enumerable});return t};var $=(t,e,r)=>(r=t!=null?Hcn(Kcn(t)):{},cCt(e||!t||!t.__esModule?IQ(r,"default",{value:t,enumerable:!0}):r,t)),Bpe=t=>cCt(IQ({},"__esModule",{value:!0}),t);var x=(t,e,r)=>Xcn(t,typeof e!="symbol"?e+"":e,r),Zcn=(t,e,r)=>e.has(t)||lCt("Cannot "+r);var cBe=(t,e,r)=>e.has(t)?lCt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var dCt=(t,e,r)=>(Zcn(t,e,"access private method"),r);function dBe(){if(!zpe&&(zpe=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!zpe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return zpe(Ycn)}var zpe,Ycn,fCt=v(()=>{Ycn=new Uint8Array(16)});function pCt(t,e=0){return Sg[t[e+0]]+Sg[t[e+1]]+Sg[t[e+2]]+Sg[t[e+3]]+"-"+Sg[t[e+4]]+Sg[t[e+5]]+"-"+Sg[t[e+6]]+Sg[t[e+7]]+"-"+Sg[t[e+8]]+Sg[t[e+9]]+"-"+Sg[t[e+10]]+Sg[t[e+11]]+Sg[t[e+12]]+Sg[t[e+13]]+Sg[t[e+14]]+Sg[t[e+15]]}var Sg,mCt=v(()=>{Sg=[];for(let t=0;t<256;++t)Sg.push((t+256).toString(16).slice(1))});var Qcn,fBe,hCt=v(()=>{Qcn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),fBe={randomUUID:Qcn}});function edn(t,e,r){if(fBe.randomUUID&&!e&&!t)return fBe.randomUUID();t=t||{};let n=t.random||(t.rng||dBe)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let o=0;o<16;++o)e[r+o]=n[o];return e}return pCt(n)}var od,gCt=v(()=>{hCt();fCt();mCt();od=edn});var qN=v(()=>{gCt()});var tdn,$t,Jo=v(()=>{tdn=Object.defineProperty,$t=(t,e)=>{for(var r in e)tdn(t,r,{get:e[r],enumerable:!0})}});function AQ(t,e=Mz){t=t.trim();let r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
2026-01-05 13:03:55 +08:00
`)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
2026-02-24 07:55:02 +08:00
`)&&(n=n.substring(1));let o=n.indexOf("```"),i=n;return o!==-1&&(i=n.substring(0,o)),e(i.trim())}function rdn(t){try{return JSON.parse(t)}catch{}let e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let r=0;function n(){for(;r<e.length&&/\s/.test(e[r]);)r+=1}function o(){if(e[r]!=='"')throw new Error(`Expected '"' at position ${r}, got '${e[r]}'`);r+=1;let c="",d=!1;for(;r<e.length;){let f=e[r];if(d){if(f==="n")c+=`
`;else if(f==="t")c+=" ";else if(f==="r")c+="\r";else if(f==="\\")c+="\\";else if(f==='"')c+='"';else if(f==="b")c+="\b";else if(f==="f")c+="\f";else if(f==="/")c+="/";else if(f==="u"){let p=e.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?c+=String.fromCharCode(Number.parseInt(p,16)):c+=`u${p}`,r+=p.length;else throw new Error(`Invalid unicode escape sequence '\\u${p}' at position ${r}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${r}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return r+=1,c;c+=f}r+=1}return d&&(c+="\\"),c}function i(){let c=r,d="";if(e[r]==="-"&&(d+="-",r+=1),r<e.length&&e[r]==="0"&&(d+="0",r+=1,e[r]>="0"&&e[r]<="9"))throw new Error(`Invalid number at position ${c}`);if(r<e.length&&e[r]>="1"&&e[r]<="9")for(;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&e[r]===".")for(d+=".",r+=1;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&(e[r]==="e"||e[r]==="E"))for(d+=e[r],r+=1,r<e.length&&(e[r]==="+"||e[r]==="-")&&(d+=e[r],r+=1);r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(d==="-")return-0;let f=Number.parseFloat(d);if(Number.isNaN(f))throw r=c,new Error(`Invalid number '${d}' at position ${c}`);return f}function a(){if(n(),r>=e.length)throw new Error(`Unexpected end of input at position ${r}`);let c=e[r];if(c==="{")return u();if(c==="[")return s();if(c==='"')return o();if("null".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),null;if("true".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),!0;if("false".startsWith(e.substring(r,r+5)))return r+=Math.min(5,e.length-r),!1;if(c==="-"||c>="0"&&c<="9")return i();throw new Error(`Unexpected character '${c}' at position ${r}`)}function s(){if(e[r]!=="[")throw new Error(`Expected '[' at position ${r}, got '${e[r]}'`);let c=[];if(r+=1,n(),r>=e.length)return c;if(e[r]==="]")return r+=1,c;for(;r<e.length;){if(n(),r>=e.length||(c.push(a()),n(),r>=e.length))return c;if(e[r]==="]")return r+=1,c;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or ']' at position ${r}, got '${e[r]}'`)}return c}function u(){if(e[r]!=="{")throw new Error(`Expected '{' at position ${r}, got '${e[r]}'`);let c={};if(r+=1,n(),r>=e.length)return c;if(e[r]==="}")return r+=1,c;for(;r<e.length;){if(n(),r>=e.length)return c;let d=o();if(n(),r>=e.length)return c;if(e[r]!==":")throw new Error(`Expected ':' at position ${r}, got '${e[r]}'`);if(r+=1,n(),r>=e.length||(c[d]=a(),n(),r>=e.length))return c;if(e[r]==="}")return r+=1,c;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or '}' at position ${r}, got '${e[r]}'`)}return c}let l=a();if(n(),r<e.length)throw new Error(`Unexpected character '${e[r]}' at position ${r}`);return l}function Mz(t){try{return typeof t>"u"?null:rdn(t)}catch{return null}}var NQ=v(()=>{});function FL(t,e){return t.lc_error_code=e,t.message=`${t.message}
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
2026-02-24 07:55:02 +08:00
`,t}var DQ=v(()=>{});var bCt=S((ZCi,yCt)=>{"use strict";yCt.exports=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,t.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}});var TCt=S((YCi,pBe)=>{"use strict";var ndn=/[\p{Lu}]/u,odn=/[\p{Ll}]/u,_Ct=/^[\p{Lu}](?![\p{Lu}])/gu,SCt=/([\p{Alpha}\p{N}_]|$)/u,CCt=/[_.\- ]+/,idn=new RegExp("^"+CCt.source),vCt=new RegExp(CCt.source+SCt.source,"gu"),wCt=new RegExp("\\d+"+SCt.source,"gu"),adn=(t,e,r)=>{let n=!1,o=!1,i=!1;for(let a=0;a<t.length;a++){let s=t[a];n&&ndn.test(s)?(t=t.slice(0,a)+"-"+t.slice(a),n=!1,i=o,o=!0,a++):o&&i&&odn.test(s)?(t=t.slice(0,a-1)+"-"+t.slice(a-1),i=o,o=!1,n=!0):(n=e(s)===s&&r(s)!==s,i=o,o=r(s)===s&&e(s)!==s)}return t},sdn=(t,e)=>(_Ct.lastIndex=0,t.replace(_Ct,r=>e(r))),udn=(t,e)=>(vCt.lastIndex=0,wCt.lastIndex=0,t.replace(vCt,(r,n)=>e(n)).replace(wCt,r=>e(r))),xCt=(t,e)=>{if(!(typeof t=="string"||Array.isArray(t)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(t)?t=t.map(i=>i.trim()).filter(i=>i.length).join("-"):t=t.trim(),t.length===0)return"";let r=e.locale===!1?i=>i.toLowerCase():i=>i.toLocaleLowerCase(e.locale),n=e.locale===!1?i=>i.toUpperCase():i=>i.toLocaleUpperCase(e.locale);return t.length===1?e.pascalCase?n(t):r(t):(t!==r(t)&&(t=adn(t,r,n)),t=t.replace(idn,""),e.preserveConsecutiveUppercase?t=sdn(t,r):t=r(t),e.pascalCase&&(t=n(t.charAt(0))+t.slice(1)),udn(t,n))};pBe.exports=xCt;pBe.exports.default=xCt});function ECt(t,e){return e?.[t]||(0,OCt.default)(t)}function PCt(t,e,r){let n={};for(let o in t)Object.hasOwn(t,o)&&(n[e(o,r)]=t[o]);return n}var OCt,ldn,MCt=v(()=>{OCt=$(bCt(),1),ldn=$(TCt(),1)});function cdn(t){return"lc"in t||Object.keys(t).length===1&&RCt in t}function ddn(t){return{[RCt]:t}}function fdn(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function pdn(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function Vpe(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return pdn(t);if(fdn(t))return t;e.add(t);let r=t;if(cdn(r))return e.delete(t),ddn(r);let n={};for(let[o,i]of Object.entries(r))n[o]=Vpe(i,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Vpe(r,e)):t}var RCt,ICt=v(()=>{RCt="__lc_escaped__"});function ACt(t){return Array.isArray(t)?[...t]:{...t}}function hdn(t,e){let r=ACt(t);for(let[n,o]of Object.entries(e)){let[i,...a]=n.split(".").reverse(),s=r;for(let u of a.reverse()){if(s[u]===void 0)break;s[u]=ACt(s[u]),s=s[u]}s[i]!==void 0&&(s[i]={lc:1,type:"secret",id:[o]})}return r}function Hpe(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var mdn,Cg,kL=v(()=>{Jo();MCt();ICt();mdn={};$t(mdn,{Serializable:()=>Cg,get_lc_unique_name:()=>Hpe});Cg=class NCt{constructor(e,...r){x(this,"lc_serializable",!1);x(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Hpe(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof NCt||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((u,l)=>(u[l]=l in this?this[l]:this.lc_kwargs[l],u),{});for(let u=Object.getPrototypeOf(this);u;u=Object.getPrototypeOf(u))Object.assign(e,Reflect.get(u,"lc_aliases",this)),Object.assign(r,Reflect.get(u,"lc_secrets",this)),Object.assign(n,Reflect.get(u,"lc_attributes",this));Object.keys(r).forEach(u=>{let l=this,c=n,[d,...f]
`)}var KCt=v(()=>{});function Ty(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(r=>Ph(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?Rz(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>Ph(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function Ype(t,e){return t==="error"||e==="error"?"error":"success"}function xdn(t,e){function r(n,o){if(typeof n!="object"||n===null||n===void 0)return n;if(o>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,o+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],o+1);return i}return JSON.stringify(r(t,0),null,2)}function XCt(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}function Fl(t,e){if(t===void 0&&e===void 0)return;if(t===void 0||e===void 0)return t??e;let r={...t};for(let[n,o]of Object.entries(e))if(r[n]==null)r[n]=o;else{if(o==null)continue;if(typeof r[n]!=typeof o||Array.isArray(r[n])!==Array.isArray(o))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?o&&(r[n]=o):r[n]+=o}else if(typeof r[n]=="number")r[n]=r[n]+o;else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=Fl(r[n],o);else if(Array.isArray(r[n]))r[n]=Rz(r[n],o);else{if(r[n]===o)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function Rz(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{let r=[...t];for(let n of e)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){let o=r.findIndex(i=>{let a=typeof i=="object",s="index"in i&&i.index===n.index,u="id"in i&&"id"in n&&i?.id===n?.id,l=!("id"in i)||!i?.id||!("id"in n)||!n?.id;return a&&s&&(u||l)});o!==-1&&typeof r[o]=="object"&&r[o]!==null?r[o]=Fl(r[o],n):r.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function Qpe(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
2026-01-05 13:03:55 +08:00
Left ${typeof t}
2026-02-24 07:55:02 +08:00
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return Rz(t,e);if(typeof t=="object"&&typeof e=="object")return Fl(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
2026-01-05 13:03:55 +08:00
Left ${t}
2026-02-24 07:55:02 +08:00
Right ${e}`)}}function eme(t){return typeof t.role=="string"}function xg(t){return typeof t?._getType=="function"}function K6(t){return Mb.isInstance(t)}var _Be,GCt,id,Mb,Oy=v(()=>{kL();LQ();hBe();gBe();yBe();bBe();KCt();_Be=Symbol.for("langchain.message");id=class extends Cg{constructor(e){let r=typeof e=="string"||Array.isArray(e)?{content:e}:e;r.additional_kwargs||(r.additional_kwargs={}),r.response_metadata||(r.response_metadata={});super(r);x(this,"lc_namespace",["langchain_core","messages"]);x(this,"lc_serializable",!0);x(this,GCt,!0);x(this,"id");x(this,"name");x(this,"content");x(this,"additional_kwargs");x(this,"response_metadata");this.name=r.name,r.content===void 0&&r.contentBlocks!==void 0?(this.content=r.contentBlocks,this.response_metadata={output_version:"v1",...r.response_metadata}):r.content!==void 0?(this.content=r.content??[],this.response_metadata=r.response_metadata):(this.content=[],this.response_metadata=r.response_metadata),this.additional_kwargs=r.additional_kwargs,this.id=r.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){let e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[BCt,Xpe,qCt].reduce((o,i)=>i(o),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&_Be in e&&e[_Be]===!0&&Zpe(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(GCt=_Be,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let r=xdn(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}toFormattedString(e="pretty"){return JCt(this,e)}};Mb=class ZCt extends id{static isInstance(e){if(!super.isInstance(e))return!1;let r=Object.getPrototypeOf(e);for(;r!==null;){if(r===ZCt.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}}});function FQ(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function kQ(t){let e=[],r=[];for(let n of t)if(n.function){let o=n.function.name;try{let i=JSON.parse(n.function.arguments);e.push({name:o||"",args:i||{},id:n.id})}catch{r.push({name:o,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}function qQ(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function vBe(t){return t._getType()==="tool"}var Tdn,Mh,_S,G6=v(()=>{Jo();Oy();Tdn={};$t(Tdn,{ToolMessage:()=>Mh,ToolMessageChunk:()=>_S,defaultToolCallParser:()=>kQ,isDirectToolOutput:()=>FQ,isToolMessage:()=>qQ,isToolMessageChunk:()=>vBe});Mh=class extends id{constructor(e,r,n){let o=typeof e=="string"||Array.isArray(e)?{content:e,name:n,tool_call_id:r}:e;super(o);x(this,"lc_direct_tool_output",!0);x(this,"type","tool");x(this,"status");x(this,"tool_call_id");x(this,"metadata");x(this,"artifact");this.tool_call_id=o.tool_call_id,this.artifact=o.artifact,this.status=o.status,this.metadata=o.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},_S=class extends Mb{constructor(e){super(e);x(this,"type","tool");x(this,"tool_call_id");x(this,"status");x(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){let r=this.constructor;return new r({content:Ty(this.content,e.content),additional_kwargs:Fl(this.addit
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(n!=null&&o===void 0){let[i,a]=kQ(n);r.tool_calls=i??[],r.invalid_tool_calls=a??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch{r.tool_calls=[],r.invalid_tool_calls=[]}if(r.response_metadata!==void 0&&"output_version"in r.response_metadata&&r.response_metadata.output_version==="v1"&&(r.contentBlocks=r.content,r.content=void 0),r.contentBlocks!==void 0){r.tool_calls&&r.contentBlocks.push(...r.tool_calls.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})));let i=r.contentBlocks.filter(a=>a.type==="tool_call").filter(a=>!r.tool_calls?.some(s=>s.id===a.id&&s.name===a.name));i.length>0&&(r.tool_calls=i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}}super(r);x(this,"type","ai");x(this,"tool_calls",[]);x(this,"invalid_tool_calls",[]);x(this,"usage_metadata");typeof r!="string"&&(this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=r.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let r=SBe(this.response_metadata.model_provider);if(r)return r.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let r=this.tool_calls.filter(n=>!e.some(o=>o.id===n.id&&o.name===n.name));e.push(...r.map(n=>({type:"tool_call",id:n.id,name:n.name,args:n.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};Er=class extends Mb{constructor(e){let r;if(typeof e=="string"||Array.isArray(e))r={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)r={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let n=ame(e.tool_call_chunks??[]);r={...e,tool_call_chunks:n.tool_call_chunks,tool_calls:n.tool_calls,invalid_tool_calls:n.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(r);x(this,"type","ai");x(this,"tool_calls",[]);x(this,"invalid_tool_calls",[]);x(this,"tool_call_chunks",[]);x(this,"usage_metadata");this.tool_call_chunks=r.tool_call_chunks??this.tool_call_chunks,this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=r.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let r=SBe(this.response_metadata.model_provider);if(r)return r.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let r=this.content.filter(n=>n.type==="tool_call").map(n=>n.id);for(let n of this.tool_calls)n.id&&!r.includes(n.id)&&e.push({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let r={conten
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function wS(t){if(typeof t=="string")return new qs(t);if(xg(t))return t;if(Array.isArray(t)){let[e,r]=t;return CBe({type:e,content:r})}else if(eme(t)){let{role:e,...r}=t;return CBe({...r,type:e})}else return CBe(t)}function fl(t,e="Human",r="AI"){let n=[];for(let o of t){let i;if(o.type==="human")i=e;else if(o.type==="ai")i=r;else if(o.type==="system")i="System";else if(o.type==="tool")i="Tool";else if(o.type==="generic")i=o.role;else throw new Error(`Got unsupported message type: ${o.type}`);let a=o.name?`${o.name}, `:"",s=o.text,u=`${i}: ${a}${s}`;if(o.type==="ai"){let l=o;l.tool_calls&&l.tool_calls.length>0?u+=JSON.stringify(l.tool_calls):l.additional_kwargs&&"function_call"in l.additional_kwargs&&(u+=JSON.stringify(l.additional_kwargs.function_call))}n.push(u)}return n.join(`
`)}function Ndn(t){if(t.data!==void 0)return t;{let e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function VQ(t){let e=Ndn(t);switch(e.type){case"human":return new qs(e.data);case"ai":return new Pn(e.data);case"system":return new Od(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Iz(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Mh(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Td(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function Rxt(t){return t.map(VQ)}function Ixt(t){return t.map(e=>e.toDict())}function Nz(t){let e=t._getType();if(e==="human")return new rw({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new Er({...r})}else{if(e==="system")return new Rb({...t});if(e==="function")return new tw({...t});if(Td.isInstance(t))return new ew({...t});throw new Error("Unknown message type.")}}function ame(t){let e=t.reduce((o,i)=>{let a=o.findIndex(([s])=>"id"in i&&i.id&&"index"in i&&i.index!==void 0?i.id===s.id&&i.index===s.index:"id"in i&&i.id?i.id===s.id:"index"in i&&i.index!==void 0?i.index===s.index:!1);return a!==-1?o[a].push(i):o.push([i]),o},[]),r=[],n=[];for(let o of e){let i=null,a=o[0]?.name??"",s=o.map(c=>c.args||"").join("").trim(),u=s.length?s:"{}",l=o[0]?.id;try{if(i=Mz(u),!l||i===null||typeof i!="object"||Array.isArray(i))throw new Error("Malformed tool call chunk args.");r.push({name:a,args:i,id:l,type:"tool_call"})}catch{n.push({name:a,args:u,id:l,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:r,invalid_tool_calls:n}}var sme,UC=v(()=>{Oy();G6();DQ();Wpe();NQ();UQ();tme();zL();rme();BQ();vS();sme=t=>t()});function TBe(){return xBe===void 0&&(xBe={library:"langchain-js",runtime:lme()}),xBe}function Xr(t){try{return typeof process<"u"?process.env?.[t]:ume()?Deno?.env.get(t):void 0}catch{return}}var Ddn,Axt,Nxt,Dxt,ume,jxt,lme,xBe,au=v(()=>{Jo();Ddn={};$t(Ddn,{getEnv:()=>lme,getEnvironmentVariable:()=>Xr,getRuntimeEnvironment:()=>TBe,isBrowser:()=>Axt,isDeno:()=>ume,isJsDom:()=>Dxt,isNode:()=>jxt,isWebWorker:()=>Nxt});Axt=()=>typeof window<"u"&&typeof window.document<"u",Nxt=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Dxt=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),ume=()=>typeof Deno<"u",jxt=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!ume(),lme=()=>{let t;return Axt()?t="browser":jxt()?t="node":Nxt()?t="webworker":Dxt()?t="jsdom":ume()?t="deno":t="other",t}});var $xt,Lxt=v(()=>{$xt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function jdn(t){return typeof t=="string"&&$xt.test(t)}var Z6,Fxt=v(()=>{Lxt();Z6=jdn});function dme(t,e=0){return(Tg[t[e+0]]+Tg[t[e+1]]+Tg[t[e+2]]+Tg[t[e+3]]+"-"+Tg[t[e+4]]+Tg[t[e+5]]+"-"+Tg[t[e+6]]+Tg[t[e+7]]+"-"+Tg[t[e+8]]+Tg[t[e+9]]+"-"+Tg[t[e+10]]+Tg[t[e+11]]+Tg[t[e+12]]+Tg[t[e+13]]+Tg[t[e+14]]+Tg[t[e+15]]).toLowerCase()}var Tg,cme,OBe=v(()=>{Tg=[];for(cme=0;cme<256;++cme)Tg.push((cme+256).toString(16).slice(1))});function HQ(){if(!fme&&(fme=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!fme))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return fme($dn)}var fme,$dn,EBe=v(()=>{$dn=new Uint8Array(16)});var Ldn,PBe,kxt=v(()=>{Ldn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),PBe={randomUUID:Ldn}});function Fdn(t,e,r){if(PBe.randomUUID&&!e&&!t)return PBe.randomUUID();t=t||{};var n=t.random||(t.rng||HQ)();if(n[6]=n[6]
Context: ${e}`:""}`),Yme("[Unserializable]");ad("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=Qhn()),Hze(t,"",0,[],void 0,0,o);let a;try{nJ.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,tgn(r),n)}catch{return Yme("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Qme.length!==0;){let s=Qme.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return Yme(a)}}function Vze(t,e,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:t}),Qme.push([n,r,e,o])):nJ.push([e,r,t]):(n[r]=t,Qme.push([n,r,e]))}function Hze(t,e,r,n,o,i,a){i+=1;var s;if(typeof t=="object"&&t!==null){for(s=0;s<n.length;s++)if(n[s]===t){Vze(Zhn,t,e,o);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Vze(pPt,t,e,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Vze(pPt,t,e,o);return}if(n.push(t),Array.isArray(t))for(s=0;s<t.length;s++)Hze(t[s],s,s,n,t,i,a);else{t=mPt(t);var u=Object.keys(t);for(s=0;s<u.length;s++){var l=u[s];Hze(t[l],l,s,n,t,i,a)}}n.pop()}}function tgn(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(nJ.length>0)for(var n=0;n<nJ.length;n++){var o=nJ[n];if(o[1]===e&&o[0]===r){r=o[2],nJ.splice(n,1);break}}return t.call(this,e,r)}}var pPt,Zhn,Qme,nJ,Yhn,hPt=v(()=>{BN();pPt="[...]",Zhn={result:"[Circular]"},Qme=[],nJ=[],Yhn=new TextEncoder});function gPt(t,e,r){if(r)return t;let n=Mme(),o=e??QBe(),i=t.extra??{},a=i.metadata;return t.extra={...i,runtime:{...n,...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}:{},...a}},t}async function ogn(t){let e=[];for await(let r of t)e.push(r);return e}function ehe(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function yPt(t){return typeof t=="number"?Number(t.toFixed(4)):t}function _Pt(t){return"dataset_id"in t||"dataset_name"in t}var rgn,ngn,ign,agn,vPt,sgn,ugn,bPt,Wze,Fz,KBe=v(()=>{gme();iOt();sze();_Ot();vOt();BN();Pme();xme();yme();cPt();zze();JBe();UBe();hPt();rgn=t=>{let e=t?.toString()??ad("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},ngn=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};ign=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};agn=24*1024*1024,vPt=1024*1024*1024,sgn=1e4,ugn=100,bPt="https://api.smith.langchain.com",Wze=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??vPt}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),o=E_(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+o>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${o} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:o}),this.sizeBytes+=o,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],o=0;for(;o+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let i=this.items.shift();i&&(n.push(i),o+=i.size,this.sizeBytes-=i.size)}if(n.length===0&&this.items.length>0){let i=this.items.shift();n.push(i),o+=i.size,this.sizeBytes-=i.size}return[n.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>n.forEach(i=>i.itemPromiseResolve())]}},Fz=class t{get _fetch(){ret
2026-01-05 13:03:55 +08:00
=== LangSmith Server Configuration ===
`+JSON.stringify(r,null,2)+`
2026-02-24 07:55:02 +08:00
`),r}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 _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){let e=Ime(),r=nOt();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"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 u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:u,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let a=gPt(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let s=E_(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let u=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Ar(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let o=await Promise.all(e?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]),i=await Promise.all(r?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]);if(o.length>0&&i.length>0){let u=o.reduce((c,d)=>(d.id&&(c[d.id]=d),c),{}),l=[];for(let c of i)c.id!==void 0&&u[c.id]?u[c.id]={...u[c.id],...c}:l.push(c);o=Object.values(u),i=l}let a={post:o,patch:i};if(!a.post.length&&!a.patch.length)return;let s={post:[],patch:[]};for(let u of["post","patch"]){let l=u,c=a[l].reverse(),d=c.pop();for(;d!==void 0;)s[l].push(d),d=c.pop()}if(s.post.length>0||s.patch.length>0){let u=s.post.map(l=>l.id).concat(s.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(E_(s,`Ingesting runs with ids: ${u}`),n)}}async _postBatchIngestRuns(e,r){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await Ar(o,"batch create run",!0),o})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let o={},i=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(o[f.id]=f.attachments),delete f.attachments,i.push(f)}let a=[];for(let d of r??[])a.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&a.length>0){let d=i.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(let p of a)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);i=Object.values(d),a=f}if(i.length===0&&a.length===0)return;let l=[],c=[];for(let[d,f]of[["post",i],["patch",
2026-01-05 13:03:55 +08:00
`])),n.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
`,`Content-Type: ${a.payload.type}\r
\r
`])),n.push(a.payload),n.push(new Blob([`\r
`]));return n.push(new Blob([`--${r}--\r
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(i){let a=async s=>{typeof s=="string"?i.enqueue(n.encode(s)):i.enqueue(s)};for(let s of e){await a(`--${r}\r
`),await a(`Content-Disposition: form-data; name="${s.name}"\r
`),await a(`Content-Type: ${s.payload.type}\r
\r
`);let l=s.payload.stream().getReader();try{let c;for(;!(c=await l.read()).done;)i.enqueue(c.value)}finally{l.releaseLock()}await a(`\r
`)}await a(`--${r}--\r
2026-02-24 07:55:02 +08:00
`),i.close()}})}async _sendMultipartRequest(e,r,n){let o="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=()=>this._createNodeFetchBody(e,o),a=()=>this._createMultipartStream(e,o),s=async u=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let l=await u(),c={...this.headers,"Content-Type":`multipart/form-data; boundary=${o}`};n?.apiKey!==void 0&&(c["x-api-key"]=n.apiKey);let d=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(d=l.pipeThrough(new CompressionStream("gzip")),c["Content-Encoding"]="gzip");let f=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:c,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Ar(f,"Failed to send multipart request",!0),f});try{let u,l=!1;jTt()&&!this.multipartStreamingDisabled&&YBe()!=="bun"?(l=!0,u=await s(a)):u=await s(i),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==bPt&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,u=await s(i))}catch(u){if(Bze(u))throw u;console.warn(`${u.message.trim()}
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
Context: ${r}`)}}async updateRun(e,r,n){Ao(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let o={...r,id:e};if(!this._filterForSampling([o],!0).length)return;if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){let s=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&o.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(i["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(i["x-tenant-id"]=n.workspaceId);let a=E_(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let s=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Ar(s,"update run",!0),s})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Ao(e);let n=await this._get(`/runs/${e}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let o;r.session_id?o=r.session_id:n?.projectName?o=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?o=n?.projectId:o=(await this.readProject({projectName:ad("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${r.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 r=await ogn(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},o={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let i of r){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 n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),o[i.id]=i)}e.child_runs=n[e.id]||[];for(let i in n)i!==e.id&&(o[i].child_runs=n[i]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:o,traceId:i,referenceExampleId:a,startTime:s,executionOrder:u,isRoot:l,runType:c,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:y,limit:g,select:b,order:_}=e,w=[];if(r&&(w=Array.isArray(r)?r:[r]),n){let P=Array.isArray(n)?n:[n],R=await Promise.all(P.map(I=>this.readProject({projectName:I}).then(N=>N.id)));w.push(...R)}let T=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],O={session:w.length?w:null,run_type:c,reference_example:a,query:p,filter:m,trace_filter:h,tree_filter:y,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:b||T,is_root:l,order:_};O.select.includes("child_run_ids")&&$z("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let E=0;for await(let P of this._getCursorPaginatedList("/runs/query",O))if(g){if(E>=g)break;if(P.length+E>g){yield*P.slice(0,g-E);break}E+=P.length,yield*P}else yield*P}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:o,filter:i,startTime:a,endTime:s,limit:u,offset:l}=e,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:o,filter:i,start_time:a?a.toISOString():null,end_time:s?s.toISOString():null,limit:Number(u)||100},f=Number(l)||0,p="/runs/group",m=`${this.apiUrl}${p}`;for(;;){let h={...d,offset:f},y
2026-01-05 13:03:55 +08:00
Status: ${i.status}
Message: ${Array.isArray(a.detail)?a.detail.join(`
2026-02-24 07:55:02 +08:00
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(s=>({...s,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:a=null}){let s=o?"?upsert=true":"",u=`${this.apiUrl}/sessions${s}`,l=i||{};n&&(l.metadata=n);let c={name:e,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);let d=JSON.stringify(c);return await(await this.caller.call(async()=>{let m=await this._fetch(u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await Ar(m,"create project"),m})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:o=null,projectExtra:i=null,endTime:a=null}){let s=`${this.apiUrl}/sessions/${e}`,u=i;o&&(u={...u||{},metadata:o});let l=JSON.stringify({name:r,extra:u,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Ar(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",o=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Ao(e),n+=`/${e}`;else if(r!==void 0)o.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Ar(a,"has project"),a});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Ao(e),o+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(o,i),s;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);s=a[0]}else s=a;return s}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,includeStats:a,datasetVersion:s,referenceFree:u,metadata:l}={}){let c=new URLSearchParams;if(e!==void 0)for(let d of e)c.append("id",d);if(r!==void 0&&c.append("name",r),n!==void 0&&c.append("name_contains",n),o!==void 0)c.append("reference_dataset",o);else if(i!==void 0){let d=await this.readDataset({datasetName:i});c.append("reference_dataset",d.id)}a!==void 0&&c.append("include_stats",a.toString()),s!==void 0&&c.append("dataset_version",s),u!==void 0&&c.append("reference_free",u.toString()),l!==void 0&&c.append("metadata",JSON.stringify(l));for await(let d of this._getPaginated("/sessions",c))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectNa
`).map(s=>JSON.parse(s))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:o,datasetNameContains:i,metadata:a}={}){let s="/datasets",u=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let l of n)u.append("id",l);o!==void 0&&u.append("name",o),i!==void 0&&u.append("name_contains",i),a!==void 0&&u.append("metadata",JSON.stringify(a));for await(let l of this._getPaginated(s,u))yield*l}async updateDataset(e){let{datasetId:r,datasetName:n,...o}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;Ao(i);let a=JSON.stringify(o);return await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Ar(u,"update dataset"),u})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:o,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;Ao(a);let s=JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i});await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Ar(u,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",o=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(o=(await this.readDataset({datasetName:r})).id),o!==void 0)Ao(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Ar(i,`delete ${n}`,!0),i})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let o=e;if(!o&&!r)throw new Error("Must provide either datasetName or datasetId");if(o&&r)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:r})).id),Ao(o);let a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Ar(u,"index dataset"),u})).json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),Ao(r);let a=JSON.stringify(i);return(await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await Ar(l,"fetch similar examples"),l})).json()).examples}async createExample(e,r,n){if(_Pt(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let o=r?n?.datasetId:e.dataset_id,i=r?n?.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 a=(r?n?.createdAt:e.created_at)||new Date,s;_Pt(e)?s=e:s={inputs:e,outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let u=await this._uploadExamplesMultipart(o,[s]);return await this.readExample(u.example_ids?.[0]??jz())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let b=e,_=b[0].dataset_id,w=b[0].dat
2026-01-05 13:03:55 +08:00
Current tenant: ${n.tenant_handle}
2026-02-24 07:55:02 +08:00
Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Ar(o,"get latest commit hash"),o})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,o,i]=VN(e),a=JSON.stringify({like:r});return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Ar(u,`${r?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){let[r,n,o]=VN(e);if(await this._currentTenantIsOwner(r)){let i=await this._getSettings();return o!=="latest"?`${this.getHostUrl()}/prompts/${n}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}else return o!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}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){for await(let r of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(e){let r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(let n of this._getPaginated("/repos",r,o=>o.repos))yield*n}async getPrompt(e){let[r,n,o]=VN(e),a=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return s?.status===404?null:(await Ar(s,"get prompt"),s)}))?.json();return a?.repo?a.repo:null}async createPrompt(e,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
2026-01-05 13:03:55 +08:00
creating a LangChain Hub handle.
You can add a handle by creating a public prompt at:
2026-02-24 07:55:02 +08:00
https://smith.langchain.com/prompts`);let[o,i,a]=VN(e);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("create a prompt",o);let s={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},u=JSON.stringify(s),l=await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await Ar(d,"create prompt"),d}),{repo:c}=await l.json();return c}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[o,i,a]=VN(e),s=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${o}/${i}`):n?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(r)),parent_commit:s},l=JSON.stringify(u),d=await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Ar(f,"create commit"),f})).json();return this._getPromptUrl(`${o}/${i}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){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 n=new FormData;for(let a of r){let s=a.id,u={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=E_(u,`Serializing body for example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=E_(a.inputs,`Serializing inputs for example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=E_(a.outputs,`Serializing outputs whle updating example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.outputs`,f)}if(a.attachments)for(let[d,f]of Object.entries(a.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}`});n.append(`${s}.attachment.${d}`,h)}if(a.attachments_operations){let d=E_(a.attachments_operations,`Serializing attachments while updating example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.attachments_operations`,f)}}let o=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${o}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await Ar(a,"update examples"),a})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){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 n=new FormData;for(let i of r){let a=(i.id??jz()).toString(),s={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}},u=E_(s,`Serializing body for uploaded example with id: ${a}`),l=new Blob([u],{type:"application/json"});if(n.append(a,l),i.inputs){let c=E_(i.inputs,`Serializing inputs for uploaded example with id: ${a}`),d=new Blob([c],{type:"application/json"});n.append(`${a}.inputs`,d)}if(i.outputs){let c=E_(i.outputs,`Serializing outputs for uploaded example with id: ${a}`),d=new Blob([c],{type:"application/json"});n.append(`${a}.outputs`,d)}if(i.attachme
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,r){e.child_runs.push(r)}_addRunToRunMap(e){let{dottedOrder:r,microsecondPrecisionDatestring:n}=Gze(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,r].join("."),o._serialized_start_time=n)):o.parent_run_id=void 0:(o.trace_id=o.id,o.dotted_order=r,o._serialized_start_time=n),this.usesRunTreeMap){let a=Zze(o,i);a!==void 0&&this.runTreeMap.set(o.id,a)}else this.runMap.set(o.id,o);return o}async _endTrace(e){let r=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);r?r.child_execution_order=Math.max(r.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 r=e!==void 0&&this.getRunById(e);return r?r.child_execution_order+1:1}_createRunForLLMStart(e,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{prompts:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,r,n,o,i,a,s,u){let l=this.getRunById(n)??this._createRunForLLMStart(e,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(e,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{messages:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,r,n,o,i,a,s,u){let l=this.getRunById(n)??this._createRunForChatModelStart(e,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(e,r,n,o,i){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,r,n,o,i){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,r,n,o,i,a,s,u,l){let c=this._getExecutionOrder(o),d=Date.now(),f={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:r,execution_order:c,child_execution_order:c,run_type:s??"chain",child_runs:[],extra:a?{...l,metadata:a}:{...l},tags:i||[]};return this._addRunToRunMap(f)}async handleChainStart(e,r,n,o,i,a,s,u){let l=this.getRunById(n)??this._createRunForChainStart(e,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(e,r,n,o,i){let a=this.getRunById(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=Xze(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Xze(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,r,n,o,i){let a=this.getRunById(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Xze(i.inputs,"input")),await this.onChainError?.(a),await
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function she(t){return typeof t=="function"&&"langsmith:traceable"in t}var r4e,t4e,Sgn,n4e,Cgn,NMi,LPt=v(()=>{r4e=class{getStore(){}run(e,r){return r()}},t4e=Symbol.for("ls:tracing_async_local_storage"),Sgn=new r4e,n4e=class{getInstance(){return globalThis[t4e]??Sgn}initializeGlobalInstance(e){globalThis[t4e]===void 0&&(globalThis[t4e]=e)}},Cgn=new n4e;NMi=Symbol.for("langsmith:traceable:root")});var o4e=v(()=>{LPt()});function Tgn(t){let e;for(let r of t)for(let n of r)Pn.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=X6(e,n.message.usage_metadata));return e}var xgn,lee,kPt=v(()=>{Jo();ime();vS();Uz();e4e();o4e();nhe();ihe();xgn={};$t(xgn,{LangChainTracer:()=>lee});lee=class FPt extends HC{constructor(r={}){super(r);x(this,"name","langchain_tracer");x(this,"projectName");x(this,"exampleId");x(this,"client");x(this,"replicas");x(this,"usesRunTreeMap",!0);let{exampleId:n,projectName:o,client:i,replicas:a}=r;this.projectName=o??ZQ(),this.replicas=a,this.exampleId=n,this.client=i??ahe();let s=FPt.getTraceableRunTree();s&&this.updateFromRunTree(s)}async persistRun(r){}async onRunCreate(r){r.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(r.id)?.postRun()}async onRunUpdate(r){let n=this.getRunTreeWithTracingConfig(r.id);r.extra?.lc_defers_inputs?await n?.postRun():await n?.patchRun()}onLLMEnd(r){let n=r.outputs;if(n?.generations){let o=Tgn(n.generations);if(o!==void 0){r.extra=r.extra??{};let i=r.extra.metadata??{};i.usage_metadata=o,r.extra.metadata=i}}}getRun(r){return this.runTreeMap.get(r)}updateFromRunTree(r){this.runTreeMap.set(r.id,r);let n=r,o=new Set;for(;n.parent_run&&!(o.has(n.id)||(o.add(n.id),!n.parent_run));)n=n.parent_run;o.clear();let i=[n];for(;i.length>0;){let a=i.shift();!a||o.has(a.id)||(o.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&i.push(...a.child_runs))}this.client=r.client??this.client,this.replicas=r.replicas??this.replicas,this.projectName=r.project_name??this.projectName,this.exampleId=r.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(r){let n=this.runTreeMap.get(r);if(n)return new VC({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return $Pt(!0)}catch{return}}}});var UPt=S((JMi,lhe)=>{"use strict";var Ogn=pze(),uhe=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},qPt=(t,e,r)=>new Promise((n,o)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let i=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(u){o(u)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,s=r instanceof Error?r:new uhe(a);typeof t.cancel=="function"&&t.cancel(),o(s)},e);Ogn(t.then(n,o),()=>{clearTimeout(i)})});lhe.exports=qPt;lhe.exports.default=qPt;lhe.exports.TimeoutError=uhe});var BPt=S(i4e=>{"use strict";Object.defineProperty(i4e,"__esModule",{value:!0});function Egn(t,e,r){let n=0,o=t.length;for(;o>0;){let i=o/2|0,a=n+i;r(t[a],e)<=0?(n=++a,o-=i+1):o=i}return n}i4e.default=Egn});var zPt=S(s4e=>{"use strict";Object.defineProperty(s4e,"__esModule",{value:!0});var Pgn=BPt(),a4e=class{constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let o=Pgn.default(this._queue,n,(i,a)=>a.priority-i.priority);this._queue.splice(o,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};s4e.default=a4e});var c4e=S(l4e=>{"use strict";Object.defineProperty(l4e,"__esModule",{value:!0});var Mgn=fze(),VPt=UPt(),Rgn=zPt(),che=()=>{},Ign=new VPt.TimeoutError,u4e=class extends Mgn{constructor(e){var r,n,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._r
`)}var Bgn,_he,vhe=v(()=>{Bgn=Object.prototype.hasOwnProperty;_he=class extends Error{constructor(t,e,r,n,o){super(rMt(t,{name:e,index:r,operation:n,tree:o})),this.name=e,this.index=r,this.operation=n,this.tree=o,Object.setPrototypeOf(this,new.target.prototype),this.message=rMt(t,{name:e,index:r,operation:n,tree:o})}}});function y4e(t){return Object.getOwnPropertyNames(Object.prototype).includes(t)}function whe(t,e){if(e=="")return t;var r={op:"_get",path:e};return Wz(t,r),r.value}function Wz(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):She(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=whe(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=fee(t,e.value),a.test===!1)throw new jc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new jc("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=Fb(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=She;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=bhe(f)),o&&(f=="__proto__"||f=="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(r&&d===void 0&&(u[f]===void 0?d=s.slice(0,l).join("/"):l==c-1&&(d=e.path),d!==void 0&&p(e,0,t,d)),l++,Array.isArray(u)){if(f==="-")f=u.length;else{if(r&&!yhe(f))throw new jc("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);yhe(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new jc("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let m=Vgn[e.op].call(e,u,f,t);if(m.test===!1)throw new jc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=aJ[e.op].call(e,u,f,t);if(m.test===!1)throw new jc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new jc("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function GL(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new jc("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Fb(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=Wz(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function Hgn(t,e,r){let n=Wz(t,e);if(n.test===!1)throw new jc("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function She(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new jc("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(aJ[t.op]){if(typeof t.path!="string")throw new jc("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new jc('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new jc("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new jc("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&mhe(t.value))throw new jc("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var o=t.path.
`)}var _Mt,Tee,dJ,k4e=v(()=>{uJ();zn();_Mt=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,P4e,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Tee=xe("$ZodError",_Mt),dJ=xe("$ZodError",_Mt,{Parent:Error})});var Rhe,aO,Ihe,Xz,Ahe,q4e,Nhe,U4e,Dhe=v(()=>{uJ();k4e();zn();Rhe=t=>(e,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new iO;if(a.issues.length){let s=new(o?.Err??t)(a.issues.map(u=>ow(u,i,Pd())));throw Mhe(s,o?.callee),s}return a.value},aO=Rhe(dJ),Ihe=t=>async(e,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(o?.Err??t)(a.issues.map(u=>ow(u,i,Pd())));throw Mhe(s,o?.callee),s}return a.value},Xz=Ihe(dJ),Ahe=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new iO;return i.issues.length?{success:!1,error:new(t??Tee)(i.issues.map(a=>ow(a,o,Pd())))}:{success:!0,data:i.value}},q4e=Ahe(dJ),Nhe=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(a=>ow(a,o,Pd())))}:{success:!0,data:i.value}},U4e=Nhe(dJ)});var Yz={};En(Yz,{_emoji:()=>wMt,base64:()=>r2e,base64url:()=>jhe,bigint:()=>l2e,boolean:()=>f2e,browserEmail:()=>Iyn,cidrv4:()=>e2e,cidrv6:()=>t2e,cuid:()=>B4e,cuid2:()=>z4e,date:()=>i2e,datetime:()=>s2e,domain:()=>Ayn,duration:()=>K4e,e164:()=>o2e,email:()=>X4e,emoji:()=>Z4e,extendedDuration:()=>xyn,guid:()=>G4e,hostname:()=>n2e,html5Email:()=>Pyn,integer:()=>c2e,ipv4:()=>Y4e,ipv6:()=>Q4e,ksuid:()=>W4e,lowercase:()=>h2e,nanoid:()=>J4e,null:()=>p2e,number:()=>d2e,rfc5322Email:()=>Myn,string:()=>u2e,time:()=>a2e,ulid:()=>V4e,undefined:()=>m2e,unicodeEmail:()=>Ryn,uppercase:()=>g2e,uuid:()=>Zz,uuid4:()=>Tyn,uuid6:()=>Oyn,uuid7:()=>Eyn,xid:()=>H4e});function Z4e(){return new RegExp(wMt,"u")}function CMt(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 a2e(t){return new RegExp(`^${CMt(t)}$`)}function s2e(t){let e=CMt({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${SMt}T(?:${n})$`)}var B4e,z4e,V4e,H4e,W4e,J4e,K4e,xyn,G4e,Zz,Tyn,Oyn,Eyn,X4e,Pyn,Myn,Ryn,Iyn,wMt,Y4e,Q4e,e2e,t2e,r2e,jhe,n2e,Ayn,o2e,SMt,i2e,u2e,l2e,c2e,d2e,f2e,p2e,m2e,h2e,g2e,$he=v(()=>{B4e=/^[cC][^\s-]{8,}$/,z4e=/^[0-9a-z]+$/,V4e=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,H4e=/^[0-9a-vA-V]{20}$/,W4e=/^[A-Za-z0-9]{27}$/,J4e=/^[a-zA-Z0-9_-]{21}$/,K4e=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xyn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,G4e=/^([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})$/,Zz=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)$/,Tyn=Zz(4),Oyn=Zz(6),Eyn=Zz(7),X4e=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Pyn=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Myn=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0
2026-01-05 13:03:55 +08:00
`).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),i=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...r,o.join(`
2026-02-24 07:55:02 +08:00
`))}}});var $2e,L2e=v(()=>{$2e={major:4,minor:0,patch:0}});function oVe(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function FMt(t){if(!jhe.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return oVe(r)}function kMt(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function EMt(t,e,r){t.issues.length&&e.issues.push(...M_(r,t.issues)),e.value[r]=t.value}function qhe(t,e,r){t.issues.length&&e.issues.push(...M_(r,t.issues)),e.value[r]=t.value}function PMt(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...M_(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function MMt(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(i=>ow(i,n,Pd())))}),e}function F2e(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(cJ(t)&&cJ(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(let i of n){let a=F2e(t[i],e[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],i=e[n],a=F2e(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function RMt(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Gz(t))return t;let n=F2e(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function Uhe(t,e,r){t.issues.length&&e.issues.push(...M_(r,t.issues)),e.value[r]=t.value}function IMt(t,e,r,n,o,i,a){t.issues.length&&(See.has(typeof n)?r.issues.push(...M_(n,t.issues)):r.issues.push({origin:"map",code:"invalid_key",input:o,inst:i,issues:t.issues.map(s=>ow(s,a,Pd()))})),e.issues.length&&(See.has(typeof n)?r.issues.push(...M_(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:e.issues.map(s=>ow(s,a,Pd()))})),r.value.set(t.value,e.value)}function AMt(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function NMt(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function DMt(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 jMt(t,e,r){return Gz(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function $Mt(t){return t.value=Object.freeze(t.value),t}function LMt(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push($4e(o))}}var uo,Qz,Ru,k2e,q2e,U2e,B2e,z2e,V2e,H2e,W2e,J2e,K2e,G2e,X2e,Z2e,Y2e,Q2e,eVe,tVe,rVe,nVe,iVe,aVe,sVe,uVe,lVe,Bhe,cVe,Mee,zhe,dVe,fVe,pVe,mVe,hVe,ZL,Ree,gVe,yVe,Iee,bVe,Vhe,_Ve,vVe,e4,wVe,SVe,CVe,xVe,TVe,OVe,Aee,pJ,EVe,PVe,MVe,RVe,IVe,AVe,NVe,Nee,DVe,jVe,$Ve,LVe,FVe,Dee=v(()=>{khe();uJ();j2e();Dhe();$he();zn();L2e();zn();uo=xe("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=$2e;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let i of o._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,s)=>{let u=Gz(i),l;for(let c of a){if(c._zod.def.when){if(!c._zod.def.when(i))continue}else if(u)continue;let d=i.issues.length,f=c._zod.check(i);if(f instanceof Promise&&s?.async===!1)throw new iO;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{awai
2026-01-05 13:03:55 +08:00
if (${_}.issues.length) {
if (input[${w}] === undefined) {
if (${w} in input) {
newResult[${w}] = undefined;
}
} else {
payload.issues = payload.issues.concat(
${_}.issues.map((iss) => ({
...iss,
path: iss.path ? [${w}, ...iss.path] : [${w}],
}))
);
}
} else if (${_}.value === undefined) {
if (${w} in input) newResult[${w}] = undefined;
} else {
newResult[${w}] = ${_}.value;
}
`)}else{let _=h[b];f.write(`const ${_} = ${m(b)};`),f.write(`
if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
2026-02-24 07:55:02 +08:00
path: iss.path ? [${Kz(b)}, ...iss.path] : [${Kz(b)}]
})));`),f.write(`newResult[${Kz(b)}] = ${_}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let g=f.compile();return(b,_)=>g(d,b,_)},o,i=lJ,a=!yee.jitless,u=a&&I4e.value,l=e.catchall,c;t._zod.parse=(d,f)=>{c??(c=r.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let m=[];if(a&&u&&f?.async===!1&&f.jitless!==!0)o||(o=n(e.shape)),d=o(d,f);else{d.value={};let _=c.shape;for(let w of c.keys){let T=_[w],O=T._zod.run({value:p[w],issues:[]},f),E=T._zod.optin==="optional"&&T._zod.optout==="optional";O instanceof Promise?m.push(O.then(P=>E?PMt(P,d,w,p):qhe(P,d,w))):E?PMt(O,d,w,p):qhe(O,d,w)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],y=c.keySet,g=l._zod,b=g.def.type;for(let _ of Object.keys(p)){if(y.has(_))continue;if(b==="never"){h.push(_);continue}let w=g.run({value:p[_],issues:[]},f);w instanceof Promise?m.push(w.then(T=>qhe(T,d,_))):qhe(w,d,_)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:t}),m.length?Promise.all(m).then(()=>d):d}});Vhe=xe("$ZodUnion",(t,e)=>{uo.init(t,e),Us(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Us(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Us(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Us(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>wee(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,i=[];for(let a of e.options){let s=a._zod.run({value:r.value,issues:[]},n);if(s instanceof Promise)i.push(s),o=!0;else{if(s.issues.length===0)return s;i.push(s)}}return o?Promise.all(i).then(a=>MMt(a,r,t,n)):MMt(i,r,t,n)}}),_Ve=xe("$ZodDiscriminatedUnion",(t,e)=>{Vhe.init(t,e);let r=t._zod.parse;Us(t._zod,"propValues",()=>{let o={};for(let i of e.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[s,u]of Object.entries(a)){o[s]||(o[s]=new Set);for(let l of u)o[s].add(l)}}return o});let n=vee(()=>{let o=e.options,i=new Map;for(let a of o){let s=a._zod.propValues[e.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let u of s){if(i.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);i.set(u,a)}}return i});t._zod.parse=(o,i)=>{let a=o.value;if(!lJ(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),o;let s=n.value.get(a?.[e.discriminator]);return s?s._zod.run(o,i):e.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),o)}}),vVe=xe("$ZodIntersection",(t,e)=>{uo.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,i=e.left._zod.run({value:o,issues:[]},n),a=e.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([u,l])=>RMt(r,u,l)):RMt(r,i,a)}});e4=xe("$ZodTuple",(t,e)=>{uo.init(t,e);let r=e.items,n=r.length-[...r].reverse().findIndex(o=>o._zod.optin!=="optional");t._zod.parse=(o,i)=>{let a=o.value;if(!Array.isArray(a))return o.issues.push({input:a,inst:t,expected:"tuple",code:"invalid_type"}),o;o.value=[];let s=[];if(!e.rest){let l=a.length>r.length,c=a.length<n-1;if(l||c)return o.issues.push({input:a,inst:t,origin:"array",...l?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length}}),o}let u=-1;for(let l of r){if(u++,u>=a.length&&u>=n)continue;let c=l._zod.run({value:a[u],issues:[]},i);c instanceof Promise?s.push(c.then(d=>Uhe(d,o,u))):Uhe(c,o,u)}if(e.rest){let l=a.slice(r.length);for(let c of l){u++;let d=e.rest._zod.run({value:c,issues:[]},i);d instanceof Promise?s.push(d.then(f=>Uhe(f,o,u))):Uhe(d,o,u)}}return s.length?Promise.all(s).then(()=>o):o}});wVe=xe("$ZodRecord",(t,e)=>{uo.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!cJ(o))return r.issues.p
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let c of this.seen.entries()){let d=c[1];if(e===c[0]){a(c);continue}if(n.external){let p=n.external.registry.get(c[0])?.id;if(e!==c[0]&&p){a(c);continue}}if(this.metadataRegistry.get(c[0])?.id){a(c);continue}if(d.cycle){a(c);continue}if(d.count>1&&n.reused==="ref"){a(c);continue}}let s=(c,d)=>{let f=this.seen.get(c),p=f.def??f.schema,m={...p};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){s(h,d);let y=this.seen.get(h).schema;y.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(y)):(Object.assign(p,y),Object.assign(p,m))}f.isParent||this.override({zodSchema:c,jsonSchema:p,path:f.path??[]})};for(let c of[...this.seen.entries()].reverse())s(c[0],{target:this.target});let u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let c=n.external.registry.get(e)?.id;if(!c)throw new Error("Schema is missing an `id` property");u.$id=n.external.uri(c)}Object.assign(u,o.def);let l=n.external?.defs??{};for(let c of this.seen.entries()){let d=c[1];d.def&&d.defId&&(l[d.defId]=d.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?u.$defs=l:u.definitions=l);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}});var pIt={};var mIt=v(()=>{});var YN={};En(YN,{$ZodAny:()=>hVe,$ZodArray:()=>Iee,$ZodAsyncError:()=>iO,$ZodBase64:()=>iVe,$ZodBase64URL:()=>aVe,$ZodBigInt:()=>zhe,$ZodBigIntFormat:()=>dVe,$ZodBoolean:()=>Mee,$ZodCIDRv4:()=>rVe,$ZodCIDRv6:()=>nVe,$ZodCUID:()=>H2e,$ZodCUID2:()=>W2e,$ZodCatch:()=>AVe,$ZodCheck:()=>gc,$ZodCheckBigIntFormat:()=>_2e,$ZodCheckEndsWith:()=>I2e,$ZodCheckGreaterThan:()=>Fhe,$ZodCheckIncludes:()=>M2e,$ZodCheckLengthEquals:()=>T2e,$ZodCheckLessThan:()=>Lhe,$ZodCheckLowerCase:()=>E2e,$ZodCheckMaxLength:()=>C2e,$ZodCheckMaxSize:()=>v2e,$ZodCheckMimeType:()=>N2e,$ZodCheckMinLength:()=>x2e,$ZodCheckMinSize:()=>w2e,$ZodCheckMultipleOf:()=>y2e,$ZodCheckNumberFormat:()=>b2e,$ZodCheckOverwrite:()=>D2e,$ZodCheckProperty:()=>A2e,$ZodCheckRegex:()=>O2e,$ZodCheckSizeEquals:()=>S2e,$ZodCheckStartsWith:()=>R2e,$ZodCheckStringFormat:()=>fJ,$ZodCheckUpperCase:()=>P2e,$ZodCustom:()=>FVe,$ZodCustomStringFormat:()=>lVe,$ZodDate:()=>yVe,$ZodDefault:()=>PVe,$ZodDiscriminatedUnion:()=>_Ve,$ZodE164:()=>sVe,$ZodEmail:()=>U2e,$ZodEmoji:()=>z2e,$ZodEnum:()=>xVe,$ZodError:()=>Tee,$ZodFile:()=>OVe,$ZodFunction:()=>mge,$ZodGUID:()=>k2e,$ZodIPv4:()=>eVe,$ZodIPv6:()=>tVe,$ZodISODate:()=>Z2e,$ZodISODateTime:()=>X2e,$ZodISODuration:()=>Q2e,$ZodISOTime:()=>Y2e,$ZodIntersection:()=>vVe,$ZodJWT:()=>uVe,$ZodKSUID:()=>G2e,$ZodLazy:()=>LVe,$ZodLiteral:()=>TVe,$ZodMap:()=>SVe,$ZodNaN:()=>NVe,$ZodNanoID:()=>V2e,$ZodNever:()=>Ree,$ZodNonOptional:()=>RVe,$ZodNull:()=>mVe,$ZodNullable:()=>EVe,$ZodNumber:()=>Bhe,$ZodNumberFormat:()=>cVe,$ZodObject:()=>bVe,$ZodOptional:()=>pJ,$ZodPipe:()=>Nee,$ZodPrefault:()=>MVe,$ZodPromise:()=>$Ve,$ZodReadonly:()=>DVe,$ZodRealError:()=>dJ,$ZodRecord:()=>wVe,$ZodRegistry:()=>mJ,$ZodSet:()=>CVe,$ZodString:()=>Qz,$ZodStringFormat:()=>Ru,$ZodSuccess:()=>IVe,$ZodSymbol:()=>fVe,$ZodTemplateLiteral:()=>jVe,$ZodTransform:()=>Aee,$ZodTuple:()=>e4,$ZodType:()=>uo,$ZodULID:()=>J2e,$ZodURL:()=>B2e,$ZodUUID:()=>q2e,$ZodUndefined:()=>pVe,$ZodUnion:()=>Vhe,$ZodUnknown:()=>ZL,$ZodVoid:()=>gVe,$ZodXID:()=>K2e,$brand:()=>T4e,$constructor:()=>xe,$input:()=>BVe,$output:()=>UVe,Doc:()=>Pee,JSONSchema:()=>pIt,JSONSchemaGenerator:()=>Zee,NEVER:()=>x4e,TimePrecision:()=>WVe,_any:()=>pHe,_array:()=>Xee,_base64:()=>cge,_base64url:()=>dge,_bigint:()=>aHe,_boolean:()=>oHe,_catch:()=>$bn,_cidrv4:()=>uge,_cidrv6:()=>lge,_coercedBigint:()=>sHe,_coercedBoolean:()=>iHe,_coercedDate:()=>gHe,_coercedNumber:()=>YVe,_coercedString:()=>HVe,_cuid:()=>tge,_cuid2:()=>rge,_custom:()=>THe,_date:()=>hHe,_default:()=>Nbn,_discriminatedUnion:()=>Sbn,_e164:()=>fge,_email:()=>Jhe,_emoji:()=>Qhe,_endsWith:()=>Vee,_enum:()
`;return e}function TIt(t,e,r){let{firstNode:n,lastNode:o,nodeColors:i,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:u=9}=r??{},l=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%
2026-01-05 13:03:55 +08:00
graph TD;
`:`graph TD;
2026-02-24 07:55:02 +08:00
`;if(a){let m="default",h={[m]:"{0}({1})"};n!==void 0&&(h[n]="{0}([{1}]):::first"),o!==void 0&&(h[o]="{0}([{1}]):::last");for(let[y,g]of Object.entries(t)){let b=g.name.split(":").pop()??"",w=Vbn.some(O=>b.startsWith(O)&&b.endsWith(O))?`<p>${b}</p>`:b;Object.keys(g.metadata??{}).length&&(w+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([O,E])=>`${O} = ${E}`).join(`
`)}</em></small>`);let T=(h[y]??h[m]).replace("{0}",jHe(y)).replace("{1}",w);l+=` ${T}
2026-01-21 08:46:13 +08:00
`}}let c={};for(let m of e){let h=m.source.split(":"),y=m.target.split(":"),g=h.filter((b,_)=>b===y[_]).join(":");c[g]||(c[g]=[]),c[g].push(m)}let d=new Set;function f(m){return[...m].sort((h,y)=>h.split(":").length-y.split(":").length)}function p(m,h){let y=m.length===1&&m[0].source===m[0].target;if(h&&!y){let b=h.split(":").pop();if(d.has(h))throw new Error(`Found duplicate subgraph '${b}' 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),l+=` subgraph ${b}
2026-02-24 07:55:02 +08:00
`}let g=f(Object.keys(c).filter(b=>b.startsWith(`${h}:`)&&b!==h&&b.split(":").length===h.split(":").length+1));for(let b of g)p(c[b],b);for(let b of m){let{source:_,target:w,data:T,conditional:O}=b,E="";if(T!==void 0){let P=T,R=P.split(" ");R.length>u&&(P=Array.from({length:Math.ceil(R.length/u)},(I,N)=>R.slice(N*u,(N+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),E=O?` -. &nbsp;${P}&nbsp; .-> `:` -- &nbsp;${P}&nbsp; --> `}else E=O?" -.-> ":" --> ";l+=` ${jHe(_)}${E}${jHe(w)};
2026-01-21 08:46:13 +08:00
`}h&&!y&&(l+=` end
2026-02-24 07:55:02 +08:00
`)}p(c[""]??[],"");for(let m in c)!m.includes(":")&&m!==""&&p(c[m],m);return a&&(l+=Hbn(i??{})),l}async function OIt(t,e){let r=e?.backgroundColor??"white",n=e?.imageType??"png",o=bMt(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let i=`https://mermaid.ink/img/${o}?bgColor=${r}&type=${n}`,a=await fetch(i);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join(`
`));return await a.blob()}var Vbn,EIt=v(()=>{Phe();Vbn=["*","_","`"]});var MIt,PIt,RIt,vge=v(()=>{MIt=Symbol("Let zodToJsonSchema decide on which parser to use"),PIt={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"},RIt=t=>typeof t=="string"?{...PIt,name:t}:{...PIt,...t}});var IIt,$He=v(()=>{vge();IIt=t=>{let e=RIt(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});var wge,Sge=v(()=>{wge=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function Ul(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?wge(e,t.currentPath):e.join("/")}}var RS=v(()=>{Sge()});function LHe(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Hi(t,e,r,n,o){t[e]=r,LHe(t,e,n,o)}var oF=v(()=>{});var Ai,FHe,cr,sO,Qee=v(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),a={};for(let s of i)a[s]=o[s];return t.objectValues(a)},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 a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},t.find=(o,i)=>{for(let a of o)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(Ai||(Ai={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(FHe||(FHe={}));cr=Ai.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sO=t=>{switch(typeof t){case"undefined":return cr.undefined;case"string":return cr.string;case"number":return Number.isNaN(t)?cr.nan:cr.number;case"boolean":return cr.boolean;case"function":return cr.function;case"bigint":return cr.bigint;case"symbol":return cr.symbol;case"object":return Array.isArray(t)?cr.array:t===null?cr.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?cr.promise:typeof Map<"u"&&t instanceof Map?cr.map:typeof Set<"u"&&t instanceof Set?cr.set:typeof Date<"u"&&t instanceof Date?cr.date:cr.object;default:return cr.unknown}}});var it,Wbn,I_,Cge=v(()=>{Qee();it=Ai.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"]),Wbn=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),I_=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issue
2026-01-05 13:03:55 +08:00
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
`:`[${n[u]}\r
2026-02-24 07:55:02 +08:00
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!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 e3e,JC,ovn,Nge=v(()=>{oF();JC={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:()=>(e3e===void 0&&(e3e=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),e3e),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-_]*$/};ovn=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Dge(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===Ae.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:kn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ul(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:kn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Ae.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Age(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Ae.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Ae.ZodBranded&&t.keyType._def.type._def.typeName===Ae.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Rge(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var jge=v(()=>{RS();Ige();Nge();Md();cO()});function rAt(t,e){if(e.mapStrategy==="record")return Dge(t,e);let r=kn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ul(e),n=kn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ul(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var r3e=v(()=>{RS();jge();Md()});function nAt(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":
2026-01-05 13:03:55 +08:00
Known schemas:
- ${Object.keys(n).join(`
2026-02-24 07:55:02 +08:00
- `)}`,new Error(Ue)}let ht=`${s}/$ref`,$e=Ku(t,ze,r,n,o,i,a,ht,u);if($e.valid||je.push({instanceLocation:a,keyword:"$ref",keywordLocation:ht,error:"A subschema had errors."},...$e.errors),r==="4"||r==="7")return{valid:je.length===0,errors:je}}if(Array.isArray(m)){let ct=m.length,ze=!1;for(let ht=0;ht<ct;ht++)if(c===m[ht]||m[ht]==="integer"&&c==="number"&&t%1===0&&t===t){ze=!0;break}ze||je.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(c!=="number"||t%1||t!==t)&&je.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&je.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(c==="object"||c==="array"?dO(t,h)||je.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&je.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),y!==void 0&&(c==="object"||c==="array"?y.some(ct=>dO(t,ct))||je.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(ct=>t===ct)||je.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),b!==void 0){let ct=`${s}/not`;Ku(t,b,r,n,o,i,a,ct).valid&&je.push({instanceLocation:a,keyword:"not",keywordLocation:ct,error:'Instance matched "not" schema.'})}let Gr=[];if(_!==void 0){let ct=`${s}/anyOf`,ze=je.length,ht=!1;for(let $e=0;$e<_.length;$e++){let Ue=_[$e],Ve=Object.create(u),Kt=Ku(t,Ue,r,n,o,p===!0?i:null,a,`${ct}/${$e}`,Ve);je.push(...Kt.errors),ht=ht||Kt.valid,Kt.valid&&Gr.push(Ve)}ht?je.length=ze:je.splice(ze,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:ct,error:"Instance does not match any subschemas."})}if(w!==void 0){let ct=`${s}/allOf`,ze=je.length,ht=!0;for(let $e=0;$e<w.length;$e++){let Ue=w[$e],Ve=Object.create(u),Kt=Ku(t,Ue,r,n,o,p===!0?i:null,a,`${ct}/${$e}`,Ve);je.push(...Kt.errors),ht=ht&&Kt.valid,Kt.valid&&Gr.push(Ve)}ht?je.length=ze:je.splice(ze,0,{instanceLocation:a,keyword:"allOf",keywordLocation:ct,error:"Instance does not match every subschema."})}if(T!==void 0){let ct=`${s}/oneOf`,ze=je.length,ht=T.filter(($e,Ue)=>{let Ve=Object.create(u),Kt=Ku(t,$e,r,n,o,p===!0?i:null,a,`${ct}/${Ue}`,Ve);return je.push(...Kt.errors),Kt.valid&&Gr.push(Ve),Kt.valid}).length;ht===1?je.length=ze:je.splice(ze,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:ct,error:`Instance does not match exactly one subschema (${ht} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...Gr),O!==void 0){let ct=`${s}/if`;if(Ku(t,O,r,n,o,i,a,ct,u).valid){if(E!==void 0){let ht=Ku(t,E,r,n,o,i,a,`${s}/then`,u);ht.valid||je.push({instanceLocation:a,keyword:"if",keywordLocation:ct,error:'Instance does not match "then" schema.'},...ht.errors)}}else if(P!==void 0){let ht=Ku(t,P,r,n,o,i,a,`${s}/else`,u);ht.valid||je.push({instanceLocation:a,keyword:"if",keywordLocation:ct,error:'Instance does not match "else" schema.'},...ht.errors)}}if(c==="object"){if(g!==void 0)for(let $e of g)$e in t||je.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${$e}".`});let ct=Object.keys(t);if(k!==void 0&&ct.length<k&&je.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),X!==void 0&&ct.length>X&&je.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${X} properties.`}),B!==void 0){let $e=`${s}/propertyNames`;for(let Ue in t){let Ve=`${a}/${iw(Ue)}`,Kt=Ku(Ue,B,r,n,o,i,Ve,$e);Kt.valid||je.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:$e,error:`Property name "${Ue}" does not
2026-01-05 13:03:55 +08:00
data: ${JSON.stringify(o)}
`));n.enqueue(e.encode(`event: end
2026-02-24 07:55:02 +08:00
`)),n.close()}});return $b.fromReadableStream(r)}var NAt=v(()=>{nO()});function x3e(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function Bge(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*T3e(t,e){for(;;){let{value:r,done:n}=Rh.runWithConfig(jb(t),e.next.bind(e),!0);if(n)break;yield r}}async function*zge(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await Rh.runWithConfig(jb(t),r.next.bind(e),!0);if(o)break;yield n}}var DAt,jAt=v(()=>{zz();Vz();rO();DAt=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function Rd(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Kvn(t){if(she(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function aw(t){if(typeof t=="function")return new D_({func:t});if(Go.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=aw(n);return new lF({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function Gvn(t,e){let r=e.name??t.getName(),n=e.description??nF(e.schema);return _J(e.schema)?new Vge({name:r,description:n,schema:wt.object({input:wt.string()}).transform(o=>o.input),bound:t}):new Vge({name:r,description:n,schema:e.schema,bound:t})}var Go,DS,LAt,Hge,Bl,lF,Jvn,D_,BAt,O3e,ate,E3e,Vge,Pg=v(()=>{kL();Wpe();zz();Vz();rO();iJ();nO();sMt();fMt();S4e();Jz();gMt();Phe();QN();IAt();NAt();jAt();cO();JQ();o4e();Go=class extends Cg{constructor(){super(...arguments);x(this,"lc_runnable",!0);x(this,"name")}getName(e){let r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}withRetry(e){return new Hge({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new DS({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new O3e({runnable:this,fallbacks:r})}_getOptionsList(e,r=0){if(Array.isArray(e)&&e.length!==r)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${r} inputs`);if(Array.isArray(e))return e.map(ai);if(r>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let n=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));return Array.from({length:r},(o,i)=>ai(i===0?e:n))}return Array.from({length:r},()=>ai(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new ES({maxConcurrency:i,onFailedAttempt:u=>{throw u}}),s=e.map((u,l)=>a.call(async()=>{try{return await this.invoke(u,o[l])}catch(c){if(n?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,r){yield this.invoke(e,r)}async stream(e,r){let n=ai(r),o=new KL({generator:this._streamIterator(e,n),config:n});return await o.setup,$b.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=ai(e):r=ai({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 n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[r,n]}async _callWithConfig(e,r,n){let o=ai(n),a=await(await Ry(o))?.handleChainStart(this.toJSON(),Rd(r,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{let u=e.call(this,r,o,a);s=await TS(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(Rd(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(Ry)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),Rd(r[c],"input"),i[c].runId,i[c].runType,void 0,void 0,i[c].runName??this.getName());return delete i[c].runId,d})),u;try{let l=e.call(this,r,i,s,o);u=await TS(l,i?.[0]?.signal)}catch(l){throw await Promise.all(s.map(c=>c?.handleChainError(l))),l}return await Promise.all(s.map(l=>l?.handleChainEnd(Rd(u,"output")))),u}_concatOutputChunks(e,r){return Lb(e,r)}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=ai(n),l=await Ry(u),c=this;async function*d(){for await(let p of e){if(i)if(o===void 0)o=p;else try{o=c._concatOutputChunks(o,p)}catch{o=void 0,i=!1}yield p}}let f;try{let p=await g4e(r.bind(this),d(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName(),void 0,{lc_defers_inputs:!0}),n?.signal,u);delete u.runId,f=p.setup;let m=f?.handlers.find(cMt),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let y=f?.handlers.find(w4e);y!==void 0&&f!==void 0&&(h=y.tapOutputIterable(f.runId,h));for await(let g of h)if(yield g,s)if(a===void 0)a=g;else try{a=this._concatOutputChunks(a,g)}catch{a=void 0,s=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,
${a.content}`),e.push(Zvn(s))}}return e}function QAt(t,e){if(Array.isArray(t)){let r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return GAt(r,e)}else{let r=t;return D_.from(n=>GAt(n,r)).withConfig({runName:"trim_messages"})}}async function GAt(t,e){let{maxTokens:r,tokenCounter:n,strategy:o="last",allowPartial:i=!1,endOn:a,startOn:s,includeSystem:u=!1,textSplitter:l}=e;if(s&&o==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(u&&o==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let c;"getNumTokens"in n?c=async f=>(await Promise.all(f.map(m=>n.getNumTokens(m.content)))).reduce((m,h)=>m+h,0):c=async f=>n(f);let d=M3e;if(l&&("splitText"in l?d=l.splitText:d=async f=>l(f)),o==="first")return eNt(t,{maxTokens:r,tokenCounter:c,textSplitter:d,partialStrategy:i?"first":void 0,endOn:a});if(o==="last")return Xvn(t,{maxTokens:r,tokenCounter:c,textSplitter:d,allowPartial:i,includeSystem:u,startOn:s,endOn:a});throw new Error(`Unrecognized strategy: '${o}'. Must be one of 'first' or 'last'.`)}async function eNt(t,e){let{maxTokens:r,tokenCounter:n,textSplitter:o,partialStrategy:i,endOn:a}=e,s=[...t],u=0;for(let l=0;l<s.length;l+=1){let c=l>0?s.slice(0,-l):s;if(await n(c)<=r){u=s.length-l;break}}if(u<s.length&&i){let l=!1;if(Array.isArray(s[u].content)){let c=s[u];if(typeof c.content=="string")throw new Error("Expected content to be an array.");let d=c.content.length,f=i==="last"?[...c.content].reverse():c.content;for(let p=1;p<=d;p+=1){let m=i==="first"?f.slice(0,p):f.slice(-p),h=Object.fromEntries(Object.entries(c).filter(([b])=>b!=="type"&&!b.startsWith("lc_"))),y=P3e(c.getType(),{...h,content:m}),g=[...s.slice(0,u),y];if(await n(g)<=r)s=g,u+=1,l=!0;else break}l&&i==="last"&&(c.content=[...f].reverse())}if(!l){let c=s[u],d;if(Array.isArray(c.content)&&c.content.some(f=>typeof f=="string"||f.type==="text")?d=c.content.find(p=>p.type==="text"&&p.text)?.text:typeof c.content=="string"&&(d=c.content),d){let f=await o(d),p=f.length;i==="last"&&f.reverse();for(let m=0;m<p-1;m+=1)if(f.pop(),c.content=f.join(""),await n([...s.slice(0,u),c])<=r){i==="last"&&(c.content=[...f].reverse().join("")),s=[...s.slice(0,u),c],u+=1;break}}}}if(a){let l=Array.isArray(a)?a:[a];for(;u>0&&!Jge(s[u-1],l);)u-=1}return s.slice(0,u)}async function Xvn(t,e){let{allowPartial:r=!1,includeSystem:n=!1,endOn:o,startOn:i,...a}=e,s=t.map(c=>{let d=Object.fromEntries(Object.entries(c).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return P3e(c.getType(),d,K6(c))});if(o){let c=Array.isArray(o)?o:[o];for(;s.length>0&&!Jge(s[s.length-1],c);)s=s.slice(0,-1)}let u=n&&s[0]?.getType()==="system",l=u?s.slice(0,1).concat(s.slice(1).reverse()):s.reverse();return l=await eNt(l,{...a,partialStrategy:r?"last":void 0,endOn:i}),u?[l[0],...l.slice(1).reverse()]:l.reverse()}function P3e(t,e,r){let n,o;switch(t){case"human":r?n=new rw(e):o=new qs(e);break;case"ai":if(r){let i={...e};"tool_calls"in i&&(i={...i,tool_call_chunks:i.tool_calls?.map(a=>({...a,type:"tool_call_chunk",index:void 0,args:JSON.stringify(a.args)}))}),n=new Er(i)}else o=new Pn(e);break;case"system":r?n=new Rb(e):o=new Od(e);break;case"developer":r?n=new Rb({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):o=new Od({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new _S(e):o=new Mh(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new tw(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");o=new Iz(e)}break;case"generic":if("role"in e)r?n=new ew(e):o=new Td(e);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${t}`)}if(r&&n)return n;if(o)return o;throw new Error(`Unrecognized message type ${t}`)}function Zvn(t){let e=t.getType(),r,n=Object.fromEntries(Object.entries(t
2026-01-05 13:03:55 +08:00
`);return Promise.resolve([...e.slice(0,-1).map(r=>`${r}
2026-02-24 07:55:02 +08:00
`),e[e.length-1]])}var Jge,XAt,tNt=v(()=>{Oy();G6();UQ();tme();zL();rme();BQ();UC();vS();Pg();Jge=(t,e)=>{let r=[...new Set(e?.map(o=>{if(typeof o=="string")return o;let i=new o({});if(!("getType"in i)||typeof i.getType!="function")throw new Error("Invalid type provided.");return i.getType()}))],n=t.getType();return r.some(o=>o===n)};XAt={human:{message:qs,messageChunk:rw},ai:{message:Pn,messageChunk:Er},system:{message:Od,messageChunk:Rb},developer:{message:Od,messageChunk:Rb},tool:{message:Mh,messageChunk:_S},function:{message:Iz,messageChunk:tw},generic:{message:Td,messageChunk:ew},remove:{message:Az,messageChunk:Az}}});var rNt,nNt=v(()=>{rNt=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"]});var oNt,iNt=v(()=>{oNt=["image","video","audio","text-plain","file"]});var aNt,sNt=v(()=>{nNt();iNt();aNt=["text","reasoning",...rNt,...oNt]});var Yvn,ta=v(()=>{Jo();LQ();bBe();Oy();ime();G6();UQ();tme();zL();rme();BQ();UC();vS();tNt();sNt();Yvn={};$t(Yvn,{AIMessage:()=>Pn,AIMessageChunk:()=>Er,BaseMessage:()=>id,BaseMessageChunk:()=>Mb,ChatMessage:()=>Td,ChatMessageChunk:()=>ew,FunctionMessage:()=>Iz,FunctionMessageChunk:()=>tw,HumanMessage:()=>qs,HumanMessageChunk:()=>rw,KNOWN_BLOCK_TYPES:()=>aNt,RemoveMessage:()=>Az,SystemMessage:()=>Od,SystemMessageChunk:()=>Rb,ToolMessage:()=>Mh,ToolMessageChunk:()=>_S,_isMessageFieldWithRole:()=>eme,_mergeDicts:()=>Fl,_mergeLists:()=>Rz,_mergeObj:()=>Qpe,_mergeStatus:()=>Ype,coerceMessageLikeToMessage:()=>wS,collapseToolCallChunks:()=>ame,convertToChunk:()=>Nz,convertToOpenAIImageBlock:()=>Kpe,convertToProviderContentBlock:()=>GT,defaultTextSplitter:()=>M3e,defaultToolCallParser:()=>kQ,filterMessages:()=>ZAt,getBufferString:()=>fl,iife:()=>sme,isAIMessage:()=>kl,isAIMessageChunk:()=>zQ,isBase64ContentBlock:()=>J6,isBaseMessage:()=>xg,isBaseMessageChunk:()=>K6,isChatMessage:()=>QCt,isChatMessageChunk:()=>ext,isDataContentBlock:()=>Ph,isDirectToolOutput:()=>FQ,isFunctionMessage:()=>txt,isFunctionMessageChunk:()=>rxt,isHumanMessage:()=>nxt,isHumanMessageChunk:()=>oxt,isIDContentBlock:()=>Jpe,isMessage:()=>Zpe,isOpenAIToolCallArray:()=>XCt,isPlainTextContentBlock:()=>LCt,isSystemMessage:()=>ixt,isSystemMessageChunk:()=>axt,isToolMessage:()=>qQ,isToolMessageChunk:()=>vBe,isURLContentBlock:()=>W6,mapChatMessagesToStoredMessages:()=>Ixt,mapStoredMessageToChatMessage:()=>VQ,mapStoredMessagesToChatMessages:()=>Rxt,mergeContent:()=>Ty,mergeMessageRuns:()=>YAt,mergeResponseMetadata:()=>ome,mergeUsageMetadata:()=>X6,parseBase64DataUrl:()=>Cy,parseMimeType:()=>$Q,trimMessages:()=>QAt})});var uNt,lNt=v(()=>{Oy();zL();vS();Pg();ta();Wge();uNt=class extends DS{constructor(e){let r=D_.from((a,s)=>this._enterHistory(a,s??{})).withConfig({runName:"loadHistory"}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(r=Au.assign({[n]:r}).withConfig({runName:"insertHistory"}));let o=r.pipe(e.runnable.withListeners({onEnd:(a,s)=>this._exitHistory(a,s??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:o});x(this,"runnable");x(this,"inputMessagesKey");x(this,"outputMessagesKey");x(this,"historyMessagesKey");x(this,"getMessageHistory");this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let r;if(typeof e=="object"&&!Array.isArray(e)&&!xg(e)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?r=e[n][0]:r=e[n]}else r=e;if(typeof r=="string")return[new qs(r)];if(Array.isArray(r))return r;if(xg(r))return[r];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
Got ${JSON.stringify(r,null,2)}`)}_getOutputMessages(e){let r;if(!Array.isArray(e)&&!xg(e)&&typeof e!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void 0?r=e.generations[0][0].message:r=e[n]}else r=e;if(typeof r=="string")return[new Pn(r)];if(Array.isArray(r))return r;if(xg(r))return[r];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(r,null,2)}`)}async _enterHistory(e,r){let o=await(r?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?o.concat(this._getInputMessages(e)):o}async _exitHistory(e,r){let n=r.configurable?.messageHistory,o;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?o=e.inputs[0]:o=e.inputs;let i=this._getInputMessages(o);if(this.historyMessagesKey===void 0){let u=await n.getMessages();i=i.slice(u.length)}let a=e.outputs;if(!a)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let s=this._getOutputMessages(a);await n.addMessages([...i,...s])}async _mergeConfig(...e){let r=await super._mergeConfig(...e);if(!r.configurable||!r.configurable.sessionId){let o={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
eg. chain.invoke(${JSON.stringify(o)}, ${JSON.stringify(i)})`)}let{sessionId:n}=r.configurable;return r.configurable.messageHistory=await this.getMessageHistory(n),r}}});var Qvn,sw=v(()=>{Jo();rO();iJ();Pg();Wge();VAt();WAt();lNt();Qvn={};$t(Qvn,{RouterRunnable:()=>zAt,Runnable:()=>Go,RunnableAssign:()=>ate,RunnableBinding:()=>DS,RunnableBranch:()=>HAt,RunnableEach:()=>LAt,RunnableLambda:()=>D_,RunnableMap:()=>lF,RunnableParallel:()=>BAt,RunnablePassthrough:()=>Au,RunnablePick:()=>E3e,RunnableRetry:()=>Hge,RunnableSequence:()=>Bl,RunnableToolLike:()=>Vge,RunnableWithFallbacks:()=>O3e,RunnableWithMessageHistory:()=>uNt,_coerceToRunnable:()=>aw,ensureConfig:()=>ai,getCallbackManagerForConfig:()=>Ry,mergeConfigs:()=>Hz,patchConfig:()=>Xs,pickRunnableConfigKeys:()=>jb,raceWithSignal:()=>TS})});var v4,o1,Ih,MJ=v(()=>{DQ();Pg();sw();v4=class extends Go{parseResultWithPrompt(t,e,r){return this.parseResult(t,r)}_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(r,n)=>this.parseResult([{text:r}],n?.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(r,n)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],n?.callbacks),t,{...e,runType:"parser"})}},o1=class extends v4{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,r){return this.parse(t,r)}_type(){throw new Error("_type not implemented")}},Ih=class extends Error{constructor(e,r,n,o=!1){super(e);x(this,"llmOutput");x(this,"observation");x(this,"sendToLLM");if(this.llmOutput=r,this.observation=n,this.sendToLLM=o,o&&(n===void 0||r===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");FL(this,"OUTPUT_PARSING_FAILURE")}}});var i1,cF,dF=v(()=>{Oy();UC();Ed();MJ();qge();i1=class extends o1{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"})}},cF=class extends i1{constructor(e){super(e);x(this,"diff",!1);this.diff=e?.diff??this.diff}async*_transform(e){let r,n;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(K6(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new si({message:o,text:o.content})}else if(xg(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new si({message:Nz(o),text:o.content})}else i=new OS({text:o});n===void 0?n=i:n=n.concat(i);let a=await this.parsePartialResult([n]);a!=null&&!dO(a,r)&&(this.diff?yield this._diff(r,a):yield a,r=a)}}getFormatInstructions(){return""}}});var cNt,dNt=v(()=>{dF();cNt=class extends i1{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","bytes"]);x(this,"lc_serializable",!0);x(this,"textEncoder",new TextEncoder)}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}}});var RJ,fNt,pNt,mNt,hNt,gNt=v(()=>{MJ();dF();RJ=class extends i1{constructor(){super(...arguments);x(this,"re")}async*_transform(e){let r="";for await(let n of e)if(typeof n=="string"?r+=n:r+=n.content,this.re){let o=[...r.matchAll(this.re)];if(o.length>1){let i=0;for(let a of o.slice(0,-1))yield[a[1]],i+=(a.index??0)+a[0].length;r=r.slice(i)}}else{let o=await this.parse(r);if(o.length>1){for(let i of o.slice(0,-1))yield[i];r=o[o.length-1]}}for(let n of await this.parse(r))yield[n]}},fNt=class extends RJ{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","list"]);x(this,"lc_serializable",!0)}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map(r=>r.trim())}catch{throw new Ih(`Could not pa
2026-01-05 13:03:55 +08:00
1. foo
2. bar
2026-02-24 07:55:02 +08:00
3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(r=>r[1])}},hNt=class extends RJ{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","list"]);x(this,"lc_serializable",!0);x(this,"re",/^\s*[-*]\s([^\n]+)$/gm)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
2026-01-05 13:03:55 +08:00
1. foo
2. bar
2026-02-24 07:55:02 +08:00
3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(r=>r[1])}}});var Kge,yNt=v(()=>{dF();Kge=class extends i1{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","string"]);x(this,"lc_serializable",!0)}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((r,n)=>r+this._messageContentToString(n),"")}}});var uw,R3e,bNt,_Nt=v(()=>{QN();Ny();MJ();cO();uw=class extends o1{constructor(e){super(e);x(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let r=wt.object(Object.fromEntries(Object.entries(e).map(([n,o])=>[n,wt.string().describe(o)])));return new this(r)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
2026-01-05 13:03:55 +08:00
"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
2026-02-24 07:55:02 +08:00
${JSON.stringify(Ci(this.schema))}
2026-01-05 13:03:55 +08:00
\`\`\`
2026-02-24 07:55:02 +08:00
`}async parse(e){try{let r=e.trim(),o=(r.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||r.match(/```json\s*([\s\S]*?)```/)?.[1]||r).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(i,a)=>`"${a.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await rF(this.schema,JSON.parse(o))}catch(r){throw new Ih(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}},R3e=class extends uw{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){let e=t?.interpolationDepth??1;if(e<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
2026-01-05 13:03:55 +08:00
\`\`\`json
2026-02-24 07:55:02 +08:00
${this._schemaToInstruction(Ci(this.schema)).replaceAll("{","{".repeat(e)).replaceAll("}","}".repeat(e))}
2026-01-05 13:03:55 +08:00
\`\`\``}_schemaToInstruction(t,e=2){let r=t;if("type"in r){let n=!1,o;if(Array.isArray(r.type)){let s=r.type.findIndex(u=>u==="null");s!==-1&&(n=!0,r.type.splice(s,1)),o=r.type.join(" | ")}else o=r.type;if(r.type==="object"&&r.properties){let s=r.description?` // ${r.description}`:"";return`{
${Object.entries(r.properties).map(([l,c])=>{let d=r.required?.includes(l)?"":" (optional)";return`${" ".repeat(e)}"${l}": ${this._schemaToInstruction(c,e+2)}${d}`}).join(`
`)}
${" ".repeat(e-2)}}${s}`}if(r.type==="array"&&r.items){let s=r.description?` // ${r.description}`:"";return`array[
${" ".repeat(e)}${this._schemaToInstruction(r.items,e+2)}
${" ".repeat(e-2)}] ${s}`}let i=n?" (nullable)":"",a=r.description?` // ${r.description}`:"";return`${o}${a}${i}`}if("anyOf"in r)return r.anyOf.map(n=>this._schemaToInstruction(n,e)).join(`
2026-02-24 07:55:02 +08:00
${" ".repeat(e-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){let e=wt.object(Object.fromEntries(Object.entries(t).map(([r,n])=>[r,wt.string().describe(n)])));return new this(e)}},bNt=class extends o1{constructor({inputSchema:e}){super(...arguments);x(this,"structuredInputParser");this.structuredInputParser=new R3e(e)}async parse(e){let r;try{r=await this.structuredInputParser.parse(e)}catch(n){throw new Ih(`Failed to parse. Text: "${e}". Error: ${n}`,e)}return this.outputProcessor(r)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}}});var ewn,I3e=v(()=>{Jo();pee();mee();_4e();ewn={};$t(ewn,{applyPatch:()=>GL,compare:()=>sJ})});var j_,A3e=v(()=>{NQ();mee();dF();I3e();j_=class extends cF{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers"]);x(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,r){return this.diff?super._concatOutputChunks(e,r):r}_diff(e,r){if(r)return e?sJ(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return AQ(e[0].text)}async parse(e){return AQ(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}}});var twn,vNt,wNt=v(()=>{twn=function(){let t={};t.parser=function(j,A){return new r(j,A)},t.SAXParser=r,t.SAXStream=l,t.createStream=u,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 r(j,A){if(!(this instanceof r))return new r(j,A);var U=this;o(U),U.q=U.c="",U.bufferCheckPosition=t.MAX_BUFFER_LENGTH,U.opt=A||{},U.opt.lowercase=U.opt.lowercase||U.opt.lowercasetags,U.looseCase=U.opt.lowercase?"toLowerCase":"toUpperCase",U.tags=[],U.closed=U.closedRoot=U.sawRoot=!1,U.tag=U.error=null,U.strict=!!j,U.noscript=!!(j||U.opt.noscript),U.state=P.BEGIN,U.strictEntities=U.opt.strictEntities,U.ENTITIES=U.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),U.attribList=[],U.opt.xmlns&&(U.ns=Object.create(m)),U.trackPosition=U.opt.position!==!1,U.trackPosition&&(U.position=U.line=U.column=0),I(U,"onready")}Object.create||(Object.create=function(j){function A(){}A.prototype=j;var U=new A;return U}),Object.keys||(Object.keys=function(j){var A=[];for(var U in j)j.hasOwnProperty(U)&&A.push(U);return A});function n(j){for(var A=Math.max(t.MAX_BUFFER_LENGTH,10),U=0,H=0,re=e.length;H<re;H++){var Z=j[e[H]].length;if(Z>A)switch(e[H]){case"textNode":z(j);break;case"cdata":N(j,"oncdata",j.cdata),j.cdata="";break;case"script":N(j,"onscript",j.script),j.script="";break;default:k(j,"Max buffer length exceeded: "+e[H])}U=Math.max(U,Z)}var le=t.MAX_BUFFER_LENGTH-U;j.bufferCheckPosition=le+j.position}function o(j){for(var A=0,U=e.length;A<U;A++)j[e[A]]=""}function i(j){z(j),j.cdata!==""&&(N(j,"oncdata",j.cdata),j.cdata=""),j.script!==""&&(N(j,"onscript",j.script),j.script="")}r.prototype={end:function(){X(this)},write:ie,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){i(this)}};var a=ReadableStream;a||(a=function(){});var s=t.EVENTS.filter(function(j){return j!=="error"&&j!=="end"});function u(j,A){return new l(j,A)}function l(j,A){if(!(this instanceof l))return new l(j,A);a.apply(this),this._parser=new r(j,A),this.writable=!0,this.readable=!0;var U=this;this._parser.onend=function(){U.emit("end")},this._parser.onerror=function(H){U.emit("error",H),U._parser.error=null},this._decoder=null,s.forEach(function(H){Object.defineProperty(U,"on"+H,{get:function(){return U._parser["on"+H]},set:function(re){if(!re)return U.removeAllListeners(H),U._parser["on"+H]=re,re;U.on(H,re)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(a.prototype,{constructor:{value:l}}),l.prototy
`||j==="\r"||j===" "}function w(j){return j==='"'||j==="'"}function T(j){return j===">"||_(j)}function O(j,A){return j.test(A)}function E(j,A){return!O(j,A)}var P=0;t.STATE={BEGIN:P++,BEGIN_WHITESPACE:P++,TEXT:P++,TEXT_ENTITY:P++,OPEN_WAKA:P++,SGML_DECL:P++,SGML_DECL_QUOTED:P++,DOCTYPE:P++,DOCTYPE_QUOTED:P++,DOCTYPE_DTD:P++,DOCTYPE_DTD_QUOTED:P++,COMMENT_STARTING:P++,COMMENT:P++,COMMENT_ENDING:P++,COMMENT_ENDED:P++,CDATA:P++,CDATA_ENDING:P++,CDATA_ENDING_2:P++,PROC_INST:P++,PROC_INST_BODY:P++,PROC_INST_ENDING:P++,OPEN_TAG:P++,OPEN_TAG_SLASH:P++,ATTRIB:P++,ATTRIB_NAME:P++,ATTRIB_NAME_SAW_WHITE:P++,ATTRIB_VALUE:P++,ATTRIB_VALUE_QUOTED:P++,ATTRIB_VALUE_CLOSED:P++,ATTRIB_VALUE_UNQUOTED:P++,ATTRIB_VALUE_ENTITY_Q:P++,ATTRIB_VALUE_ENTITY_U:P++,CLOSE_TAG:P++,CLOSE_TAG_SAW_WHITE:P++,SCRIPT:P++,SCRIPT_ENDING:P++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(j){var A=t.ENTITIES[j],U=typeof A=="number"?String.fromCharCode(A):A;t.ENTITIES[j]=U});for(var R in t.STATE)t.STATE[t.STATE[R]]=R;P=t.STATE;function I(j,A,U){j[A]&&j[A](U)}function N(j,A,U){j.textNode&&z(j),I(j,A,U)}function z(j){j.textNode=V(j.opt,j.textNode),j.textNode&&I(j,"ontext",j.textNode),j.textNode=""}function V(j,A){return j.trim&&(A=A.trim()),j.normalize&&(A=A.replace(/\s+/g," ")),A}function k(j,A){return z(j),j.trackPosition&&(A+=`
Line: `+j.line+`
Column: `+j.column+`
Char: `+j.c),A=new Error(A),j.error=A,I(j,"onerror",A),j}function X(j){return j.sawRoot&&!j.closedRoot&&B(j,"Unclosed root tag"),j.state!==P.BEGIN&&j.state!==P.BEGIN_WHITESPACE&&j.state!==P.TEXT&&k(j,"Unexpected end"),z(j),j.c="",j.closed=!0,I(j,"onend"),r.call(j,j.strict,j.opt),j}function B(j,A){if(typeof j!="object"||!(j instanceof r))throw new Error("bad call to strictFail");j.strict&&k(j,A)}function Q(j){j.strict||(j.tagName=j.tagName[j.looseCase]());var A=j.tags[j.tags.length-1]||j,U=j.tag={name:j.tagName,attributes:{}};j.opt.xmlns&&(U.ns=A.ns),j.attribList.length=0,N(j,"onopentagstart",U)}function Y(j,A){var U=j.indexOf(":"),H=U<0?["",j]:j.split(":"),re=H[0],Z=H[1];return A&&j==="xmlns"&&(re="xmlns",Z=""),{prefix:re,local:Z}}function K(j){if(j.strict||(j.attribName=j.attribName[j.looseCase]()),j.attribList.indexOf(j.attribName)!==-1||j.tag.attributes.hasOwnProperty(j.attribName)){j.attribName=j.attribValue="";return}if(j.opt.xmlns){var A=Y(j.attribName,!0),U=A.prefix,H=A.local;if(U==="xmlns")if(H==="xml"&&j.attribValue!==f)B(j,"xml: prefix must be bound to "+f+`
Actual: `+j.attribValue);else if(H==="xmlns"&&j.attribValue!==p)B(j,"xmlns: prefix must be bound to "+p+`
Actual: `+j.attribValue);else{var re=j.tag,Z=j.tags[j.tags.length-1]||j;re.ns===Z.ns&&(re.ns=Object.create(Z.ns)),re.ns[H]=j.attribValue}j.attribList.push([j.attribName,j.attribValue])}else j.tag.attributes[j.attribName]=j.attribValue,N(j,"onattribute",{name:j.attribName,value:j.attribValue});j.attribName=j.attribValue=""}function oe(j,A){if(j.opt.xmlns){var U=j.tag,H=Y(j.tagName);U.prefix=H.prefix,U.local=H.local,U.uri=U.ns[H.prefix]||"",U.prefix&&!U.uri&&(B(j,"Unbound namespace prefix: "+JSON.stringify(j.tagName)),U.uri=H.prefix);var re=j.tags[j.tags.length-1]||j;U.ns&&re.ns!==U.ns&&Object.keys(U.ns).forEach(function(Gr){N(j,"onopennamespace",{prefix:Gr,uri:U.ns[Gr]})});for(var Z=0,le=j.attribList.length;Z<le;Z++){var Ce=j.attribList[Z],He=Ce[0],lt=Ce[1],qe=Y(He,!0),Nt=qe.prefix,mt=qe.local,Ot=Nt===""?"":U.ns[Nt]||"",je={name:He,value:lt,prefix:Nt,local:mt,uri:Ot};Nt&&Nt!=="xmlns"&&!Ot&&(B(j,"Unbound namespace prefix: "+JSON.stringify(Nt)),je.uri=Nt),j.tag.attributes[He]=je,N(j,"onattribute",je)}j.attribList.length=0}j.tag.isSelfClosing=!!A,j.sawRoot=!0,j.tags.push(j.tag),N(j,"onopentag",j.tag),A||(!j.noscript&&j.tagName.toLowerCase()==="script"?j.state=P.SCRIPT:j.state=P.TEXT,j.tag=null,j.tagName=""),j.attribName=j.attribValue="",j.attribList.length=0}function ue(j){if(!j.tagName){B(j,"Weird empty close tag."),j.textNode+="</>",j.state=P.TEXT;return}if(j.script){if(j.tagName!=="script"){j.script+="</"+j.tagName+">",j.tagName="",j.state=P.SCRIPT;return}N(j,"onscript",j.script),j.script=""}var A=j.tags.length,U=j.tagName;j.strict||(U=U[j.looseCase]());for(var H=U;A--;){var re=j.tags[A];if(re.name!==H)B(j,"Unexpected close tag");else break}if(A<0){B(j,"Unmatched closing tag: "+j.tagName),j.textNode+="</"+j.tagName+">",j.state=P.TEXT;return}j.tagName=U;for(var Z=j.tags.length;Z-- >A;){var le=j.tag=j.tags.pop();j.tagName=j.tag.name,N(j,"onclosetag",j.tagName);var Ce={};for(var He in le.ns)Ce[He]=le.ns[He];var lt=j.tags[j.tags.length-1]||j;j.opt.xmlns&&le.ns!==lt.ns&&Object.keys(le.ns).forEach(function(qe){var Nt=le.ns[qe];N(j,"onclosenamespace",{prefix:qe,uri:Nt})})}A===0&&(j.closedRoot=!0),j.tagName=j.attribValue=j.attribName="",j.attribList.length=0,j.state=P.TEXT}function de(j){var A=j.entity,U=A.toLowerCase(),H,re="";return j.ENTITIES[A]?j.ENTITIES[A]:j.ENTITIES[U]?j.ENTITIES[U]:(A=U,A.charAt(0)==="#"&&(A.charAt(1)==="x"?(A=A.slice(2),H=parseInt(A,16),re=H.toString(16)):(A=A.slice(1),H=parseInt(A,10),re=H.toString(10))),A=A.replace(/^0+/,""),isNaN(H)||re.toLowerCase()!==A?(B(j,"Invalid character entity"),"&"+j.entity+";"):String.fromCodePoint(H))}function L(j,A){A==="<"?(j.state=P.OPEN_WAKA,j.startTagPosition=j.position):_(A)||(B(j,"Non-whitespace before first tag."),j.textNode=A,j.state=P.TEXT)}function W(j,A){var U="";return A<j.length&&(U=j.charAt(A)),U}function ie(j){var A=this;if(this.error)throw this.error;if(A.closed)return k(A,"Cannot write after close. Assign an onready handler.");if(j===null)return X(A);typeof j=="object"&&(j=j.toString());for(var U=0,H="";H=W(j,U++),A.c=H,!!H;)switch(A.trackPosition&&(A.position++,H===`
`?(A.line++,A.column=0):A.column++),A.state){case P.BEGIN:if(A.state=P.BEGIN_WHITESPACE,H==="\uFEFF")continue;L(A,H);continue;case P.BEGIN_WHITESPACE:L(A,H);continue;case P.TEXT:if(A.sawRoot&&!A.closedRoot){for(var re=U-1;H&&H!=="<"&&H!=="&";)H=W(j,U++),H&&A.trackPosition&&(A.position++,H===`
`?(A.line++,A.column=0):A.column++);A.textNode+=j.substring(re,U-1)}H==="<"&&!(A.sawRoot&&A.closedRoot&&!A.strict)?(A.state=P.OPEN_WAKA,A.startTagPosition=A.position):(!_(H)&&(!A.sawRoot||A.closedRoot)&&B(A,"Text data outside of root node."),H==="&"?A.state=P.TEXT_ENTITY:A.textNode+=H);continue;case P.SCRIPT:H==="<"?A.state=P.SCRIPT_ENDING:A.script+=H;continue;case P.SCRIPT_ENDING:H==="/"?A.state=P.CLOSE_TAG:(A.script+="<"+H,A.state=P.SCRIPT);continue;case P.OPEN_WAKA:if(H==="!")A.state=P.SGML_DECL,A.sgmlDecl="";else if(!_(H))if(O(h,H))A.state=P.OPEN_TAG,A.tagName=H;else if(H==="/")A.state=P.CLOSE_TAG,A.tagName="";else if(H==="?")A.state=P.PROC_INST,A.procInstName=A.procInstBody="";else{if(B(A,"Unencoded <"),A.startTagPosition+1<A.position){var Z=A.position-A.startTagPosition;H=new Array(Z).join(" ")+H}A.textNode+="<"+H,A.state=P.TEXT}continue;case P.SGML_DECL:(A.sgmlDecl+H).toUpperCase()===c?(N(A,"onopencdata"),A.state=P.CDATA,A.sgmlDecl="",A.cdata=""):A.sgmlDecl+H==="--"?(A.state=P.COMMENT,A.comment="",A.sgmlDecl=""):(A.sgmlDecl+H).toUpperCase()===d?(A.state=P.DOCTYPE,(A.doctype||A.sawRoot)&&B(A,"Inappropriately located doctype declaration"),A.doctype="",A.sgmlDecl=""):H===">"?(N(A,"onsgmldeclaration",A.sgmlDecl),A.sgmlDecl="",A.state=P.TEXT):(w(H)&&(A.state=P.SGML_DECL_QUOTED),A.sgmlDecl+=H);continue;case P.SGML_DECL_QUOTED:H===A.q&&(A.state=P.SGML_DECL,A.q=""),A.sgmlDecl+=H;continue;case P.DOCTYPE:H===">"?(A.state=P.TEXT,N(A,"ondoctype",A.doctype),A.doctype=!0):(A.doctype+=H,H==="["?A.state=P.DOCTYPE_DTD:w(H)&&(A.state=P.DOCTYPE_QUOTED,A.q=H));continue;case P.DOCTYPE_QUOTED:A.doctype+=H,H===A.q&&(A.q="",A.state=P.DOCTYPE);continue;case P.DOCTYPE_DTD:A.doctype+=H,H==="]"?A.state=P.DOCTYPE:w(H)&&(A.state=P.DOCTYPE_DTD_QUOTED,A.q=H);continue;case P.DOCTYPE_DTD_QUOTED:A.doctype+=H,H===A.q&&(A.state=P.DOCTYPE_DTD,A.q="");continue;case P.COMMENT:H==="-"?A.state=P.COMMENT_ENDING:A.comment+=H;continue;case P.COMMENT_ENDING:H==="-"?(A.state=P.COMMENT_ENDED,A.comment=V(A.opt,A.comment),A.comment&&N(A,"oncomment",A.comment),A.comment=""):(A.comment+="-"+H,A.state=P.COMMENT);continue;case P.COMMENT_ENDED:H!==">"?(B(A,"Malformed comment"),A.comment+="--"+H,A.state=P.COMMENT):A.state=P.TEXT;continue;case P.CDATA:H==="]"?A.state=P.CDATA_ENDING:A.cdata+=H;continue;case P.CDATA_ENDING:H==="]"?A.state=P.CDATA_ENDING_2:(A.cdata+="]"+H,A.state=P.CDATA);continue;case P.CDATA_ENDING_2:H===">"?(A.cdata&&N(A,"oncdata",A.cdata),N(A,"onclosecdata"),A.cdata="",A.state=P.TEXT):H==="]"?A.cdata+="]":(A.cdata+="]]"+H,A.state=P.CDATA);continue;case P.PROC_INST:H==="?"?A.state=P.PROC_INST_ENDING:_(H)?A.state=P.PROC_INST_BODY:A.procInstName+=H;continue;case P.PROC_INST_BODY:if(!A.procInstBody&&_(H))continue;H==="?"?A.state=P.PROC_INST_ENDING:A.procInstBody+=H;continue;case P.PROC_INST_ENDING:H===">"?(N(A,"onprocessinginstruction",{name:A.procInstName,body:A.procInstBody}),A.procInstName=A.procInstBody="",A.state=P.TEXT):(A.procInstBody+="?"+H,A.state=P.PROC_INST_BODY);continue;case P.OPEN_TAG:O(y,H)?A.tagName+=H:(Q(A),H===">"?oe(A):H==="/"?A.state=P.OPEN_TAG_SLASH:(_(H)||B(A,"Invalid character in tag name"),A.state=P.ATTRIB));continue;case P.OPEN_TAG_SLASH:H===">"?(oe(A,!0),ue(A)):(B(A,"Forward-slash in opening tag not followed by >"),A.state=P.ATTRIB);continue;case P.ATTRIB:if(_(H))continue;H===">"?oe(A):H==="/"?A.state=P.OPEN_TAG_SLASH:O(h,H)?(A.attribName=H,A.attribValue="",A.state=P.ATTRIB_NAME):B(A,"Invalid attribute name");continue;case P.ATTRIB_NAME:H==="="?A.state=P.ATTRIB_VALUE:H===">"?(B(A,"Attribute without value"),A.attribValue=A.attribName,K(A),oe(A)):_(H)?A.state=P.ATTRIB_NAME_SAW_WHITE:O(y,H)?A.attribName+=H:B(A,"Invalid attribute name");continue;case P.ATTRIB_NAME_SAW_WHITE:if(H==="=")A.state=P.ATTRIB_VALUE;else{if(_(H))continue;B(A,"Attribute without value"),A.tag.attributes[A.attribName]="",A.attribValue="",N(A,"onattribute",{name:A.attribName,value:""}),A.attribName="",H===">"?oe(A):O(h,H)?(A.attribName=H,A.state=P.ATTRIB_NAME):(B(A,"Invalid attribute name"),A.state=P.ATTRIB)}continue;case P.ATTRIB_VALUE:if(_(H))continue;w(H)?(A.q
2026-01-05 13:03:55 +08:00
1. Output should conform to the tags below.
2. If tags are not given, make them on your own.
3. Remember to always open and close all the tags.
As an example, for the tags ["foo", "bar", "baz"]:
1. String "<foo>
<bar>
<baz></baz>
</bar>
</foo>" is a well-formatted instance of the schema.
2. String "<foo>
<bar>
</foo>" is a badly-formatted instance.
3. String "<foo>
<tag>
</tag>
</foo>" is a badly-formatted instance.
Here are the output tags:
\`\`\`
{tags}
2026-02-24 07:55:02 +08:00
\`\`\``,SNt=class extends cF{constructor(e){super(e);x(this,"tags");x(this,"lc_namespace",["langchain_core","output_parsers"]);x(this,"lc_serializable",!0);this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}_diff(e,r){if(r)return e?sJ(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return Xge(e[0].text)}async parse(e){return Xge(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?Gge.replace("{tags}",this.tags?.join(", ")??""):Gge}},rwn=t=>t.split(`
2026-01-05 13:03:55 +08:00
`).map(e=>e.replace(/^\s+/,"")).join(`
2026-02-24 07:55:02 +08:00
`).trim(),CNt=t=>{if(Object.keys(t).length===0)return{};let e={};return t.children.length>0?(e[t.name]=t.children.map(CNt),e):(e[t.name]=t.text??void 0,e)}});var nwn,fO=v(()=>{Jo();NQ();MJ();dF();dNt();gNt();yNt();_Nt();A3e();xNt();nwn={};$t(nwn,{AsymmetricStructuredOutputParser:()=>bNt,BaseCumulativeTransformOutputParser:()=>cF,BaseLLMOutputParser:()=>v4,BaseOutputParser:()=>o1,BaseTransformOutputParser:()=>i1,BytesOutputParser:()=>cNt,CommaSeparatedListOutputParser:()=>fNt,CustomListOutputParser:()=>pNt,JsonMarkdownStructuredOutputParser:()=>R3e,JsonOutputParser:()=>j_,ListOutputParser:()=>RJ,MarkdownListOutputParser:()=>hNt,NumberedListOutputParser:()=>mNt,OutputParserException:()=>Ih,StringOutputParser:()=>Kge,StructuredOutputParser:()=>uw,XMLOutputParser:()=>SNt,XML_FORMAT_INSTRUCTIONS:()=>Gge,parseJsonMarkdown:()=>AQ,parsePartialJson:()=>Mz,parseXMLMarkdown:()=>Xge})});var jS,IJ=v(()=>{Pg();jS=class extends Go{constructor(e){super(e);x(this,"lc_serializable",!0);x(this,"lc_namespace",["langchain_core","prompts",this._getPromptType()]);x(this,"inputVariables");x(this,"outputParser");x(this,"partialVariables");x(this,"metadata");x(this,"tags");let{inputVariables:r}=e;if(r.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}get lc_attributes(){return{partialVariables:void 0}}async mergePartialAndUserVariables(e){let r=this.partialVariables??{},n={};for(let[i,a]of Object.entries(r))typeof a=="string"?n[i]=a:n[i]=await a();return{...n,...e}}async invoke(e,r){let n={...this.metadata,...r?.metadata},o=[...this.tags??[],...r?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...r,tags:o,metadata:n,runType:"prompt"})}}});var own,Zge,ste,ute,N3e,lte=v(()=>{Jo();kL();zL();UC();own={};$t(own,{BasePromptValue:()=>Zge,ChatPromptValue:()=>ute,ImagePromptValue:()=>N3e,StringPromptValue:()=>ste});Zge=class extends Cg{},ste=class extends Zge{constructor(e){super({value:e});x(this,"lc_namespace",["langchain_core","prompt_values"]);x(this,"lc_serializable",!0);x(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new qs(this.value)]}},ute=class extends Zge{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);x(this,"lc_namespace",["langchain_core","prompt_values"]);x(this,"lc_serializable",!0);x(this,"messages");this.messages=e.messages}static lc_name(){return"ChatPromptValue"}toString(){return fl(this.messages)}toChatMessages(){return this.messages}},N3e=class extends Zge{constructor(e){"imageUrl"in e||(e={imageUrl:e});super(e);x(this,"lc_namespace",["langchain_core","prompt_values"]);x(this,"lc_serializable",!0);x(this,"imageUrl");x(this,"value");this.imageUrl=e.imageUrl}static lc_name(){return"ImagePromptValue"}toString(){return this.imageUrl.url}toChatMessages(){return[new qs({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var a1,cte=v(()=>{lte();IJ();a1=class extends jS{async formatPromptValue(t){let e=await this.format(t);return new ste(e)}}});function j3e(t){return typeof t=="function"}function awn(t){return NJ(t)?"array":typeof t}function D3e(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function TNt(t,e){return t!=null&&typeof t=="object"&&e in t}function swn(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function lwn(t,e){return uwn.call(t,e)}function dwn(t){return!lwn(cwn,t)}function pwn(t){return String(t).replace(/[&<>"'`=\/]/g,function(r){return fwn[r]})}function bwn(t,e){if(!t)return[];var r=!1,n=[],o=[],i=[],a=!1,s=!1,u="",l=0;function c(){if(a&&!s)for(;i.length;)delete o[i.pop()];else i=[];a=!1,s=!1}var d,f,p;function m(P){if(typeof P=="string"&&(P=P.split(hwn,2)),!NJ(P)||P.length!==2)throw new Error("Invalid tags: "+P);d=new RegExp(D3e(P[0])+"\\s*"),f=new RegExp("\\s*"+D3e(P[1])),p=new RegExp("\\s*"+D3e("}"+P[1]))}m(e||$S.tags);for(var h=new fte(t),y,g,b,_,w,T;!h.eos();){if(y=h.pos,b=h.scanUntil(d),b)for(var O=0,E=b.length;O<E;++O)_=b.cha
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,g=h.scan(ywn)||"name",h.scan(mwn),g==="="?(b=h.scanUntil(ONt),h.scan(ONt),h.scanUntil(f)):g==="{"?(b=h.scanUntil(p),h.scan(gwn),h.scanUntil(f),g="&"):b=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(g==">"?w=[g,b,y,h.pos,u,l,r]:w=[g,b,y,h.pos],l++,o.push(w),g==="#"||g==="^")n.push(w);else if(g==="/"){if(T=n.pop(),!T)throw new Error('Unopened section "'+b+'" at '+y);if(T[1]!==b)throw new Error('Unclosed section "'+T[1]+'" at '+y)}else g==="name"||g==="{"||g==="&"?s=!0:g==="="&&m(b)}if(c(),T=n.pop(),T)throw new Error('Unclosed section "'+T[1]+'" at '+h.pos);return vwn(_wn(o))}function _wn(t){for(var e=[],r,n,o=0,i=t.length;o<i;++o)r=t[o],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(e.push(r),n=r));return e}function vwn(t){for(var e=[],r=e,n=[],o,i,a=0,s=t.length;a<s;++a)switch(o=t[a],o[0]){case"#":case"^":r.push(o),n.push(o),r=o[4]=[];break;case"/":i=n.pop(),i[5]=o[2],r=n.length>0?n[n.length-1][4]:e;break;default:r.push(o)}return e}function fte(t){this.string=t,this.tail=t,this.pos=0}function AJ(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function qb(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var iwn,NJ,uwn,cwn,fwn,mwn,hwn,ONt,gwn,ywn,$S,dte,Yge,ENt=v(()=>{iwn=Object.prototype.toString,NJ=Array.isArray||function(e){return iwn.call(e)==="[object Array]"};uwn=RegExp.prototype.test;cwn=/\S/;fwn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};mwn=/\s*/,hwn=/\s+/,ONt=/\s*=/,gwn=/\s*\}/,ywn=/#|\^|\/|>|\{|&|=|!/;fte.prototype.eos=function(){return this.tail===""};fte.prototype.scan=function(e){var r=this.tail.match(e);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};fte.prototype.scanUntil=function(e){var r=this.tail.search(e),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};AJ.prototype.push=function(e){return new AJ(e,this)};AJ.prototype.lookup=function(e){var r=this.cache,n;if(r.hasOwnProperty(e))n=r[e];else{for(var o=this,i,a,s,u=!1;o;){if(e.indexOf(".")>0)for(i=o.view,a=e.split("."),s=0;i!=null&&s<a.length;)s===a.length-1&&(u=TNt(i,a[s])||swn(i,a[s])),i=i[a[s++]];else i=o.view[e],u=TNt(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return j3e(n)&&(n=n.call(this.view)),n};qb.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};qb.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||$S.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=bwn(e,r),i&&n.set(o,a)),a};qb.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof AJ?r:new AJ(r,void 0);return this.renderTokens(a,s,n,e,o)};qb.prototype.renderTokens=function(e,r,n,o,i){for(var a="",s,u,l,c=0,d=e.length;c<d;++c)l=void 0,s=e[c],u=s[0],u==="#"?l=this.renderSection(s,r,n,o,i):u==="^"?l=this.renderInverted(s,r,n,o,i):u===">"?l=this.renderPartial(s,r,n,i):u==="&"?l=this.unescapedValue(s,r):u==="name"?l=this.escapedValue(s,r,i):u==="text"&&(l=this.rawValue(s)),l!==void 0&&(a+=l);return a};qb.prototype.renderSection=function(e,r,n,o,i){var a=this,s="",u=r.lookup(e[1]);function l(f){return a.render(f,r,n,i)}if(u){if(NJ(u))for(var c=0,d=u.length;c<d;++c)s+=this.renderTokens(e[4],r.push(u[c]),n,o,i);else if(typeof u=="object"||typeof u=="string"||typeof u=="number")s+=this.renderTokens(e[4],r.push(u),n,o,i);else if(j3e(u)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");u=u.call(r.view,o.slice(e[3],e[5]),l),u!=null&&(s+=u)}else s+=this.renderTokens(e[4],r,n,o,i);return s}};qb.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||NJ(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};qb.prototype.indentPartial=function(e,r,n){for(var o=r.replace(/[^ \t]/g,""),i=e.split(`
2026-01-05 13:03:55 +08:00
`),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=o+i[a]);return i.join(`
2026-02-24 07:55:02 +08:00
`)};qb.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=j3e(n)?n(e[1]):n[e[1]];if(a!=null){var s=e[6],u=e[5],l=e[4],c=a;u==0&&l&&(c=this.indentPartial(a,l,s));var d=this.parse(c,i);return this.renderTokens(d,r,n,c,o)}}};qb.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};qb.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||$S.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===$S.escape?String(i):o(i)};qb.prototype.rawValue=function(e){return e[1]};qb.prototype.getConfigTags=function(e){return NJ(e)?e:e&&typeof e=="object"?e.tags:void 0};qb.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!NJ(e))return e.escape};$S={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){dte.templateCache=t},get templateCache(){return dte.templateCache}},dte=new qb;$S.clearCache=function(){return dte.clearCache()};$S.parse=function(e,r){return dte.parse(e,r)};$S.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+awn(e)+'" was given as the first argument for mustache#render(template, view, partials)');return dte.render(e,r,n,o)};$S.escape=pwn;$S.Scanner=fte;$S.Context=AJ;$S.Writer=qb;Yge=$S});function PNt(){Yge.escape=t=>t}var w4,MNt,DJ,$3e,L3e,pte,F3e,Dy,S4,s1,C4=v(()=>{DQ();ENt();w4=t=>{let e=t.split(""),r=[],n=(i,a)=>{for(let s=a;s<e.length;s+=1)if(i.includes(e[s]))return s;return-1},o=0;for(;o<e.length;)if(e[o]==="{"&&o+1<e.length&&e[o+1]==="{")r.push({type:"literal",text:"{"}),o+=2;else if(e[o]==="}"&&o+1<e.length&&e[o+1]==="}")r.push({type:"literal",text:"}"}),o+=2;else if(e[o]==="{"){let i=n("}",o);if(i<0)throw new Error("Unclosed '{' in template.");r.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=n("{}",o),a=(i<0?e.slice(o):e.slice(o,i)).join("");r.push({type:"literal",text:a}),o=i<0?e.length:i}}return r},MNt=(t,e=[])=>{let r=[];for(let n of t)if(n[0]==="name"){let o=n[1].includes(".")?n[1].split(".")[0]:n[1];r.push({type:"variable",name:o})}else if(["#","&","^",">"].includes(n[0])){if(r.push({type:"variable",name:n[1]}),n[0]==="#"&&n.length>4&&Array.isArray(n[4])){let o=[...e,n[1]],i=MNt(n[4],o);r.push(...i)}}else r.push({type:"literal",text:n[1]});return r},DJ=t=>{PNt();let e=Yge.parse(t);return MNt(e)},$3e=(t,e)=>w4(t).reduce((r,n)=>{if(n.type==="variable"){if(n.name in e){let o=typeof e[n.name]=="string"?e[n.name]:JSON.stringify(e[n.name]);return r+o}throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),L3e=(t,e)=>(PNt(),Yge.render(t,e)),pte={"f-string":$3e,mustache:L3e},F3e={"f-string":w4,mustache:DJ},Dy=(t,e,r)=>{try{return pte[e](t,r)}catch(n){throw FL(n,"INVALID_PROMPT_INPUT")}},S4=(t,e)=>F3e[e](t),s1=(t,e,r)=>{if(!(e in pte)){let n=Object.keys(pte);throw new Error(`Invalid template format. Got \`${e}\`;
should be one of ${n}`)}try{let n=Object.fromEntries(r.map(o=>[o,"foo"]));Array.isArray(t)?t.forEach(o=>{if(o.type==="text"&&"text"in o&&typeof o.text=="string")Dy(o.text,e,n);else if(o.type==="image_url"){if(typeof o.image_url=="string")Dy(o.image_url,e,n);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;Dy(i,e,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Dy(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var mu,Qge=v(()=>{cte();C4();mu=class mte extends a1{constructor(r){super(r);x(this,"template");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);x(this,"additionalContentFields");if(r.templateFormat==="mustache"&&r.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,r),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),s1(this.template,this.templateFormat,n)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(r){let n=await this.mergePartialAndUserVariables(r);return Dy(this.template,this.templateFormat,n)}static fromExamples(r,n,o,i=`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`,a=""){let s=[a,...r,n].join(i);return new mte({inputVariables:o,template:s})}static fromTemplate(r,n){let{templateFormat:o="f-string",...i}=n??{},a=new Set;return S4(r,o).forEach(s=>{s.type==="variable"&&a.add(s.name)}),new mte({inputVariables:[...a],templateFormat:o,template:r,...i})}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new mte(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(r){if(!r.template)throw new Error("Prompt template must have a template");return new mte({inputVariables:r.input_variables,template:r.template,templateFormat:r.template_format})}}});var jJ,k3e=v(()=>{lte();IJ();C4();jJ=class RNt extends jS{constructor(r){super(r);x(this,"lc_namespace",["langchain_core","prompts","image"]);x(this,"template");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);x(this,"additionalContentFields");if(this.template=r.template,this.templateFormat=r.templateFormat??this.templateFormat,this.validateTemplate=r.validateTemplate??this.validateTemplate,this.additionalContentFields=r.additionalContentFields,this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),s1([{type:"image_url",image_url:this.template}],this.templateFormat,n)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new RNt(i)}async format(r){let n={};for(let[s,u]of Object.entries(this.template))typeof u=="string"?n[s]=Dy(u,this.templateFormat,r):n[s]=u;let o=r.url||n.url,i=r.detail||n.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 a={url:o};return i&&(a.detail=i),a}async formatPromptValue(r){let n=await this.format(r);return new N3e(n)}}});function q3e(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")S4(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?S4(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...q3e(o,e));else typeof n=="object"&&n!==null&&r.push(...q3e(n,e));return Array.from(new Set(r))}function U3e(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=Dy(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(Dy(s,r,e)):typeof s=="object"&&a.push(U3e(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=U3e(i,e,r):n[o]=i;return n}var hte,B3e=v(()=>{Pg();C4();hte=class extends Go{constructor(e){let r=e.templateFormat??"f-string",n=q3e(e.template,r);super({inputVariables:n,...e});x(this,"lc_namespace",["langchain_core","prompts","dict"]);x(this,"lc_serializable",!0);x(this,"template");x(this,"templateFormat");x(this,"inputVariables");this.template=e.template,this.templateFormat=r,this.inputVariables=n}static lc_name(){return"DictPromptTemplate"}async format(e){return U3e(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function wwn(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Swn(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 Cwn(t){return typeof t.formatMessages=="function"}function xwn(t,e){if(Cwn(t)||xg(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)==="}}
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},z3e=class extends gte{constructor(e){"prompt"in e||(e={prompt:e});super(e);x(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},yte=class extends jS{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){let e=await this.formatMessages(t);return new ute(e)}},V3e=class extends z3e{constructor(e,r){"prompt"in e||(e={prompt:e,role:r});super(e);x(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new Td(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(mu.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};H3e=class extends gte{constructor(e,r){"prompt"in e||(e={prompt:e});super(e);x(this,"lc_namespace",["langchain_core","prompts","chat"]);x(this,"lc_serializable",!0);x(this,"inputVariables",[]);x(this,"additionalOptions",{});x(this,"prompt");x(this,"messageClass");x(this,"chatMessageClass");if(this.prompt=e.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(o=>{"inputVariables"in o&&(n=n.concat(o.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=r??this.additionalOptions}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){let r=this.constructor;if(r._messageClass()){let n=r._messageClass();return new n({content:e})}else if(r.chatMessageClass){let n=r.chatMessageClass();return new n({content:e,role:this.getRoleFromMessageClass(n.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,r){if(typeof e=="string")return new this(mu.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(mu.fromTemplate(o,r));else if(o!==null)if(wwn(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(mu.fromTemplate(i,a))}else if(Swn(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=DJ(i):u=w4(i);let l=u.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
2026-01-05 13:03:55 +08:00
Got: ${l}
2026-02-24 07:55:02 +08:00
From: ${i}`);s=[l[0]]}else s=[];i={url:i},a=new jJ({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=DJ(i.url):u=w4(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new jJ({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");n.push(a)}else typeof o=="object"&&n.push(new hte({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof a1){let r=await this.prompt.format(e);return this.createMessage(r)}else{let r=[];for(let n of this.prompt){let o={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(let i of n.inputVariables)o||(o={[i]:e[i]}),o={...o,[i]:e[i]};if(n instanceof a1){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),i!==""&&r.push({...a,type:"text",text:i})}else if(n instanceof jJ){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"image_url",image_url:i})}else if(n instanceof hte){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,...i})}}return this.createMessage(r)}}async formatMessages(e){return[await this.format(e)]}},$_=class extends H3e{static _messageClass(){return qs}static lc_name(){return"HumanMessagePromptTemplate"}},tye=class extends H3e{static _messageClass(){return Pn}static lc_name(){return"AIMessagePromptTemplate"}},LS=class extends H3e{static _messageClass(){return Od}static lc_name(){return"SystemMessagePromptTemplate"}};Ah=class eye extends yte{constructor(r){super(r);x(this,"promptMessages");x(this,"validateTemplate",!0);x(this,"templateFormat","f-string");if(r.templateFormat==="mustache"&&r.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,r),this.validateTemplate){let n=new Set;for(let u of this.promptMessages)if(!(u instanceof id))for(let l of u.inputVariables)n.add(l);let o=this.inputVariables,i=new Set(this.partialVariables?o.concat(Object.keys(this.partialVariables)):o),a=new Set([...i].filter(u=>!n.has(u)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are not used in any of the prompt messages.`);let s=new Set([...n].filter(u=>!i.has(u)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` 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(r,n){if(typeof r.content=="string")return r;let o=await Promise.all(r.content.map(async i=>{if(i.type!=="image_url")return i;let a="";typeof i.image_url=="string"?a=i.image_url:typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url&&typeof i.image_url.url=="string"&&(a=i.image_url.url);let u=await mu.fromTemplate(a,{templateFormat:this.templateFormat}).format(n);return typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url?i.image_url.url=u:i.image_url=u,i}));return r.content=o,r}async formatMessages(r){let n=await this.mergePartialAndUserVariables(r),o=[];for(let i of this.promptMessages)if(i instanceof id)o.push(await this._parseImagePrompts(i,n));else{let a;this.templateFormat==="mustache"?a={...n}:a=i.inputVariables.reduce((u,l)=>{if(!(l in n)&&!(Twn(i)&&i.optional))throw FL(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return u[l]=n[l],u},{});let s=await i.formatMessages(a);o=o.concat(s)}return o}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new eye(i)}static fromTemplate(r,n){let o=mu.fromTemplate(r,n),i=new $_({prompt:o});return this.fromMessages([i])}static fromMessages(r,n){let o=r.reduce((s,u)=>s.concat(u instanceof eye?u.promptMessages:[xwn(u,n)]),[]),i=r.reduce((s,u)=>u
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`);x(this,"prefix","");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);if(Object.assign(this,r),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),s1(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(r){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(r);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new W3e(i)}async format(r){let n=await this.mergePartialAndUserVariables(r),o=await this.getExamples(n),i=await Promise.all(o.map(s=>this.examplePrompt.format(s))),a=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return Dy(a,this.templateFormat,n)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(r){let{example_prompt:n}=r;if(!n)throw new Error("Missing example prompt");let o=await mu.deserialize(n),i;if(Array.isArray(r.examples))i=r.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new W3e({inputVariables:r.input_variables,examplePrompt:o,examples:i,exampleSeparator:r.example_separator,prefix:r.prefix,suffix:r.suffix,templateFormat:r.template_format})}},ANt=class NNt extends yte{constructor(r){super(r);x(this,"lc_serializable",!0);x(this,"examples");x(this,"exampleSelector");x(this,"examplePrompt");x(this,"suffix","");x(this,"exampleSeparator",`
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
`);x(this,"prefix","");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);if(this.examples=r.examples,this.examplePrompt=r.examplePrompt,this.exampleSeparator=r.exampleSeparator??`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`,this.exampleSelector=r.exampleSelector,this.prefix=r.prefix??"",this.suffix=r.suffix??"",this.templateFormat=r.templateFormat??"f-string",this.validateTemplate=r.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),s1(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}async getExamples(r){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(r);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(r){let n=await this.mergePartialAndUserVariables(r),o=await this.getExamples(n);o=o.map(a=>{let s={};return this.examplePrompt.inputVariables.forEach(u=>{s[u]=a[u]}),s});let i=[];for(let a of o){let s=await this.examplePrompt.formatMessages(a);i.push(...s)}return i}async format(r){let n=await this.mergePartialAndUserVariables(r),o=await this.getExamples(n),a=(await Promise.all(o.map(u=>this.examplePrompt.formatMessages(u)))).flat().map(u=>u.content),s=[this.prefix,...a,this.suffix].join(this.exampleSeparator);return Dy(s,this.templateFormat,n)}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new NNt(i)}}});var jNt,$Nt=v(()=>{IJ();bte();jNt=class rye extends jS{constructor(r){super({...r,inputVariables:[]});x(this,"pipelinePrompts");x(this,"finalPrompt");this.pipelinePrompts=r.pipelinePrompts,this.finalPrompt=r.finalPrompt,this.inputVariables=this.computeInputValues()}static lc_name(){return"PipelinePromptTemplate"}computeInputValues(){let r=this.pipelinePrompts.map(o=>o.name),n=this.pipelinePrompts.map(o=>o.prompt.inputVariables.filter(i=>!r.includes(i))).flat();return[...new Set(n)]}static extractRequiredInputValues(r,n){return n.reduce((o,i)=>(o[i]=r[i],o),{})}async formatPipelinePrompts(r){let n=await this.mergePartialAndUserVariables(r);for(let{name:o,prompt:i}of this.pipelinePrompts){let a=rye.extractRequiredInputValues(n,i.inputVariables);i instanceof Ah?n[o]=await i.formatMessages(a):n[o]=await i.format(a)}return rye.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(r){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(r))}async format(r){return this.finalPrompt.format(await this.formatPipelinePrompts(r))}async partial(r){let n={...this};return n.inputVariables=this.inputVariables.filter(o=>!(o in r)),n.partialVariables={...this.partialVariables??{},...r},new rye(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}}});function LNt(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function Own(t){return typeof t=="object"&&t!=null&&"lc_id"in t&&Array.isArray(t.lc_id)&&t.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var FNt,qNt=v(()=>{Pg();bte();FNt=class kNt extends Ah{constructor(r){super(r);x(this,"schema");x(this,"method");x(this,"lc_namespace",["langchain_core","prompts","structured"]);this.schema=r.schema,this.method=r.method}get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}pipe(r){if(LNt(r))return super.pipe(r.withStructuredOutput(this.schema));if(Own(r)&&LNt(r.bound))return super.pipe(new DS({bound:r.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:r.kwargs??{},config:r.config,configFactories:r.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(r,n,o){return kNt.fromMessages(r,{schema:n,method:o})}}});var E
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`)});function bc(t,e){let r=`atom${++Rwn}`,n={toString(){return(zl.env?zl.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=Iwn,n.write=Awn),e&&(n.write=e),n}function Iwn(t){return t(this)}function Awn(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var zl,Rwn,UNt,K3e,G3e,iye,Z3e,Nwn,Dwn,Y3e,BNt,oye,HNt,zNt,LJ,X3e,jwn,$wn,VNt,fF,WNt,pF,vte,JNt,Q3e=v(()=>{zl={},Rwn=0;UNt=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,K3e=t=>"init"in t,G3e=t=>!!t.write,iye=new WeakMap,Z3e=t=>{var e;return Y3e(t)&&!((e=iye.get(t))!=null&&e[1])},Nwn=(t,e)=>{let r=iye.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if((zl.env?zl.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},Dwn=t=>{if(iye.has(t))return;let e=[new Set,!1];iye.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},Y3e=t=>typeof t?.then=="function",BNt=t=>"v"in t||"e"in t,oye=t=>{if("e"in t)throw t.e;if((zl.env?zl.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},HNt=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},zNt=(t,e,r,n,o)=>{var i;if((zl.env?zl.env.MODE:void 0)!=="production"&&n===e)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),Z3e(r.v)&&HNt(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&jwn(t,n,e)},LJ=()=>[new Map,new Map,new Set],X3e=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},jwn=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},$wn=(t,e)=>t[0].get(e),VNt=(t,e)=>{t[2].add(e)},fF=t=>{let e,r=!1,n=o=>{try{o()}catch(i){r||(e=i,r=!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(a=>{var s;return(s=a.m)==null?void 0:s.l.forEach(n)}),i.forEach(n)}if(r)throw e},WNt=(...[t,e,r,n])=>{let o;(zl.env?zl.env.MODE:void 0)!=="production"&&(o=new Set);let i=(_,w,T)=>{let O="v"in w,E=w.v,P=Z3e(w.v)?w.v:null;if(Y3e(T)){Dwn(T);for(let R of w.d.keys())HNt(_,T,t(R));w.v=T,delete w.e}else w.v=T,delete w.e;(!O||!Object.is(E,w.v))&&(++w.n,P&&Nwn(P,T))},a=(_,w,T)=>{var O;let E=t(w);if(BNt(E)&&(E.m&&!T?.has(w)||Array.from(E.d).every(([V,k])=>a(_,V,T).n===k)))return E;E.d.clear();let P=!0,R=V=>{if(UNt(w,V)){let X=t(V);if(!BNt(X))if(K3e(V))i(V,X,V.init);else throw new Error("no atom init");return oye(X)}let k=a(_,V,T);try{return oye(k)}finally{if(P)zNt(_,w,E,V,k);else{let X=LJ();zNt(X,w,E,V,k),p(X,w,E),fF(X)}}},I,N,z={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(zl.env?zl.env.MODE:void 0)!=="production"&&!G3e(w)&&console.warn("setSelf function cannot be used with read-only atom"),!N&&G3e(w)&&(N=(...V)=>{if((zl.env?zl.env.MODE:void 0)!=="production"&&P&&console.warn("setSelf function cannot be called in sync"),!P)return f(w,...V)}),N}};try{let V=e(w,R,z);if(i(w,E,V),Y3e(V)){(O=V.onCancel)==null||O.call(V,()=>I?.abort());let k=()=>{if(E.m){let X=LJ();p(X,w,E),fF(X)}};V.then(k,k)}return E}catch(V){return delete E.v,E.e=V,++E.n,E}finally{P=!1}},s=_=>oye(a(void 0,_)),u=(_,w,T)=>{var O,E;let P=new Map;for(let R of((O=T.m)==null?void 0:O.t)||[])P.set(R,t(R));for(let R of T.p)P.set(R,t(R));return(E=$wn(_,w))==null||E.forEach(R=>{P.set(R,t(R))}),P};function l(_,w,T){let O=[],E=new Set,P=new Set,R=[[w,T]];for(;R.length>0;){let[I,N]=R[R.length-1];if(P.has(I)){R.pop();continue}if(E.has(I)){O.push([I,N,N.n]),P.add(I),R.pop();continue}E.add(I);for(let[z,V]of u(_,I,N))I!==z&&!E.has(z)&&R.push([z,V])}return[O,P]}let c=(_,w,T)=>{let[O,E]=l(_,w,T),P=new Set([w]);for(let R=O.length-1;R>=0;--R){let[I,N,z]=O[R],V=!1;for(let k of N.d.keys())if(k!==I&&P.has(k)){V=!0;break}V&&(a(_,I,E),p(_,I,N),z!==N.n&&(X3e(_,I,N),P.add(I))),E.delete(I)}},d=(_,w,...T)=>{let O=!0,E=R=>oye(a(_,R)),P=(R,...I)=>{let N=t(R);try{if(UNt(w,R)){if(!K3e(R))throw new Error("atom not writable");let z=N.n,V=I[0];i(R,N,V),p(_,R,N),z!==N.n&&(X3e(_,R,N),c(_,R,N));return}else return d(_,R,...I)}finally{O||fF(_)}};try{return r(w,E,P,...T)}finally{O=!1}},f=(_,...w)=>{let T=LJ();try{return d
`)}return JSON.stringify(t)??String(t)}catch{return String(t)}}var cWe=v(()=>{});var dWe,Im,O4=v(()=>{cWe();Bt();Ye();dWe=class t{constructor(){this.maxLines=500;this.maxLineChars=8e3;this.buffer=[];this.initialized=!1;this.flushing=!1}static getInstance(){return t.instance||(t.instance=new t),t.instance}getLogPath(){return"copilot/copilot-log.md"}async ensureInitialized(){this.initialized||(this.initialized=!0)}hasVault(){try{return typeof app<"u"&&!!app.vault?.adapter}catch{return!1}}sanitizeForSingleLine(e){if(e instanceof Error){let r=zr(e,!0);return this.escapeAngleBrackets(this.collapseToSingleLine(r))}if(typeof e=="string")return this.escapeAngleBrackets(this.collapseToSingleLine(e));try{let r=JSON.stringify(e);return this.escapeAngleBrackets(this.collapseToSingleLine(r??String(e)))}catch{return this.escapeAngleBrackets(this.collapseToSingleLine(String(e)))}}collapseToSingleLine(e){let r=e.replace(/[\r\n]+/g,"\\n").replace(/\t/g," ");return r.length<=this.maxLineChars?r:r.slice(0,this.maxLineChars)+` \u2026 [truncated ${r.length-this.maxLineChars} chars]`}async append(e,...r){await this.ensureInitialized();let n=new Date().toISOString(),o=r.map(a=>this.sanitizeForSingleLine(a)),i=`${n} ${e} ${o.join(" ")}`.trim();this.buffer.push(i),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}escapeAngleBrackets(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}async appendMarkdownBlock(e){if(await this.ensureInitialized(),!(!Array.isArray(e)||e.length===0))for(let r of e){let n=typeof r=="string"?r:String(r??"");this.buffer.push(n),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}}async flush(){if(this.hasVault()&&!this.flushing){this.flushing=!0;try{let e=this.getLogPath();if(await app.vault.adapter.exists(e)){let r=this.buffer.join(`
2026-01-05 13:03:55 +08:00
`)+(this.buffer.length?`
2026-02-24 07:55:02 +08:00
`:"");await app.vault.adapter.write(e,r)}}catch{}finally{this.flushing=!1}}}async clear(){if(this.buffer=[],!!this.hasVault())try{let e=this.getLogPath();await app.vault.adapter.exists(e)&&await app.vault.adapter.remove(e)}catch{}}sanitizeSettingsForLog(){let e=te();return this.removeKeysRecursive(e)}removeKeysRecursive(e){if(e==null)return e;if(Array.isArray(e))return e.map(r=>this.removeKeysRecursive(r));if(typeof e=="object"&&e.constructor===Object){let r={},n=e;for(let[o,i]of Object.entries(n))/apiKey$/i.test(o)||/licenseKey$/i.test(o)||/_api_key$/i.test(o)||/_license_key$/i.test(o)||/orgId$/i.test(o)||/instanceName$/i.test(o)||/deploymentName$/i.test(o)||/apiVersion$/i.test(o)||(r[o]=this.removeKeysRecursive(i));return r}return e}async openLogFile(){if(!this.hasVault())return;let e=this.getLogPath(),r=[...this.buffer];try{let o=this.sanitizeSettingsForLog(),a=["","## Settings","```json",...JSON.stringify(o,null,2).split(`
2026-01-05 13:03:55 +08:00
`),"```"];r.push(...a)}catch{}try{let o=r.join(`
`)+(r.length?`
2026-02-24 07:55:02 +08:00
`:""),i=e.includes("/")?e.split("/").slice(0,-1).join("/"):"";i&&await $c(i),await app.vault.adapter.exists(e)?await app.vault.adapter.write(e,o):await app.vault.create(e,o)}catch{}let n=app.vault.getAbstractFileByPath(e);try{n&&await app.workspace.getLeaf(!0).openFile(n)}catch{}}},Im=dWe.getInstance()});function F(...t){te().debug&&console.log(...t),Im.append("INFO",...t)}function ne(...t){te().debug&&console.error(...t),Im.append("ERROR",...t)}function Te(...t){te().debug&&console.warn(...t),Im.append("WARN",...t)}function fye(t){Im.appendMarkdownBlock(t)}function p1t(t,e){if(te().debug)try{if(typeof console.table=="function"){Array.isArray(e)&&e.length>0?console.table(t,e):console.table(t);return}}catch{}F("Table:",JSON.stringify(t))}var Xe=v(()=>{Ye();O4()});var m1t=S((fWe,BJ)=>{(function(t,e){typeof fWe=="object"&&typeof BJ<"u"?BJ.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(fWe,function(){"use strict";var t;function e(){return t.apply(null,arguments)}function r(C){t=C}function n(C){return C instanceof Array||Object.prototype.toString.call(C)==="[object Array]"}function o(C){return C!=null&&Object.prototype.toString.call(C)==="[object Object]"}function i(C,M){return Object.prototype.hasOwnProperty.call(C,M)}function a(C){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(C).length===0;var M;for(M in C)if(i(C,M))return!1;return!0}function s(C){return C===void 0}function u(C){return typeof C=="number"||Object.prototype.toString.call(C)==="[object Number]"}function l(C){return C instanceof Date||Object.prototype.toString.call(C)==="[object Date]"}function c(C,M){var D=[],q,G=C.length;for(q=0;q<G;++q)D.push(M(C[q],q));return D}function d(C,M){for(var D in M)i(M,D)&&(C[D]=M[D]);return i(M,"toString")&&(C.toString=M.toString),i(M,"valueOf")&&(C.valueOf=M.valueOf),C}function f(C,M,D,q){return U0t(C,M,D,q,!0).utc()}function p(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function m(C){return C._pf==null&&(C._pf=p()),C._pf}var h;Array.prototype.some?h=Array.prototype.some:h=function(C){var M=Object(this),D=M.length>>>0,q;for(q=0;q<D;q++)if(q in M&&C.call(this,M[q],q,M))return!0;return!1};function y(C){if(C._isValid==null){var M=m(C),D=h.call(M.parsedDateParts,function(G){return G!=null}),q=!isNaN(C._d.getTime())&&M.overflow<0&&!M.empty&&!M.invalidEra&&!M.invalidMonth&&!M.invalidWeekday&&!M.weekdayMismatch&&!M.nullInput&&!M.invalidFormat&&!M.userInvalidated&&(!M.meridiem||M.meridiem&&D);if(C._strict&&(q=q&&M.charsLeftOver===0&&M.unusedTokens.length===0&&M.bigHour===void 0),Object.isFrozen==null||!Object.isFrozen(C))C._isValid=q;else return q}return C._isValid}function g(C){var M=f(NaN);return C!=null?d(m(M),C):m(M).userInvalidated=!0,M}var b=e.momentProperties=[],_=!1;function w(C,M){var D,q,G,fe=b.length;if(s(M._isAMomentObject)||(C._isAMomentObject=M._isAMomentObject),s(M._i)||(C._i=M._i),s(M._f)||(C._f=M._f),s(M._l)||(C._l=M._l),s(M._strict)||(C._strict=M._strict),s(M._tzm)||(C._tzm=M._tzm),s(M._isUTC)||(C._isUTC=M._isUTC),s(M._offset)||(C._offset=M._offset),s(M._pf)||(C._pf=m(M)),s(M._locale)||(C._locale=M._locale),fe>0)for(D=0;D<fe;D++)q=b[D],G=M[q],s(G)||(C[q]=G);return C}function T(C){w(this,C),this._d=new Date(C._d!=null?C._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),_===!1&&(_=!0,e.updateOffset(this),_=!1)}function O(C){return C instanceof T||C!=null&&C._isAMomentObject!=null}function E(C){e.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+C)}function P(C,M){var D=!0;return d(function(){if(e.deprecationHandler!=null&&e.deprecationHandler(null,C),D){var q=[],G,fe,De,sn=arguments.length;for(fe=0;fe<sn;fe++){if(G="",typeof arguments[fe]=="object"){G+=`
[`+fe+"] ";for(De in arguments[0])i(arguments[0],De)&&(G+=De+": "+arguments[0][De]+", ");G=G.slice(0,-2)}else G=arguments[fe];q.push(G)}E(C+`
Arguments: `+Array.prototype.slice.call(q).join("")+`
`+new Error().stack),D=!1}return M.apply(this,arguments)},M)}var R={};function I(C,M){e.deprecationHandler!=null&&e.deprecationHandler(C,M),R[C]||(E(M),R[C]=!0)}e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;function N(C){return typeof Function<"u"&&C instanceof Function||Object.prototype.toString.call(C)==="[object Function]"}function z(C){var M,D;for(D in C)i(C,D)&&(M=C[D],N(M)?this[D]=M:this["_"+D]=M);this._config=C,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function V(C,M){var D=d({},C),q;for(q in M)i(M,q)&&(o(C[q])&&o(M[q])?(D[q]={},d(D[q],C[q]),d(D[q],M[q])):M[q]!=null?D[q]=M[q]:delete D[q]);for(q in C)i(C,q)&&!i(M,q)&&o(C[q])&&(D[q]=d({},D[q]));return D}function k(C){C!=null&&this.set(C)}var X;Object.keys?X=Object.keys:X=function(C){var M,D=[];for(M in C)i(C,M)&&D.push(M);return D};var B={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function Q(C,M,D){var q=this._calendar[C]||this._calendar.sameElse;return N(q)?q.call(M,D):q}function Y(C,M,D){var q=""+Math.abs(C),G=M-q.length,fe=C>=0;return(fe?D?"+":"":"-")+Math.pow(10,Math.max(0,G)).toString().substr(1)+q}var K=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,oe=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,ue={},de={};function L(C,M,D,q){var G=q;typeof q=="string"&&(G=function(){return this[q]()}),C&&(de[C]=G),M&&(de[M[0]]=function(){return Y(G.apply(this,arguments),M[1],M[2])}),D&&(de[D]=function(){return this.localeData().ordinal(G.apply(this,arguments),C)})}function W(C){return C.match(/\[[\s\S]/)?C.replace(/^\[|\]$/g,""):C.replace(/\\/g,"")}function ie(C){var M=C.match(K),D,q;for(D=0,q=M.length;D<q;D++)de[M[D]]?M[D]=de[M[D]]:M[D]=W(M[D]);return function(G){var fe="",De;for(De=0;De<q;De++)fe+=N(M[De])?M[De].call(G,C):M[De];return fe}}function j(C,M){return C.isValid()?(M=A(M,C.localeData()),ue[M]=ue[M]||ie(M),ue[M](C)):C.localeData().invalidDate()}function A(C,M){var D=5;function q(G){return M.longDateFormat(G)||G}for(oe.lastIndex=0;D>=0&&oe.test(C);)C=C.replace(oe,q),oe.lastIndex=0,D-=1;return C}var U={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function H(C){var M=this._longDateFormat[C],D=this._longDateFormat[C.toUpperCase()];return M||!D?M:(this._longDateFormat[C]=D.match(K).map(function(q){return q==="MMMM"||q==="MM"||q==="DD"||q==="dddd"?q.slice(1):q}).join(""),this._longDateFormat[C])}var re="Invalid date";function Z(){return this._invalidDate}var le="%d",Ce=/\d{1,2}/;function He(C){return this._ordinal.replace("%d",C)}var lt={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function qe(C,M,D,q){var G=this._relativeTime[D];return N(G)?G(C,M,D,q):G.replace(/%d/i,C)}function Nt(C,M){var D=this._relativeTime[C>0?"future":"past"];return N(D)?D(M):D.replace(/%s/i,M)}var mt={};function Ot(C,M){var D=C.toLowerCase();mt[D]=mt[D+"s"]=mt[M]=C}function je(C){return typeof C=="string"?mt[C]||mt[C.toLowerCase()]:void 0}function Gr(C){var M={},D,q;for(q in C)i(C,q)&&(D=je(q),D&&(M[D]=C[q]));return M}var ct={};function ze(C,M){ct[C]=M}function ht(C){var M=[],D;for(D in C)i(C,D)&&M.push({unit:D,priority:ct[D]});return M.sort(function(q,G){return q.priority-G.priority}),M}function $e(C){return C%4===0&&C%100!==0||C%400===0}function Ue(C){return C<0?Math.ceil(C)||0:Math.floor(C)}function Ve(C){var M=+C,D=0;return M!==0&&isFinite(M)&&(D=Ue(M)),D}function Kt(C,M){return function(D){return D!=null?(iu(this,C,D),e.updateOffset(this,M),this):so(this,C)}}function so(C,M){return C.isValid()?C._d["get"+(C._isUTC?"UTC":"")+M]():NaN}function iu(C,M,D){C.isValid()&&!isNaN(D)&&(M==="FullYe
2026-01-21 08:46:13 +08:00
`)?o.slice(2):o.startsWith(`
2026-02-24 07:55:02 +08:00
`)||o.startsWith("\r")?o.slice(1):o}}return t}function gO(t,e=!0){let r=app.metadataCache.getFileCache(t),n=r?.frontmatter?.tags,o=new Set;if(!e){let i=r?.tags?.map(a=>a.tag);i&&i.forEach(a=>o.add(VJ(a)))}return n&&(Array.isArray(n)?n.forEach(i=>{typeof i=="string"&&o.add(VJ(i))}):typeof n=="string"&&o.add(VJ(n))),Array.from(o)}function mye(t,e,r){if(e.length===0)return[];e=e.map(i=>VJ(i));let n=r&&r.length>0?r:Ote(t,"/"),o=[];for(let i of n){let a=gO(i);e.some(s=>a.includes(s))&&o.push(i)}return o}async function $c(t){let e=(0,$y.normalizePath)(t).replace(/^\/+/,"").replace(/\/+$/,"");if(!e)return;let r=e.split("/").filter(Boolean),n="";for(let o of r){n=n?`${n}/${o}`:o;let i=app.vault.getAbstractFileByPath(n);if(i){if(i instanceof $y.TFile)throw new Error(`Path conflict: "${n}" exists as a file, expected folder.`);continue}await app.vault.adapter.mkdir(n)}}async function WJ(t,e){return t.extension!="md"&&t.extension!="canvas"?null:await e.cachedRead(t)}function hye(t){return t.basename}function yO(t){return t?dSn.includes(t.extension):!1}function zb(t){return t==="copilot_plus"||t==="project"}function JJ(t,e){return t?t.extension==="md"||t.extension==="canvas"?!0:zb(e):!1}function w1t(t,e){return!t||!e?!1:t.includes(hWe)&&e.includes(hWe)||t==="small"&&e==="cohereai"||t==="cohereai"&&e==="small"?!0:t===e}function gye(t){let e=[],{history:r}=t;for(let n=0;n<r.length;n+=2){let o=r[n]?.content||"",i=r[n+1]?.content||"";e.push({role:"user",content:o},{role:"assistant",content:i})}return e}function S1t(t,e){let r=new Map;return t.forEach(n=>{let o=e.getAbstractFileByPath(n);if(o instanceof $y.TFile)r.set(o.path,o);else{let a=e.getMarkdownFiles().filter(s=>s.basename===n);a.length>0&&(fSn(n,e)?r.set(a[0].path,a[0]):console.warn(`Found multiple files with title "${n}". Expected a full path for duplicate titles.`))}}),Array.from(r.values())}function kS(t,e){let r=/\[\[(.*?)\]\]/g,n=t.match(r);if(!n)return[];let o=n.map(i=>i.slice(2,-2));return S1t(o,e)}function C1t(t,e){let r=/\{\[\[(.*?)\]\]\}/g,n=t.match(r);if(!n)return[];let o=n.map(i=>i.slice(3,-3));return S1t(o,e)}function fSn(t,e){return e.getMarkdownFiles().filter(n=>n.basename===t).length===1}function x1t(t){return t=t.trim(),t.startsWith("[[")&&t.endsWith("]]")?`${t.slice(2,-2).trim()}.md`:t}function T1t(t){let e=new Set;return t.forEach(r=>{r.metadata?.title&&e.add(r.metadata?.title)}),Array.from(e)}function gWe(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 r=yWe(e);return r?/^[a-zA-Z0-9_-]{11}$/.test(r)?{isValid:!0,videoId:r}:{isValid:!1,error:"Invalid YouTube video ID"}:{isValid:!1,error:"Invalid YouTube URL format"}}function yWe(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 r of e){let n=t.match(r);if(n&&n[1])return n[1]}return null}catch{return null}}function O1t(t){return`https://www.youtube.com/watch?v=${t}`}function E1t(t){return gWe(t).isValid}function P1t(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 M1t(t){let e=t.matchAll(new RegExp(pSn,"g"));return Array.from(e,r=>r[0])}async function gl(t,e={}){let{throwOnHttpError:r=!0}=e,n=new Headers(e.headers),o=Object.fromEntries(n.entries());delete o["content-length"],F("safeFetch request");let i=e.method?.toUpperCase()||"POST",s=await(0,$y.requestUrl)({url:t,contentType:"application/json",headers:o,method:i,...["POST","PUT","PATCH"].includes(i)&&{body:e.body?.toString()},throw:!1});if(r&&s.status>=400){let u;try{u=typeof s.json=="string"?JSON.parse(s.json):s.json}catch{try{u=typeof s.text=="string"?JSON.parse(s.text):s.text}catch{u=null}}let l=new Error(mWe.REQUEST_FAILED(s.status));if(l.json=u,u?.detail?.reason==="Invalid license key"||u?.reason==="Invalid license key")l.message="Invalid license key";else if
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`),e=e.trim(),e}async function KJ(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new $y.Notice("No active leaf found.");return}if(r.view instanceof $y.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof $y.MarkdownView)){new $y.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=f1(t),s=a.split(`
`),u=(b,_)=>{let w=_.length-1;return w===0?{line:b.line,ch:b.ch+(_[0]?.length??0)}:{line:b.line+w,ch:_[_.length-1]?.length??0}},l=()=>{let b=e?o:i;n.replaceRange(a,b,i),n.setSelection(b,u(b,s))},c=()=>{n.focus(),new $y.Notice("Message inserted into the active note.")},d=n.cm;if(!(d?.state?.doc&&typeof d.dispatch=="function")){l(),c();return}let{from:p,to:m}=d.state.selection.main,h=e?p:m,y=d.state.toText(a),g=h+y.length;try{d.dispatch({changes:{from:h,to:m,insert:y},selection:{anchor:h,head:g}})}catch(b){Te("CM6 dispatch failed, falling back to Obsidian API",b),l()}c()}function yye(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function bye(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if(r[o]>n[o])return!0;if(r[o]<n[o])return!1}return!1}async function I1t(){try{return{version:(await(0,$y.requestUrl)({url:"https://api.github.com/repos/logancyang/obsidian-copilot/releases/latest",method:"GET"})).json.tag_name.replace("v",""),error:null}}catch(t){return{version:null,error:t instanceof Error?t.message:"Failed to check for updates"}}}function Pte(t){if(typeof t=="string")return t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4");let e=t.modelName||t.model||"";return e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")}function hSn(t){return typeof t=="string"?t.startsWith("gpt-5"):(t.modelName||t.model||"").startsWith("gpt-5")}function GJ(t){let e=typeof t=="string"?t:t.modelName||t.model||"",r=Pte(e),n=hSn(e),o=e.startsWith("claude-3-7-sonnet")||e.startsWith("claude-sonnet-4")||e.startsWith("claude-opus-4");return{isOSeries:r,isGPT5:n,isThinkingEnabled:o}}function Mte(t,e="system"){return Pte(t)?"human":e}function bWe(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","github-copilot","copilot-plus","copilot-plus-jina"];return Object.keys(QC).filter(e=>!t.includes(e))}function XJ(t,e){if(t.provider==="amazon-bedrock")return t.apiKey||e.amazonBedrockApiKey?{hasApiKey:!0}:{hasApiKey:!1,errorNotice:"Amazon Bedrock API key is missing. Please add a key in Settings > API Keys or update the model configuration."};if(t.provider==="github-copilot")return!(t.apiKey||e.githubCopilotToken||e.githubCopilotAccessToken)?{hasApiKey:!1,errorNotice:"GitHub Copilot is not authenticated. Please connect it in Settings > Copilot > Basic Tab > Set Keys."}:{hasApiKey:!0};let r=!!bWe().find(o=>o===t.provider),n=!Bb(t.provider,t);return r&&n?{hasApiKey:!1,errorNotice:`Please configure API Key for ${t.name} in settings first.
Path: Settings > copilot plugin > Basic Tab > Set Keys`}:{hasApiKey:!0}}function M4(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function Rte(t){let r=M4(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function _ye(t){return M4(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function A1t(){return crypto.randomUUID()}async function Vb(t){let e=console.warn;try{return console.warn=function(...r){if(!(r[0]?.includes&&(r[0].includes("Failed to calculate number of tokens")||r[0].includes("Unknown model"))))return e.apply(console,r)},await t()}finally{console.warn=e}}async function N1t(t,e,r="Operation"){let{TimeoutError:n}=await Promise.resolve().then(()=>(lw(),g1t)),o=new AbortController,i=setTimeout(()=>{o.abort()},e);try{return await Promise.race([t(o.signal),new Promise((a,s)=>{o.signal.addEventListener("abort",()=>{s(new n(r,e))})})])}finally{clearTimeout(i)}}function Ite(){let t=app.workspace.getActiveViewOfType($y.MarkdownView);return t?t.getState().source===!0:!0}function P4(t){return new TextEncoder().encode(t).length}function Tte(t,e){if(e<=0)return"";let r=new TextEncoder;if(r.encode(t).length<=e)return t;let o=0,i=t.length,a="";for(;o<=i;){let s=Math.floor((o+i)/2),u=t.substring(0,s);r.encode(u).length<=e?(a=u,o=s+1):i=s-1}return a}function D1t(t){let e=t.split("/"),r=e[e.length-1];if(P4(r)<=pWe)return t;let n=r.lastIndexOf("."),o=n>=0?r.substring(n):"",i=n>=0?r.substring(0,n):r,a=P4(o),s=pWe-a;return s<=0?e[e.length-1]=Tte(r,pWe):e[e.length-1]=Tte(i,s)+o,e.join("/")}async function j1t(t,e=!0){let r=null;app.workspace.iterateAllLeaves(n=>{if(n.view.getViewType()==="markdown"||n.view.getViewType()==="pdf"||n.view.getViewType()==="canvas"){let o=n.view.file;o&&o.path===t.path&&(r=n)}}),r&&e?app.workspace.setActiveLeaf(r,{focus:!0}):r||await app.workspace.getLeaf("tab").openFile(t)}var y1t,$y,mWe,Ote,lSn,cSn,v1t,Mg,dSn,pSn,pWe,Bt=v(()=>{sd();mr();Xe();y1t=$(m1t()),$y=require("obsidian");hF();cWe();mWe={INVALID_LICENSE_KEY_USER:"Invalid Copilot Plus license key. Please check your license key in settings.",UNKNOWN_ERROR:"An unknown error occurred",REQUEST_FAILED:t=>`Request failed, status ${t}`};Ote=(t,e)=>{let r=t.getMarkdownFiles();if(e==="/")return r;let n=e.toLowerCase().replace(/^\/|\/$/g,"");return r.filter(o=>{let a=o.path.toLowerCase().split("/"),s=n.split("/"),u=0;for(let l of s){for(;u<a.length&&a[u]!==l;)u++;if(u>=a.length)return!1}return!0})};lSn=t=>t.last?.modelName||t.last?.model,cSn=t=>t.last?.retriever!==void 0,v1t=t=>lSn(t)||cSn(t),Mg=(t,e="local")=>{let r=(0,y1t.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};dSn=["md","pdf","canvas"];pSn=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/;pWe=255});var ZJ,_We,Ate,sd=v(()=>{fO();FS();sw();J3e();Bt();ZJ=class ZJ{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.withConfig({signal:i?.signal}),s=Bl.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return ZJ.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=ZJ.instances.get("llm_chain");return r||(r=ZJ.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=mu.fromTemplate(`Given the following conversation and a follow up question,
2026-01-05 13:03:55 +08:00
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.
Chat History:
{chat_history}
Follow Up Input: {question}
2026-02-24 07:55:02 +08:00
Standalone question:`),c=mu.fromTemplate(`{system_message}
2026-01-05 13:03:55 +08:00
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
2026-01-21 08:46:13 +08:00
`),d=y=>y.map(b=>`Human: ${b[0]}
2026-01-05 13:03:55 +08:00
Assistant: ${b[1]}`).join(`
2026-02-24 07:55:02 +08:00
`),f=Bl.from([{question:y=>(n&&console.log("Input Question: ",y.question),y.question),chat_history:y=>{let g=d(y.chat_history);return n&&console.log("Formatted Chat History: ",g),g}},u,o,new Kge,y=>{let g=Rte(y),b=_ye(g);return n&&console.log("Standalone Question: ",b),b}]),p=async y=>(r(y),_te(y)),m=Bl.from([{context:i.pipe(p),question:new Au,system_message:()=>a},c,o]);return f.pipe(m)}};ZJ.instances=new Map;_We=ZJ,Ate=_We});var Nte=v(()=>{});var vWe,p1,Nu,Zs,cw,ZC,gSn,ySn,bSn,_Sn,lWe,L1t,F1t,Dte,q_,wWe,jte,R4,$te,SWe,Lte,CWe,xWe,vye,TWe,Fte,wye,Sye,OWe,Cye,Ly,EWe,dye,dw,m1,Hb,k_,gF,hO,YC,T4,hWe,QC,Ste,k1t,UJ,Sn,xye,YJ,ko,US,mr=v(()=>{qN();sd();Nte();vWe="https://api.brevilabs.com/v1",p1="https://models.brevilabs.com/v1",Nu="copilot-chat-view",Zs="user",cw="ai",ZC="copilot",gSn=`${ZC}/copilot-conversations`,ySn=`${ZC}/copilot-custom-prompts`,bSn=`${ZC}/memory`,_Sn=`${ZC}/system-prompts`,lWe=ZC,L1t=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
2026-01-05 13:03:55 +08:00
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 ![link](url) 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.
2026-02-24 07:55:02 +08:00
15. For markdown lists, always use '- ' (hyphen followed by exactly one space) for bullet points, with no leading spaces before the hyphen. Never use '*' (asterisk) for bullets.`,F1t=`Return the new note content or canvas JSON in <writeToFile> tags.
2026-01-05 13:03:55 +08:00
# Steps to find the the target notes
1. Extract the target note information from user message and find out the note path from the context below.
2. If target note is not specified, use the <active_note> as the target note.
3. If still failed to find the target note or the note path, ask the user to specify the target note.
# Examples
Input: Add a new section to note A
Output:
<writeToFile>
<path>path/to/file.md</path>
<content>The FULL CONTENT of the note A with added section goes here</content>
</writeToFile>
Input: Create a new canvas with "Hello, world!"
Output:
<writeToFile>
<path>path/to/file.canvas</path>
<content>
{
"nodes": [
{
"id": "1",
"type": "text",
"text": "Hello, world!",
"x": 0,
"y": 0,
"width": 200,
"height": 50
}
],
"edges": []
}
</content>
</writeToFile>
Input: Create a canvas with a file node and a group
Output:
<writeToFile>
<path>path/to/file.canvas</path>
<content>
{
"nodes": [
{"id": "1", "type": "file", "file": "note.md", "subpath": "#heading", "x": 100, "y": 100, "width": 300, "height": 200, "color": "2"},
{"id": "2", "type": "group", "label": "My Group", "x": 50, "y": 50, "width": 400, "height": 300, "color": "1"},
{"id": "3", "type": "link", "url": "https://example.com", "x": 500, "y": 100, "width": 200, "height": 100, "color": "#FF5733"}
],
"edges": [
{"id": "e1-2", "fromNode": "1", "toNode": "3", "fromSide": "right", "toSide": "left", "fromEnd": "arrow", "toEnd": "none", "color": "3", "label": "references"}
]
}
</content>
</writeToFile>
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
Required edge fields: id, fromNode, toNode
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
All IDs must be unique. Edge nodes must reference existing node IDs.
Position nodes with reasonable spacing and logical visual flow.
2026-02-24 07:55:02 +08:00
`,Dte="note_context",q_="selected_text",wWe="web_selected_text",jte="variable",R4="variable_note",$te="embedded_pdf",SWe="embedded_note",Lte="dataview_block",CWe="retrieved_document",xWe="web_tab_context",vye="active_web_tab",TWe="youtube_video_context",Fte="{activeWebTab}",wye=6e3,Sye=.4,OWe=448e3,Cye=3e4,Ly=30,EWe=5*60*1e3,dye=16,dw={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree",COMPACTING:"Compacting"},m1={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},Hb={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},k_=(g=>(g.OPENROUTERAI="openrouterai",g.OPENAI="openai",g.OPENAI_FORMAT="3rd party (openai-format)",g.ANTHROPIC="anthropic",g.GOOGLE="google",g.XAI="xai",g.AMAZON_BEDROCK="amazon-bedrock",g.AZURE_OPENAI="azure openai",g.GROQ="groq",g.OLLAMA="ollama",g.LM_STUDIO="lm-studio",g.COPILOT_PLUS="copilot-plus",g.MISTRAL="mistralai",g.DEEPSEEK="deepseek",g.COHEREAI="cohereai",g.SILICONFLOW="siliconflow",g.GITHUB_COPILOT="github-copilot",g))(k_||{}),gF={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},hO=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,plusExclusive:!0,projectEnabled:!1,capabilities:["vision"]},{name:"google/gemini-3-flash-preview",provider:"openrouterai",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"google/gemini-3.1-pro-preview",provider:"openrouterai",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"google/gemini-2.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5.2",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5-mini",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"grok-4-1-fast",provider:"xai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"x-ai/grok-4.1-fast",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-5.2",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"claude-opus-4-6",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-sonnet-4-5-20250929",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3-flash-preview",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-pro-preview",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0},{name:"deepseek-chat",provider:"deepseek",enabled:!0,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!0,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"]}],YC=(d=>(d.OPENAI="openai",d.OPENROUTERAI="openrouterai",d.COHEREAI="cohereai",d.GOOGLE="google",d.
`+n6e+t}var o6e=!1;function i6e(t,e){if(!t||o6e)return"";o6e=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(l){var n=l}Reflect.construct(t,[],e)}else{try{e.call()}catch(l){n=l}t.call(e.prototype)}else{try{throw Error()}catch(l){n=l}t()}}catch(l){if(l&&n&&typeof l.stack=="string"){for(var o=l.stack.split(`
2026-01-05 13:03:55 +08:00
`),i=n.stack.split(`
`),a=o.length-1,s=i.length-1;1<=a&&0<=s&&o[a]!==i[s];)s--;for(;1<=a&&0<=s;a--,s--)if(o[a]!==i[s]){if(a!==1||s!==1)do if(a--,s--,0>s||o[a]!==i[s]){var u=`
2026-02-24 07:55:02 +08:00
`+o[a].replace(" at new "," at ");return t.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",t.displayName)),u}while(1<=a&&0<=s);break}}}finally{o6e=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?ere(t):""}function a0n(t){switch(t.tag){case 5:return ere(t.type);case 16:return ere("Lazy");case 13:return ere("Suspense");case 19:return ere("SuspenseList");case 0:case 2:case 15:return t=i6e(t.type,!1),t;case 11:return t=i6e(t.type.render,!1),t;case 1:return t=i6e(t.type,!0),t;default:return""}}function M6e(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case p5:return"Fragment";case f5:return"Portal";case O6e:return"Profiler";case vJe:return"StrictMode";case E6e:return"Suspense";case P6e:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case zjt:return(t.displayName||"Context")+".Consumer";case Bjt:return(t._context.displayName||"Context")+".Provider";case wJe:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case SJe:return e=t.displayName||null,e!==null?e:M6e(t.type)||"Memo";case wF:e=t._payload,t=t._init;try{return M6e(t(e))}catch{}}return null}function s0n(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return M6e(e);case 8:return e===vJe?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function jF(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function Hjt(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function u0n(t){var e=Hjt(t)?"checked":"value",r=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),n=""+t[e];if(!t.hasOwnProperty(e)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var o=r.get,i=r.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return o.call(this)},set:function(a){n=""+a,i.call(this,a)}}),Object.defineProperty(t,e,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(a){n=""+a},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function Uye(t){t._valueTracker||(t._valueTracker=u0n(t))}function Wjt(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=Hjt(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function hbe(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function R6e(t,e){var r=e.checked;return wc({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function LDt(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=jF(e.value!=null?e.value:r),t._wrapperState={initialChecked:n,initialValue:r,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function Jjt(t,e){e=e.checked,e!=null&&_Je(t,"checked",e,!1)}function I6e(t,e){Jjt(t,e);var r=jF(e.value),n=e.type;if(r!=null)n==="number"?(r===0&&t.value===""||t.value!=r)&&(t.value=""+r):t.value!==""+r&&(t.value=""+r);else if(n==="submit"||n==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?A6e(t,e.type,r):e.hasOwnProperty("defaultValue")&&A6e(t,e.type,jF(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}fun
`).replace(gCn,"")}function Qye(t,e,r){if(e=ujt(e),ujt(t)!==e&&r)throw Error(ut(425))}function Cbe(){}var W6e=null,J6e=null;function K6e(t,e){return t==="textarea"||t==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var G6e=typeof setTimeout=="function"?setTimeout:void 0,yCn=typeof clearTimeout=="function"?clearTimeout:void 0,ljt=typeof Promise=="function"?Promise:void 0,bCn=typeof queueMicrotask=="function"?queueMicrotask:typeof ljt<"u"?function(t){return ljt.resolve(null).then(t).catch(_Cn)}:G6e;function _Cn(t){setTimeout(function(){throw t})}function h6e(t,e){var r=e,n=0;do{var o=r.nextSibling;if(t.removeChild(r),o&&o.nodeType===8)if(r=o.data,r==="/$"){if(n===0){t.removeChild(o),bre(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);bre(e)}function RF(t){for(;t!=null;t=t.nextSibling){var e=t.nodeType;if(e===1||e===3)break;if(e===8){if(e=t.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return t}function cjt(t){t=t.previousSibling;for(var e=0;t;){if(t.nodeType===8){var r=t.data;if(r==="$"||r==="$!"||r==="$?"){if(e===0)return t;e--}else r==="/$"&&e++}t=t.previousSibling}return null}var F5=Math.random().toString(36).slice(2),EO="__reactFiber$"+F5,Cre="__reactProps$"+F5,S1="__reactContainer$"+F5,X6e="__reactEvents$"+F5,vCn="__reactListeners$"+F5,wCn="__reactHandles$"+F5;function F4(t){var e=t[EO];if(e)return e;for(var r=t.parentNode;r;){if(e=r[S1]||r[EO]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=cjt(t);t!==null;){if(r=t[EO])return r;t=cjt(t)}return e}t=r,r=t.parentNode}return null}function Are(t){return t=t[EO]||t[S1],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function y5(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(ut(33))}function zbe(t){return t[Cre]||null}var Z6e=[],b5=-1;function FF(t){return{current:t}}function bl(t){0>b5||(t.current=Z6e[b5],Z6e[b5]=null,b5--)}function Zu(t,e){b5++,Z6e[b5]=t.current,t.current=e}var $F={},By=FF($F),H_=FF(!1),z4=$F;function I5(t,e){var r=t.type.contextTypes;if(!r)return $F;var n=t.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in r)o[i]=e[i];return n&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=o),o}function W_(t){return t=t.childContextTypes,t!=null}function xbe(){bl(H_),bl(By)}function djt(t,e,r){if(By.current!==$F)throw Error(ut(168));Zu(By,e),Zu(H_,r)}function j$t(t,e,r){var n=t.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var o in n)if(!(o in e))throw Error(ut(108,s0n(t)||"Unknown",o));return wc({},r,n)}function Tbe(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||$F,z4=By.current,Zu(By,t),Zu(H_,H_.current),!0}function fjt(t,e,r){var n=t.stateNode;if(!n)throw Error(ut(169));r?(t=j$t(t,e,z4),n.__reactInternalMemoizedMergedChildContext=t,bl(H_),bl(By),Zu(By,t)):bl(H_),Zu(H_,r)}var y1=null,Vbe=!1,g6e=!1;function $$t(t){y1===null?y1=[t]:y1.push(t)}function SCn(t){Vbe=!0,$$t(t)}function kF(){if(!g6e&&y1!==null){g6e=!0;var t=0,e=su;try{var r=y1;for(su=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}y1=null,Vbe=!1}catch(o){throw y1!==null&&(y1=y1.slice(t+1)),s$t(xJe,kF),o}finally{su=e,g6e=!1}}return null}var _5=[],v5=0,Obe=null,Ebe=0,WS=[],JS=0,V4=null,b1=1,_1="";function $4(t,e){_5[v5++]=Ebe,_5[v5++]=Obe,Obe=t,Ebe=e}function L$t(t,e,r){WS[JS++]=b1,WS[JS++]=_1,WS[JS++]=V4,V4=t;var n=b1;t=_1;var o=32-sx(n)-1;n&=~(1<<o),r+=1;var i=32-sx(e)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,b1=1<<32-sx(e)+o|r<<o|n,_1=i+t}else b1=1<<i|r<<o|n,_1=t}function NJe(t){t.return!==null&&($4(t,1),L$t(t,1,0))}function DJe(t){for(;t===Obe;)Obe=_5[--v5],_5[v5]=null,Ebe=_5[--v5],_5[v5]=null;for(;t===V4;)V4=WS[--JS],WS[JS]=null,_1=WS[--JS],WS[JS]=null,b1=WS[--JS],WS[JS]=null}var hw=null,mw=null,Vl=!1,ax=null;function F$t(t,e){var r=KS(5,n
2026-01-05 13:03:55 +08:00
Error generating stack: `+i.message+`
2026-02-24 07:55:02 +08:00
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function w6e(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function nJe(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var ICn=typeof WeakMap=="function"?WeakMap:Map;function fLt(t,e,r){r=v1(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){jbe||(jbe=!0,pJe=n),nJe(t,e)},r}function pLt(t,e,r){r=v1(-1,r),r.tag=3;var n=t.type.getDerivedStateFromError;if(typeof n=="function"){var o=e.value;r.payload=function(){return n(o)},r.callback=function(){nJe(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){nJe(t,e),typeof n!="function"&&(AF===null?AF=new Set([this]):AF.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function Sjt(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new ICn;var o=new Set;n.set(e,o)}else o=n.get(e),o===void 0&&(o=new Set,n.set(e,o));o.has(r)||(o.add(r),t=HCn.bind(null,t,e,r),e.then(t,t))}function Cjt(t){do{var e;if((e=t.tag===13)&&(e=t.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return t;t=t.return}while(t!==null);return null}function xjt(t,e,r,n,o){return(t.mode&1)===0?(t===e?t.flags|=65536:(t.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(e=v1(-1,1),e.tag=2,IF(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var ACn=T1.ReactCurrentOwner,V_=!1;function Wb(t,e,r,n){e.child=t===null?H$t(e,null,r,n):N5(e,t.child,r,n)}function Tjt(t,e,r,n,o){r=r.render;var i=e.ref;return P5(e,o),n=HJe(t,e,r,n,i,o),r=WJe(),t!==null&&!V_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,x1(t,e,o)):(Vl&&r&&NJe(e),e.flags|=1,Wb(t,e,n,o),e.child)}function Ojt(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!r5e(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,mLt(t,e,i,n,o)):(t=mbe(r.type,null,n,e,e.mode,o),t.ref=e.ref,t.return=e,e.child=t)}if(i=t.child,(t.lanes&o)===0){var a=i.memoizedProps;if(r=r.compare,r=r!==null?r:vre,r(a,n)&&t.ref===e.ref)return x1(t,e,o)}return e.flags|=1,t=DF(i,n),t.ref=e.ref,t.return=e,e.child=t}function mLt(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(vre(i,n)&&t.ref===e.ref)if(V_=!1,e.pendingProps=n=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(V_=!0);else return e.lanes=t.lanes,x1(t,e,o)}return oJe(t,e,r,n,o)}function hLt(t,e,r){var n=e.pendingProps,o=n.children,i=t!==null?t.memoizedState:null;if(n.mode==="hidden")if((e.mode&1)===0)e.memoizedState={baseLanes:0,cachePool:null,transitions:null},Zu(C5,pw),pw|=r;else{if((r&1073741824)===0)return t=i!==null?i.baseLanes|r:r,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:t,cachePool:null,transitions:null},e.updateQueue=null,Zu(C5,pw),pw|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,Zu(C5,pw),pw|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,Zu(C5,pw),pw|=n;return Wb(t,e,o,r),e.child}function gLt(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function oJe(t,e,r,n,o){var i=W_(r)?z4:By.current;return i=I5(e,i),P5(e,o),r=HJe(t,e,r,n,i,o),n=WJe(),t!==null&&!V_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,x1(t,e,o)):(Vl&&n&&NJe(e),e.flags|=1,Wb(t,e,r,o),e.child)}function Ejt(t,e,r,n,o){if(W_(r)){var i=!0;Tbe(e)}else i=!1;if(P5(e,o),e.stateNode===null)dbe(t,e),z$t(e,r,n),rJe(e,r,n,o),n=!0;else if(t===null){var a=e.stateNode,s=e.memoizedProps;a.props=s;var u=a.context,l=r.contextType;typeof l=="object"&&l!==null?l=XS(l):(l=W_(r)?z4:By.current,l=I5(e,l));var c=r.getDerivedStateFromProps,d=typeof c=="function"||typeof a.getSnapshotBeforeUpdate=="function";d||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(s!==n||u!==l)&&bjt(e,a,n,l),SF=!1;var f=e.memoizedState;a.state=f,Rbe(e,n,a,o),u=e.memoizedState,s!==n||f!==u||H_.current||SF?(typeof c=="function"&&(tJe(e,r,c,n),u=e.memoizedState),(s=SF||yjt(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount
`)}});var e3t=S(rve=>{"use strict";Object.defineProperty(rve,"__esModule",{value:!0});rve.CohereTimeoutError=void 0;var T5e=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};rve.CohereTimeoutError=T5e});var kc=S(K5=>{"use strict";Object.defineProperty(K5,"__esModule",{value:!0});K5.CohereTimeoutError=K5.CohereError=void 0;var DTn=QHt();Object.defineProperty(K5,"CohereError",{enumerable:!0,get:function(){return DTn.CohereError}});var jTn=e3t();Object.defineProperty(K5,"CohereTimeoutError",{enumerable:!0,get:function(){return jTn.CohereTimeoutError}})});var t3t=S(DO=>{"use strict";var $Tn=DO&&DO.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),LTn=DO&&DO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),FTn=DO&&DO.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&$Tn(r,e,n[o]);return LTn(r,e),r}}();Object.defineProperty(DO,"__esModule",{value:!0});DO.BadRequestError=void 0;var kTn=FTn(kc()),O5e=class t extends kTn.CohereError{constructor(e,r){super({message:"BadRequestError",statusCode:400,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};DO.BadRequestError=O5e});var r3t=S(jO=>{"use strict";var qTn=jO&&jO.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),UTn=jO&&jO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),BTn=jO&&jO.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&qTn(r,e,n[o]);return UTn(r,e),r}}();Object.defineProperty(jO,"__esModule",{value:!0});jO.UnauthorizedError=void 0;var zTn=BTn(kc()),E5e=class t extends zTn.CohereError{constructor(e,r){super({message:"UnauthorizedError",statusCode:401,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};jO.UnauthorizedError=E5e});var n3t=S($O=>{"use strict";var VTn=$O&&$O.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),HTn=$O&&$O.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),WTn=$O&&$O.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&VTn(r,e,n[o]);return HTn(r,e),r}}();Object.defineProperty($O,"__esModule",{value:!0});$O.ForbiddenError=void 0;var JTn=WTn(kc()),P5e=class t extends JTn.CohereError{constructor(e,r){super({message:"ForbiddenError",statusCode:403,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};$O.ForbiddenError=P5e});var o3t=S(LO=>{"use strict";var KTn=LO&&LO.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(
`));return r(o)}});var kEn,Tve,DWt=v(()=>{tKe();kEn={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},Tve=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(NWt(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),kEn)}})});var jWt=v(()=>{});var $Wt=v(()=>{});var Ove,LWt=v(()=>{Ove={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var rKe=v(()=>{jWt();LWt();$Wt()});var PGi,FWt=v(()=>{rKe();PGi={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:Ove.name}});var kWt=v(()=>{tKe();DWt();FWt()});var qWt=v(()=>{});var UWt=v(()=>{qWt()});var BWt=v(()=>{});var zWt=v(()=>{});var VWt=v(()=>{});function qEn(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var ek,HWt=v(()=>{ek=class t{constructor(e){x(this,"method");x(this,"protocol");x(this,"hostname");x(this,"port");x(this,"path");x(this,"query");x(this,"headers");x(this,"username");x(this,"password");x(this,"fragment");x(this,"body");this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){let r=new t({...e,headers:{...e.headers}});return r.query&&(r.query=qEn(r.query)),r}static isInstance(e){if(!e)return!1;let r=e;return"method"in r&&"protocol"in r&&"hostname"in r&&"path"in r&&typeof r.query=="object"&&typeof r.headers=="object"}clone(){return t.clone(this)}}});var Z5,WWt=v(()=>{Z5=class{constructor(e){x(this,"statusCode");x(this,"reason");x(this,"headers");x(this,"body");this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;let r=e;return typeof r.statusCode=="number"&&typeof r.headers=="object"}}});var JWt=v(()=>{});var KWt=v(()=>{});var mne=v(()=>{UWt();BWt();zWt();VWt();HWt();WWt();JWt();KWt()});var GWt,UEn,BEn,XWt,nKe=v(()=>{mne();GWt=$(r0()),UEn=t=>e=>{throw e},BEn=(t,e)=>{},XWt=t=>(e,r)=>async n=>{if(!ek.isInstance(n.request))return e(n);let i=(0,GWt.getSmithyContext)(r).selectedHttpAuthScheme;if(!i)throw new Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:a={}},identity:s,signer:u}=i,l=await e({...n,request:await u.sign(n.request,s,a)}).catch((u.errorHandler||UEn)(a));return(u.successHandler||BEn)(l.response,a),l}});var zEn,Eve,ZWt=v(()=>{nKe();zEn={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},Eve=t=>({applyToStack:e=>{e.addRelativeTo(XWt(t),zEn)}})});var YWt=v(()=>{nKe();ZWt()});var j1,QWt=v(()=>{j1=t=>{if(typeof t=="function")return t;let e=Promise.resolve(t);return()=>e}});function oKe(t,e,r,n,o){return async function*(a,s,...u){let l=s,c=a.startingToken??l[r],d=!0,f;for(;d;){if(l[r]=c,o&&(l[o]=l[o]??a.pageSize),a.client instanceof t)f=await VEn(e,a.client,s,a.withCommand,...u);else throw new Error(`Invalid client, expected instance of ${t.name}`);yield f;let p=c;c=HEn(f,n),d=!!(c&&(!a.stopOnSameToken||c!==p))}return void 0}}var VEn,HEn,e6t=v(()=>{VEn=async(t,e,r,n=i=>i,...o)=>{let i=new t(r);return i=n(i)??i,await e.send(i,...o)};HEn=(t,e)=>{let r=t,n=e.split(".");for(let o of n){if(!r||typeof r!="object")return;r=r[o]}return r}});var t6t,iKe,r6t,tk,p2,n6t,aKe=v(()=>{t6t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",iKe=Object.entries(t6t).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),r6t=t6t.split(""),tk=6,p2=8,n6t=63});var Sw,o6t=v(()=>{aKe();Sw=t=>{let e=t.length/4*3;t.slice(-2)==="=="?e-=2:t.slice(-1)==="="&&e--;let r=ne
If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return o.stream()};return Object.assign(t,{transformToByteArray:r,transformToString:async o=>{let i=await r();if(o==="base64")return Cw(i);if(o==="hex")return U6t(i);if(o===void 0||o==="utf8"||o==="utf-8")return Pve(i);if(typeof TextDecoder=="function")return new TextDecoder(o).decode(i);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)throw new Error(z6t);if(e=!0,V6t(t))return n(t);if(uKe(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},V6t=t=>typeof Blob=="function"&&t instanceof Blob});var J6t=v(()=>{});var fKe=v(()=>{h6t();g6t();b6t();_6t();v6t();w6t();W6t();J6t()});var $1,pKe=v(()=>{fKe();$1=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return Y5.mutate(t);if(!t)return Y5.mutate(new Uint8Array);let r=e.streamCollector(t);return Y5.mutate(await r)}});function mKe(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}var K6t=v(()=>{});var nk,hKe=v(()=>{nk=t=>typeof t=="function"?t():t});var Rve,Ive=v(()=>{Rve=(t,e,r,n,o)=>({name:e,namespace:t,traits:r,input:n,output:o})});var G6t,X6t,gKe,Z6t=v(()=>{mne();G6t=$(r0());Ive();X6t=t=>(e,r)=>async n=>{let{response:o}=await e(n),{operationSchema:i}=(0,G6t.getSmithyContext)(r),[,a,s,u,l,c]=i??[];try{let d=await t.protocol.deserializeResponse(Rve(a,s,u,l,c),{...t,...r},o);return{response:o,output:d}}catch(d){if(Object.defineProperty(d,"$response",{value:o,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in d)){let f="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{d.message+=`
`+f}catch{!r.logger||r.logger?.constructor?.name==="NoOpLogger"?console.warn(f):r.logger?.warn?.(f)}typeof d.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(Z5.isInstance(o)){let{headers:p={}}=o,m=Object.entries(p);d.$metadata={httpStatusCode:o.statusCode,requestId:gKe(/^x-[\w-]+-request-?id$/,m),extendedRequestId:gKe(/^x-[\w-]+-id-2$/,m),cfId:gKe(/^x-[\w-]+-cf-id$/,m)}}}catch{}}throw d}},gKe=(t,e)=>(e.find(([r])=>r.match(t))||[void 0,void 0])[1]});var Y6t,Q6t,eJt=v(()=>{Y6t=$(r0());Ive();Q6t=t=>(e,r)=>async n=>{let{operationSchema:o}=(0,Y6t.getSmithyContext)(r),[,i,a,s,u,l]=o??[],c=r.endpointV2?.url&&t.urlParser?async()=>t.urlParser(r.endpointV2.url):t.endpoint,d=await t.protocol.serializeRequest(Rve(i,a,s,u,l),n.input,{...t,...r,endpoint:c});return e({...n,request:d})}});function Ave(t){return{applyToStack:e=>{e.add(Q6t(t),QEn),e.add(X6t(t),YEn),t.protocol.setSerdeContext(t)}}}var YEn,QEn,tJt=v(()=>{Z6t();eJt();YEn={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},QEn={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var n0,m2=v(()=>{n0=class{constructor(){x(this,"name");x(this,"namespace");x(this,"traits")}static assign(e,r){return Object.assign(e,r)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"&&e!==null?e.symbol===this.symbol:r}getName(){return this.namespace+"#"+this.name}}});var Nve,rJt,nJt=v(()=>{m2();Nve=class Nve extends n0{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"valueSchema");x(this,"symbol",Nve.symbol)}};x(Nve,"symbol",Symbol.for("@smithy/lis"));rJt=Nve});var Dve,oJt,iJt=v(()=>{m2();Dve=class Dve extends n0{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"keySchema");x(this,"valueSchema");x(this,"symbol",Dve.symbol)}};x(Dve,"symbol",Symbol.for("@smithy/map"));oJt=Dve});var jve,aJt,sJt=v(()=>{m2();jve=class jve extends n0{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"input");x(this,"output");x(this,"symbol",jve.symbol)}};x(jve,"symbol",Symbol.for("@smithy/ope"));aJt=jve});var Lve,$ve,yKe=v(()=>{m2();Lve=class Lve extends n0{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"memberNames");x(this,"memberList");x(this,"symbol",Lve.symbol)}};x(Lve,"symbol",Symbol.for("@smithy/str"));$ve=Lve});var Fve,uJt,lJt=v(()=>{yKe();Fve=class Fve extends $ve{constructor(){super(...arguments);x(this,"ctor");x(this,"symbol",Fve.symbol)}};x(Fve,"symbol",Symbol.for("@smithy/err"));uJt=Fve});function h2(t){if(typeof t=="object")return t;t=t|0;let e={},r=0;for(let n of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(t>>r++&1)===1&&(e[n]=1);return e}var bKe=v(()=>{});function bne(t,e){if(t instanceof na)return Object.assign(t,{memberName:e,_isMemberSchema:!0});let r=na;return new r(t,e)}var ok,na,_Ke,ePn,cJt=v(()=>{hKe();bKe();ok=class ok{constructor(e,r){x(this,"ref");x(this,"memberName");x(this,"symbol",ok.symbol);x(this,"name");x(this,"schema");x(this,"_isMemberSchema");x(this,"traits");x(this,"memberTraits");x(this,"normalizedTraits");this.ref=e,this.memberName=r;let n=[],o=e,i=e;for(this._isMemberSchema=!1;_Ke(o);)n.push(o[1]),o=o[0],i=nk(o),this._isMemberSchema=!0;if(n.length>0){this.memberTraits={};for(let a=n.length-1;a>=0;--a){let s=n[a];Object.assign(this.memberTraits,h2(s))}}else this.memberTraits=0;if(i instanceof ok){let a=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},a,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=r??i.memberName;return}if(this.schema=nk(i),ePn(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(i),this.traits=0),this._isMemberSchema&&!r)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"
2026-01-05 13:03:55 +08:00
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
2026-02-24 07:55:02 +08:00
`),aPn={warn:console.warn}});function Uve(t){let e=t.getUTCFullYear(),r=t.getUTCMonth(),n=t.getUTCDay(),o=t.getUTCDate(),i=t.getUTCHours(),a=t.getUTCMinutes(),s=t.getUTCSeconds(),u=o<10?`0${o}`:`${o}`,l=i<10?`0${i}`:`${i}`,c=a<10?`0${a}`:`${a}`,d=s<10?`0${s}`:`${s}`;return`${sPn[n]}, ${u} ${CKe[r]} ${e} ${l}:${c}:${d} GMT`}var sPn,CKe,uPn,CJt,lPn,xJt,cPn,dPn,fPn,TJt,OJt,_ne,pPn,mPn,hPn,SKe,gPn,yPn,bPn,XO,_Pn,vPn,tK,EJt=v(()=>{wKe();sPn=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],CKe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];uPn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),CJt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=uPn.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=eK(tK(n)),d=XO(o,"month",1,12),f=XO(i,"day",1,31);return _ne(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},lPn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),xJt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=lPn.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l,c]=e,d=eK(tK(n)),f=XO(o,"month",1,12),p=XO(i,"day",1,31),m=_ne(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-vPn(c)),m},cPn=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),dPn=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),fPn=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),TJt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=cPn.exec(t);if(e){let[r,n,o,i,a,s,u,l]=e;return _ne(eK(tK(i)),SKe(o),XO(n,"day",1,31),{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})}if(e=dPn.exec(t),e){let[r,n,o,i,a,s,u,l]=e;return hPn(_ne(pPn(i),SKe(o),XO(n,"day",1,31),{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l}))}if(e=fPn.exec(t),e){let[r,n,o,i,a,s,u,l]=e;return _ne(eK(tK(l)),SKe(n),XO(o.trimLeft(),"day",1,31),{hours:i,minutes:a,seconds:s,fractionalMilliseconds:u})}throw new TypeError("Invalid RFC-7231 date-time value")},OJt=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=vJt(t);else if(typeof t=="object"&&t.tag===1)e=t.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},_ne=(t,e,r,n)=>{let o=e-1;return yPn(t,o,r),new Date(Date.UTC(t,o,r,XO(n.hours,"hour",0,23),XO(n.minutes,"minute",0,59),XO(n.seconds,"seconds",0,60),_Pn(n.fractionalMilliseconds)))},pPn=t=>{let e=new Date().getUTCFullYear(),r=Math.floor(e/100)*100+eK(tK(t));return r<e?r+100:r},mPn=50*365*24*60*60*1e3,hPn=t=>t.getTime()-new Date().getTime()>mPn?new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds())):t,SKe=t=>{let e=CKe.indexOf(t);if(e<0)throw new TypeError(`Invalid month: ${t}`);return e+1},gPn=[31,28,31,30,31,30,31,31,30,31,30,31],yPn=(t,e,r)=>{let n=gPn[e];if(e===1&&bPn(t)&&(n=29),r>n)throw new TypeError(`Invalid day for ${CKe[e]} in ${t}: ${r}`)},bPn=t=>t%4===0&&(t%100!==0||t%400===0),XO=(t,e,r,n)=>{let o=SJt(tK(t));if(o<r||o>n)throw new TypeError(`${e} must be between ${r} and ${n}, inclusive`);return o},_Pn=t=>t==null?0:wJt("0."+t)*1e3,vPn=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new Typ
2026-01-05 13:03:55 +08:00
${this.getCanonicalPath(e)}
2026-02-24 07:55:02 +08:00
${H8t(e)}
2026-01-05 13:03:55 +08:00
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
2026-02-24 07:55:02 +08:00
${n}`}async createStringToSign(e,r,n,o){let i=new this.sha256;i.update(q1(n));let a=await i.digest();return`${o}
2026-01-05 13:03:55 +08:00
${e}
${r}
2026-02-24 07:55:02 +08:00
${s0(a)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let r=[];for(let i of e.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));let n=`${e?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&e?.endsWith("/")?"/":""}`;return(0,G8t.escapeUri)(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){let r=J8t(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}});var Pne,Z8t=v(()=>{lK();ck();dk();r8e();N8t();$8t();k8t();U8t();z8t();V8t();X8t();Pne=class extends pwe{constructor({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s});x(this,"headerFormatter",new dwe)}async presign(r,n={}){let{signingDate:o=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:u,hoistableHeaders:l,signingRegion:c,signingService:d}=n,f=await this.credentialProvider();this.validateResolvedCredentials(f);let p=c??await this.regionProvider(),{longDate:m,shortDate:h}=this.formatDate(o);if(i>R8t)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let y=lwe(h,p,d??this.service),g=B8t(i8e(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(g.query[ZKe]=f.sessionToken),g.query[y8t]=swe,g.query[b8t]=`${f.accessKeyId}/${y}`,g.query[GKe]=m,g.query[v8t]=i.toString(10);let b=n8e(g,a,u);return g.query[_8t]=this.getCanonicalHeaderList(b),g.query[XKe]=await this.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,await cwe(r,this.sha256))),g}async sign(r,n){return typeof r=="string"?this.signString(r,n):r.headers&&r.payload?this.signEvent(r,n):r.message?this.signMessage(r,n):this.signRequest(r,n)}async signEvent({headers:r,payload:n},{signingDate:o=new Date,priorSignature:i,signingRegion:a,signingService:s}){let u=a??await this.regionProvider(),{shortDate:l,longDate:c}=this.formatDate(o),d=lwe(l,u,s??this.service),f=await cwe({headers:{},body:n},this.sha256),p=new this.sha256;p.update(r);let m=s0(await p.digest()),h=[E8t,c,d,i,m,f].join(`
`);return this.signString(h,{signingDate:o,signingRegion:u,signingService:s})}async signMessage(r,{signingDate:n=new Date,signingRegion:o,signingService:i}){return this.signEvent({headers:this.headerFormatter.format(r.message.headers),payload:r.message.body},{signingDate:n,signingRegion:o,signingService:i,priorSignature:r.priorSignature}).then(s=>({message:r.message,signature:s}))}async signString(r,{signingDate:n=new Date,signingRegion:o,signingService:i}={}){let a=await this.credentialProvider();this.validateResolvedCredentials(a);let s=o??await this.regionProvider(),{shortDate:u}=this.formatDate(n),l=new this.sha256(await this.getSigningKey(a,s,u,i));return l.update(q1(r)),s0(await l.digest())}async signRequest(r,{signingDate:n=new Date,signableHeaders:o,unsignableHeaders:i,signingRegion:a,signingService:s}={}){let u=await this.credentialProvider();this.validateResolvedCredentials(u);let l=a??await this.regionProvider(),c=i8e(r),{longDate:d,shortDate:f}=this.formatDate(n),p=lwe(f,l,s??this.service);c.headers[QKe]=d,u.sessionToken&&(c.headers[C8t]=u.sessionToken);let m=await cwe(c,this.sha256);!q8t(Ene,c.headers)&&this.applyChecksum&&(c.headers[Ene]=m);let h=n8e(c,i,o),y=await this.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));return c.headers[YKe]=`${swe} Credential=${u.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${y}`,c}async getSignature(r,n,o,i){let a=await this.createStringToSign(r,n,i,swe),s=new this.sha256(await o);return s.update(q1(a)),s0(await s.digest())}getSigningKey(r,n,o,i){return A8t(this.sha256,r,o,n,i||this.service)}}});var Y8t=v(()=>{});var Q8t=v(()=>{Z8t();dk();r8e();Y8t()});function UPn(t,{credentials:e,credentialDefaultProvider:r}){let n;return e?e?.memoized?n=e:n=m5t(e,p5t,NKe):r?n=j1(r(Object.assign({},t,{parentClientConfig:t}))):n=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},n.memoized=!0,n}function BPn(t,e){if(e.configBound)return e;let r=async n=>e({...n,callerClientConfig:t});return r.memoized=e.memoized,r.configBound=!0,r}var mwe,eGt=v(()=>{nwe();ZO();Q8t();mwe=t=>{let e=t.credentials,r=!!t.credentials,n;Object.defineProperty(t,"credentials",{set(l){l&&l!==e&&l!==n&&(r=!0),e=l;let c=UPn(t,{credentials:e,credentialDefaultProvider:t.credentialDefaultProvider}),d=BPn(t,c);if(r&&!d.attributed){let f=typeof e=="object"&&e!==null;n=async p=>{let h=await d(p);return f&&(!h.$source||Object.keys(h.$source).length===0)?uK(h,"CREDENTIALS_CODE","e"):h},n.memoized=d.memoized,n.configBound=d.configBound,n.attributed=!0}else n=d},get(){return n},enumerable:!0,configurable:!0}),t.credentials=e;let{signingEscapePath:o=!0,systemClockOffset:i=t.systemClockOffset||0,sha256:a}=t,s;return t.signer?s=j1(t.signer):t.regionInfoProvider?s=()=>j1(t.region)().then(async l=>[await t.regionInfoProvider(l,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},l]).then(([l,c])=>{let{signingRegion:d,signingService:f}=l;t.signingRegion=t.signingRegion||d||c,t.signingName=t.signingName||f||t.serviceId;let p={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o},m=t.signerConstructor||Pne;return new m(p)}):s=async l=>{l=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await j1(t.region)(),properties:{}},l);let c=l.signingRegion,d=l.signingName;t.signingRegion=t.signingRegion||c,t.signingName=t.signingName||d||t.serviceId;let f={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o},p=t.signerConstructor||Pne;return new p(f)},Object.assign(t,{systemClockOffset:i,signingEscapePath:o,signer:s})}});var tGt=v(()=>{l8t();d8t();f8t();eGt()});var rGt=v(()=>{tGt();c8t()});var nGt,hwe,oGt=v(()=>{nGt=typeof TextEncoder=="function"?new TextEncoder:null,hwe=t=>{if(typeof t=="string"){if(nGt)return nGt.encode(t).byteLength;let e=t.length;for(let r=e-1;r>=0;r--){let n=t.charCodeAt(r);n>127&
2026-01-05 13:03:55 +08:00
- loopback CIDR 127.0.0.0/8 or [::1/128]
- ECS container host 169.254.170.2
2026-02-24 07:55:02 +08:00
- EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:e})}}});var aYt=v(()=>{});var sYt=v(()=>{aYt()});var uYt=v(()=>{});var lYt=v(()=>{});var cYt=v(()=>{});function rNn(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var e0e,dYt=v(()=>{e0e=class t{constructor(e){x(this,"method");x(this,"protocol");x(this,"hostname");x(this,"port");x(this,"path");x(this,"query");x(this,"headers");x(this,"username");x(this,"password");x(this,"fragment");x(this,"body");this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){let r=new t({...e,headers:{...e.headers}});return r.query&&(r.query=rNn(r.query)),r}static isInstance(e){if(!e)return!1;let r=e;return"method"in r&&"protocol"in r&&"hostname"in r&&"path"in r&&typeof r.query=="object"&&typeof r.headers=="object"}clone(){return t.clone(this)}}});var fYt=v(()=>{});var pYt=v(()=>{});var mYt=v(()=>{});var hYt=v(()=>{sYt();uYt();lYt();cYt();dYt();fYt();pYt();mYt()});function gYt(t){return new e0e({protocol:t.protocol,hostname:t.hostname,port:Number(t.port),path:t.pathname,query:Array.from(t.searchParams.entries()).reduce((e,[r,n])=>(e[r]=n,e),{}),fragment:t.hash})}async function yYt(t,e){let n=await H6t(t.body).transformToString();if(t.statusCode===200){let o=JSON.parse(n);if(typeof o.AccessKeyId!="string"||typeof o.SecretAccessKey!="string"||typeof o.Token!="string"||typeof o.Expiration!="string")throw new Lm("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }",{logger:e});return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,sessionToken:o.Token,expiration:CJt(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new Lm(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new Lm(`Server responded with status: ${t.statusCode}`,{logger:e})}var bYt=v(()=>{QF();hYt();Lo();fKe()});var _Yt,vYt=v(()=>{_Yt=(t,e,r)=>async()=>{for(let n=0;n<e;++n)try{return await t()}catch{await new Promise(i=>setTimeout(i,r))}return await t()}});var RGe,wYt=v(()=>{yne();QF();iYt();bYt();vYt();RGe=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new Lm("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);oYt(n,t.logger);let o=new rk;return _Yt(async()=>{let i=gYt(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return yYt(a.response)},t.maxRetries??3,t.timeout??1e3)}});var SYt=v(()=>{wYt()});function nNn(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function oNn(t){return{schemeId:"smithy.api#noAuth"}}var Lne,CYt,xYt,iNn,TYt,IGe=v(()=>{hK();Lne=$(r0());Fne();CYt=async(t,e,r)=>({operation:(0,Lne.getSmithyContext)(e).operation,region:await(0,Lne.normalizeProvider)(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});xYt=t=>{let e=[];switch(t.operation){case"AssumeRoleWithWebIdentity":{e.push(oNn(t));break}default:e.push(nNn(t))}return e},iNn=t=>Object.assign(t,{stsClientCtor:l0}),TYt=t=>{let e=iNn(t),r=mwe(e);return Object.assign(r,{authSchemePreference:(0,Lne.normalizeProvider)(t.authSchemePreference??[])})}});var OYt,t0e,r0e=v(()=>{OYt=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),t0e={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:
2026-01-05 13:03:55 +08:00
${this.getCanonicalPath(e)}
2026-02-24 07:55:02 +08:00
${etr(e)}
2026-01-05 13:03:55 +08:00
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
2026-02-24 07:55:02 +08:00
${n}`}async createStringToSign(e,r,n,o){let i=new this.sha256;i.update(M2.toUint8Array(n));let a=await i.digest();return`${o}
2026-01-05 13:03:55 +08:00
${e}
${r}
2026-02-24 07:55:02 +08:00
${bk.toHex(a)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let r=[];for(let i of e.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));let n=`${e?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&e?.endsWith("/")?"/":""}`;return c0e.escapeUri(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){let r=E1n(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}},r9e=class extends g0e{constructor({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s});x(this,"headerFormatter",new QGe)}async presign(r,n={}){let{signingDate:o=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:u,hoistableHeaders:l,signingRegion:c,signingService:d}=n,f=await this.credentialProvider();this.validateResolvedCredentials(f);let p=c??await this.regionProvider(),{longDate:m,shortDate:h}=this.formatDate(o);if(i>Xer)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let y=p0e(h,p,d??this.service),g=Qer(t9e(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(g.query[i9e]=f.sessionToken),g.query[$er]=d0e,g.query[Ler]=`${f.accessKeyId}/${y}`,g.query[n9e]=m,g.query[ker]=i.toString(10);let b=YGe(g,a,u);return g.query[Fer]=this.getCanonicalHeaderList(b),g.query[o9e]=await this.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,await m0e(r,this.sha256))),g}async sign(r,n){return typeof r=="string"?this.signString(r,n):r.headers&&r.payload?this.signEvent(r,n):r.message?this.signMessage(r,n):this.signRequest(r,n)}async signEvent({headers:r,payload:n},{signingDate:o=new Date,priorSignature:i,signingRegion:a,signingService:s}){let u=a??await this.regionProvider(),{shortDate:l,longDate:c}=this.formatDate(o),d=p0e(l,u,s??this.service),f=await m0e({headers:{},body:n},this.sha256),p=new this.sha256;p.update(r);let m=bk.toHex(await p.digest()),h=[Jer,c,d,i,m,f].join(`
`);return this.signString(h,{signingDate:o,signingRegion:u,signingService:s})}async signMessage(r,{signingDate:n=new Date,signingRegion:o,signingService:i}){return this.signEvent({headers:this.headerFormatter.format(r.message.headers),payload:r.message.body},{signingDate:n,signingRegion:o,signingService:i,priorSignature:r.priorSignature}).then(s=>({message:r.message,signature:s}))}async signString(r,{signingDate:n=new Date,signingRegion:o,signingService:i}={}){let a=await this.credentialProvider();this.validateResolvedCredentials(a);let s=o??await this.regionProvider(),{shortDate:u}=this.formatDate(n),l=new this.sha256(await this.getSigningKey(a,s,u,i));return l.update(M2.toUint8Array(r)),bk.toHex(await l.digest())}async signRequest(r,{signingDate:n=new Date,signableHeaders:o,unsignableHeaders:i,signingRegion:a,signingService:s}={}){let u=await this.credentialProvider();this.validateResolvedCredentials(u);let l=a??await this.regionProvider(),c=t9e(r),{longDate:d,shortDate:f}=this.formatDate(n),p=p0e(f,l,s??this.service);c.headers[s9e]=d,u.sessionToken&&(c.headers[zer]=u.sessionToken);let m=await m0e(c,this.sha256);!Yer(h0e,c.headers)&&this.applyChecksum&&(c.headers[h0e]=m);let h=YGe(c,i,o),y=await this.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));return c.headers[a9e]=`${d0e} Credential=${u.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${y}`,c}async getSignature(r,n,o,i){let a=await this.createStringToSign(r,n,i,d0e),s=new this.sha256(await o);return s.update(M2.toUint8Array(a)),bk.toHex(await s.digest())}getSigningKey(r,n,o,i){return Zer(this.sha256,r,o,n,i||this.service)}},M1n={SignatureV4a:null};hi.ALGORITHM_IDENTIFIER=d0e;hi.ALGORITHM_IDENTIFIER_V4A=x1n;hi.ALGORITHM_QUERY_PARAM=$er;hi.ALWAYS_UNSIGNABLE_HEADERS=Ver;hi.AMZ_DATE_HEADER=s9e;hi.AMZ_DATE_QUERY_PARAM=n9e;hi.AUTH_HEADER=a9e;hi.CREDENTIAL_QUERY_PARAM=Ler;hi.DATE_HEADER=qer;hi.EVENT_ALGORITHM_IDENTIFIER=Jer;hi.EXPIRES_QUERY_PARAM=ker;hi.GENERATED_HEADERS=Uer;hi.HOST_HEADER=S1n;hi.KEY_TYPE_IDENTIFIER=u9e;hi.MAX_CACHE_SIZE=Ger;hi.MAX_PRESIGNED_TTL=Xer;hi.PROXY_HEADER_PATTERN=Her;hi.REGION_SET_PARAM=w1n;hi.SEC_HEADER_PATTERN=Wer;hi.SHA256_HEADER=h0e;hi.SIGNATURE_HEADER=Ber;hi.SIGNATURE_QUERY_PARAM=o9e;hi.SIGNED_HEADERS_QUERY_PARAM=Fer;hi.SignatureV4=r9e;hi.SignatureV4Base=g0e;hi.TOKEN_HEADER=zer;hi.TOKEN_QUERY_PARAM=i9e;hi.UNSIGNABLE_PATTERNS=C1n;hi.UNSIGNED_PAYLOAD=Ker;hi.clearCredentialCache=T1n;hi.createScope=p0e;hi.getCanonicalHeaders=YGe;hi.getCanonicalQuery=etr;hi.getPayloadHash=m0e;hi.getSigningKey=Zer;hi.hasHeader=Yer;hi.moveHeadersToQuery=Qer;hi.prepareRequest=t9e;hi.signatureV4aContainer=M1n});var Sc=S((Mva,rtr)=>{"use strict";rtr.exports={ArrayIsArray(t){return Array.isArray(t)},ArrayPrototypeIncludes(t,e){return t.includes(e)},ArrayPrototypeIndexOf(t,e){return t.indexOf(e)},ArrayPrototypeJoin(t,e){return t.join(e)},ArrayPrototypeMap(t,e){return t.map(e)},ArrayPrototypePop(t,e){return t.pop(e)},ArrayPrototypePush(t,e){return t.push(e)},ArrayPrototypeSlice(t,e,r){return t.slice(e,r)},Error,FunctionPrototypeCall(t,e,...r){return t.call(e,...r)},FunctionPrototypeSymbolHasInstance(t,e){return Function.prototype[Symbol.hasInstance].call(t,e)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(t,e){return Object.defineProperties(t,e)},ObjectDefineProperty(t,e,r){return Object.defineProperty(t,e,r)},ObjectGetOwnPropertyDescriptor(t,e){return Object.getOwnPropertyDescriptor(t,e)},ObjectKeys(t){return Object.keys(t)},ObjectSetPrototypeOf(t,e){return Object.setPrototypeOf(t,e)},Promise,PromisePrototypeCatch(t,e){return t.catch(e)},PromisePrototypeThen(t,e,r){return t.then(e,r)},PromiseReject(t){return Promise.reject(t)},PromiseResolve(t){return Promise.resolve(t)},ReflectApply:Reflect.apply,RegExpPrototypeTest(t,e){return t.test(e)},SafeSet:Set,String,StringPrototypeSlice(t,e,r){return t.slice(e,r)},StringPrototype
`;super(r),this.name="AggregateError",this.errors=e}};d9e.exports={AggregateError:c9e,kEmptyObject:Object.freeze({}),once(t){let e=!1;return function(...r){e||(e=!0,t.apply(this,r))}},createDeferredPromise:function(){let t,e;return{promise:new Promise((n,o)=>{t=n,e=o}),resolve:t,reject:e}},promisify(t){return new Promise((e,r)=>{t((n,...o)=>n?r(n):e(...o))})},debuglog(){return function(){}},format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let o=e.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}},types:{isAsyncFunction(t){return t instanceof B1n},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:z1n,deprecate(t,e){return t},addAbortListener:Wne().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);htr(e,"signal"),V1n(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[F1n]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[k1n](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:q1n.any||function(e){if(e.length===1)return e[0];let r=new U1n,n=()=>r.abort();return e.forEach(o=>{htr(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};d9e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var Qb=S((Nva,btr)=>{"use strict";var{format:H1n,inspect:v0e,AggregateError:W1n}=Xy(),J1n=globalThis.AggregateError||W1n,K1n=Symbol("kIsNodeError"),G1n=["string","function","number","object","Function","Object","boolean","bigint","symbol"],X1n=/^([A-Z][a-z0-9]*)+$/,Z1n="__node_internal_",w0e={};function R2(t,e){if(!t)throw new w0e.ERR_INTERNAL_ASSERTION(e)}function gtr(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function Y1n(t,e,r){if(typeof e=="function")return R2(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return R2(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:H1n(e,...r)}function Bg(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(Y1n(t,e,i))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[K1n]=!0,w0e[t]=n}function ytr(t){let e=Z1n+t.name;return Object.defineProperty(t,"name",{value:e}),t}function Q1n(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new J1n([e,t],e.message);return r.code=e.code,r}return t||e}var f9e=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new w0e.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Bg("ERR_ASSERTION","%s",Error);Bg("ERR_INVALID_ARG_TYPE",(t,e,r)=>{R2(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let o=[],i=[],a=[];for(let u of e)R2(typeof u=="string","All expected entries have to be of type string"),G1n.includes(u)?o.push(u.toLowerCase()):X1n.test(u)?i.push(u):(R2(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>
`)>=0)return!1;return!0}function Pkn(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=cE.call(Array(t.indent+1)," ");else return null;return{base:r,prev:cE.call(Array(e+1),r)}}function A7e(t,e){if(t.length===0)return"";var r=`
`+e.prev+e.base;return r+cE.call(t,","+r)+`
`+e.prev}function Z0e(t,e){var r=I7e(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=Z1(t,o)?e(t[o],t):""}var i=typeof O7e=="function"?O7e(t):[],a;if(zK){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)Z1(t,u)&&(r&&String(Number(u))===u&&u<t.length||zK&&a["$"+u]instanceof Symbol||(Mor.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof O7e=="function")for(var l=0;l<i.length;l++)Ror.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var For=S((cwa,Lor)=>{"use strict";var Mkn=coe(),Rkn=z2(),eCe=function(t,e,r){for(var n=t,o;(o=n.next)!=null;n=o)if(o.key===e)return n.next=o.next,r||(o.next=t.next,t.next=o),o},Ikn=function(t,e){if(t){var r=eCe(t,e);return r&&r.value}},Akn=function(t,e,r){var n=eCe(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},Nkn=function(t,e){return t?!!eCe(t,e):!1},Dkn=function(t,e){if(t)return eCe(t,e,!0)};Lor.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new Rkn("Side channel does not contain "+Mkn(n))},delete:function(n){var o=e&&e.next,i=Dkn(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return Ikn(e,n)},has:function(n){return Nkn(e,n)},set:function(n,o){e||(e={next:void 0}),Akn(e,n,o)}};return r}});var $7e=S((dwa,kor)=>{"use strict";kor.exports=Object});var Uor=S((fwa,qor)=>{"use strict";qor.exports=Error});var zor=S((pwa,Bor)=>{"use strict";Bor.exports=EvalError});var Hor=S((mwa,Vor)=>{"use strict";Vor.exports=RangeError});var Jor=S((hwa,Wor)=>{"use strict";Wor.exports=ReferenceError});var Gor=S((gwa,Kor)=>{"use strict";Kor.exports=SyntaxError});var Zor=S((ywa,Xor)=>{"use strict";Xor.exports=URIError});var Qor=S((bwa,Yor)=>{"use strict";Yor.exports=Math.abs});var tir=S((_wa,eir)=>{"use strict";eir.exports=Math.floor});var nir=S((vwa,rir)=>{"use strict";rir.exports=Math.max});var iir=S((wwa,oir)=>{"use strict";oir.exports=Math.min});var sir=S((Swa,air)=>{"use strict";air.exports=Math.pow});var lir=S((Cwa,uir)=>{"use strict";uir.exports=Math.round});var dir=S((xwa,cir)=>{"use strict";cir.exports=Number.isNaN||function(e){return e!==e}});var pir=S((Twa,fir)=>{"use strict";var jkn=dir();fir.exports=function(e){return jkn(e)||e===0?e:e<0?-1:1}});var hir=S((Owa,mir)=>{"use strict";mir.exports=Object.getOwnPropertyDescriptor});var L7e=S((Ewa,gir)=>{"use strict";var tCe=hir();if(tCe)try{tCe([],"length")}catch{tCe=null}gir.exports=tCe});var bir=S((Pwa,yir)=>{"use strict";var rCe=Object.defineProperty||!1;if(rCe)try{rCe({},"a",{value:1})}catch{rCe=!1}yir.exports=rCe});var vir=S((Mwa,_ir)=>{"use strict";_ir.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var o=42;e[r]=o;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(e,r);if(s.value!==o||s.enumerable!==!0)return!1}return!0}});var Cir=S((Rwa,Sir)=>{"use strict";var wir=typeof Symbol<"u"&&Symbol,$kn=vir();Sir.exports=function(){return typeof wir!="function"||typeof Symbol!="function"||typeof wir("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:$kn()}});var F7e=S((Iwa,xir)=>{"use strict";xir.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var k7e=S((Awa,Tir)=>{"use strict";var Lkn=$7e();Tir.exports=Lkn.getPrototypeOf||null});var Pir=S((Nwa,Eir)=>{"use strict";var Fkn="Function.prototype.bind called on incompatible ",kkn=Object.prototype.toString,qkn=Math.max,Ukn="[object Function]",Oir=function(e,r){for(var n=[],o=0;o<e.length;o+=1)n[o]=e[o];for(var i=0;i<r.length;i+=1)n[i+e.length]=r[i];return n},Bkn=function(e,r){
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return tsr(this,arguments,function*(){var r,n,o,i;this.controller.signal;let a=rsr(this.stream),s="",u=!1;try{for(var l=!0,c=esr(a),d;d=yield Cx(c.next()),r=d.done,!r;l=!0){i=d.value,l=!1;let f=i;s+=this.decodeChunk(f);let p;for(;(p=s.indexOf(this.messageTerminator))>=0;){let m=s.slice(0,p+1);if(s=s.slice(p+this.messageTerminator.length),!m.trim())continue;if(!u&&this.prefix!=null){let y=m.indexOf(this.prefix);if(y===-1)continue;u=!0,m=m.slice(y+this.prefix.length)}if(this.streamTerminator!=null&&m.includes(this.streamTerminator))return yield Cx(void 0);let h=yield Cx(this.parse(JSON.parse(m)));yield yield Cx(h),u=!1}}}catch(f){n={error:f}}finally{try{!l&&!r&&(o=c.return)&&(yield Cx(o.call(c)))}finally{if(n)throw n.error}}})}[Symbol.asyncIterator](){return tsr(this,arguments,function*(){var r,n,o,i;try{for(var a=!0,s=esr(this.iterMessages()),u;u=yield Cx(s.next()),r=u.done,!r;a=!0)i=u.value,a=!1,yield yield Cx(i)}catch(l){n={error:l}}finally{try{!a&&!r&&(o=s.return)&&(yield Cx(o.call(s)))}finally{if(n)throw n.error}}})}decodeChunk(e){let r="";if(typeof TextDecoder<"u"){let n=new TextDecoder("utf8");r+=n.decode(e)}else TBn.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};Tw.Stream=fXe;function rsr(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return Qar(this,void 0,void 0,function*(){try{let r=yield e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}})},return(){return Qar(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}});var nsr=S(SCe=>{"use strict";Object.defineProperty(SCe,"__esModule",{value:!0});SCe.Stream=void 0;var EBn=pXe();Object.defineProperty(SCe,"Stream",{enumerable:!0,get:function(){return EBn.Stream}})});var osr=S(Soe=>{"use strict";var PBn=Soe&&Soe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Soe,"__esModule",{value:!0});Soe.encodeAsFormParameter=RBn;var MBn=PBn(tXe());function RBn(t){let r=MBn.default.stringify(t,{encode:!1}).split("&").map(n=>{let[o,i]=n.split("=");return[o,i]});return Object.fromEntries(r)}});var ssr=S((CSa,asr)=>{"use strict";var mXe=Object.defineProperty,IBn=Object.getOwnPropertyDescriptor,ABn=Object.getOwnPropertyNames,NBn=Object.prototype.hasOwnProperty,DBn=(t,e)=>{for(var r in e)mXe(t,r,{get:e[r],enumerable:!0})},jBn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ABn(e))!NBn.call(t,o)&&o!==r&&mXe(t,o,{get:()=>e[o],enumerable:!(n=IBn(e,o))||n.enumerable});return t},$Bn=t=>jBn(mXe({},"__esModule",{value:!0}),t),isr={};DBn(isr,{Blob:()=>kBn,File:()=>qBn,FormData:()=>FBn});asr.exports=$Bn(isr);var LBn=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:FBn,Blob:kBn,File:qBn}=LBn});var vsr=S((xSa,_sr)=>{"use strict";var yXe=Object.defineProperty,UBn=Object.getOwnPropertyDescriptor,BBn=Object.getOwnPropertyNames,zBn=Object.prototype.hasOwnProperty,VBn=(t,e)=>{for(var r in e)yXe(t,r,{get:e[r],enumerable:!0})},HBn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of BBn(e))!zBn.call(t,o)&&o!==r&&yXe(t,o,{get:()=>e[o],enumerable:!(n=UBn(e,o))||n.enumerable});return t},WBn=t=>HBn(yXe({},"__esModule",{value:!0}),t),bXe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},Uc=(t,e,r)=>(bXe(t,e,"read from private field"),r?r.call(t):e.get(t)),pE=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},Coe=(t,e,r,n)=>(bXe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),hXe=(t,e,r)=>(bXe(t,e,"access private method"),r),msr={};VBn(msr,{FormDataEncoder:()=>ezn,isFile:()=>G2,isFormData:()=>ysr});_sr.exports=WBn(msr);var Y1=t=>typeof t=="function",JBn=t=>Y1(t[Symbol.asyncIterator]),usr=65536;function*hsr(t){if(t.byteLength<=usr){yield t;return}let e=
2026-01-05 13:03:55 +08:00
`||e===`
`&&n[r-1]!=="\r"?`\r
2026-02-24 07:55:02 +08:00
`:e),ZBn=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function dsr(t){if(ZBn(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function fsr(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var YBn=t=>new Proxy(t,{get:(e,r)=>fsr(e,r),has:(e,r)=>fsr(e,r)!==void 0}),ysr=t=>!!(t&&Y1(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&Y1(t.append)&&Y1(t.getAll)&&Y1(t.entries)&&Y1(t[Symbol.iterator])),psr=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),G2=t=>!!(t&&typeof t=="object"&&Y1(t.constructor)&&t[Symbol.toStringTag]==="File"&&Y1(t.stream)&&t.name!=null),QBn={enableAdditionalHeaders:!1},CCe={writable:!1,configurable:!1},Ek,xoe,xCe,Toe,K2,Ooe,Eoe,TCe,OCe,_Xe,gXe,bsr,ezn=class{constructor(t,e,r){if(pE(this,OCe),pE(this,gXe),pE(this,Ek,`\r
`),pE(this,xoe,void 0),pE(this,xCe,void 0),pE(this,Toe,"-".repeat(2)),pE(this,K2,new TextEncoder),pE(this,Ooe,void 0),pE(this,Eoe,void 0),pE(this,TCe,void 0),!ysr(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(dsr(e)?r=e:n=e,n||(n=XBn()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!dsr(r))throw new TypeError("Expected options argument to be an object.");Coe(this,Eoe,Array.from(t.entries())),Coe(this,TCe,{...QBn,...r}),Coe(this,xoe,Uc(this,K2).encode(Uc(this,Ek))),Coe(this,xCe,Uc(this,xoe).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,Coe(this,Ooe,Uc(this,K2).encode(`${Uc(this,Toe)}${this.boundary}${Uc(this,Toe)}${Uc(this,Ek).repeat(2)}`));let o={"Content-Type":this.contentType},i=hXe(this,gXe,bsr).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=YBn(Object.freeze(o)),Object.defineProperties(this,{boundary:CCe,contentType:CCe,contentLength:CCe,headers:CCe})}*values(){for(let[t,e]of Uc(this,Eoe)){let r=G2(e)?e:Uc(this,K2).encode(gsr(e));yield hXe(this,OCe,_Xe).call(this,t,r),yield r,yield Uc(this,xoe)}yield Uc(this,Ooe)}async*encode(){for(let t of this.values())G2(t)?yield*GBn(t.stream()):yield*hsr(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};Ek=new WeakMap;xoe=new WeakMap;xCe=new WeakMap;Toe=new WeakMap;K2=new WeakMap;Ooe=new WeakMap;Eoe=new WeakMap;TCe=new WeakMap;OCe=new WeakSet;_Xe=function(t,e){let r="";if(r+=`${Uc(this,Toe)}${this.boundary}${Uc(this,Ek)}`,r+=`Content-Disposition: form-data; name="${psr(t)}"`,G2(e)&&(r+=`; filename="${psr(e.name)}"${Uc(this,Ek)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Uc(this,TCe).enableAdditionalHeaders===!0){let n=G2(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Uc(this,Ek)}Content-Length: ${n}`)}return Uc(this,K2).encode(`${r}${Uc(this,Ek).repeat(2)}`)};gXe=new WeakSet;bsr=function(){let t=0;for(let[e,r]of Uc(this,Eoe)){let n=G2(r)?r:Uc(this,K2).encode(gsr(r)),o=G2(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=hXe(this,OCe,_Xe).call(this,e,n).byteLength,t+=o,t+=Uc(this,xCe)}return String(t+Uc(this,Ooe).byteLength)}});var Ssr=S((OSa,wsr)=>{"use strict";wsr.exports=typeof self=="object"?self.FormData:window.FormData});var Csr=S(zg=>{"use strict";var tzn=zg&&zg.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),rzn=zg&&zg.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o8=zg&&zg.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&tzn(r,e,n[o]);return rzn(r,e),r}}(),Pk=zg&&zg.__awaiter||function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(c){try{l(n.next(c))}catch(d){a(d)}}function u(c){try{l(n.throw(c))}catch(d){a(d)}}function l(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(t,e||[])).next())})};Object.defineProperty(zg,"__esModule",{value:!0});zg.WebFormData=zg.Node16FormData=zg.Node18FormData=void 0;zg.newFormData=nzn;var ECe=GK();function vXe(t){return typeof t=="object"&&t!=null&&"name"in t}function nzn(){return Pk(this,void 0,void 0,function*(){let t;return ECe.RUNTIME.type==="node"&&ECe.RUNTIME.parsedVersion!=null&&ECe.RUNTIME.parsedVersion>=18?t=new PCe:ECe.RUNTIME.type==="node"?t=new MCe:t=new RCe,yield t.setup(),t})}var PCe=class{setup(){return Pk(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>o8(ssr()))).FormData})}append(e
`)),{ok:!0,value:e}):n}}});var xXe=S(CXe=>{"use strict";Object.defineProperty(CXe,"__esModule",{value:!0});CXe.stringifyValidationError=czn;function czn(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}});var OXe=S(ACe=>{"use strict";Object.defineProperty(ACe,"__esModule",{value:!0});ACe.JsonError=void 0;var dzn=xXe(),TXe=class t extends Error{constructor(e){super(e.map(dzn.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};ACe.JsonError=TXe});var PXe=S(NCe=>{"use strict";Object.defineProperty(NCe,"__esModule",{value:!0});NCe.ParseError=void 0;var fzn=xXe(),EXe=class t extends Error{constructor(e){super(e.map(fzn.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};NCe.ParseError=EXe});var Rsr=S(X2=>{"use strict";Object.defineProperty(X2,"__esModule",{value:!0});X2.getSchemaUtils=Poe;X2.nullable=Osr;X2.optional=Esr;X2.optionalNullable=Psr;X2.transform=Msr;var MXe=Uh(),pzn=OXe(),mzn=PXe();function Poe(t){return{nullable:()=>Osr(t),optional:()=>Esr(t),optionalNullable:()=>Psr(t),transform:e=>Msr(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new mzn.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new pzn.JsonError(n.errors)}}}function Osr(t){let e={parse:(r,n)=>r==null?{ok:!0,value:null}:t.parse(r,n),json:(r,n)=>r==null?{ok:!0,value:null}:t.json(r,n),getType:()=>MXe.SchemaType.NULLABLE};return Object.assign(Object.assign({},e),Poe(e))}function Esr(t){let e={parse:(r,n)=>r==null?{ok:!0,value:void 0}:t.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:t.json(r,n),getType:()=>MXe.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),Poe(e))}function Psr(t){let e={parse:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:t.parse(r,n),json:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:t.json(r,n),getType:()=>MXe.SchemaType.OPTIONAL_NULLABLE};return Object.assign(Object.assign({},e),Poe(e))}function Msr(t,e){let r={parse:(n,o)=>{let i=t.parse(n,o);return i.ok?{ok:!0,value:e.transform(i.value)}:i},json:(n,o)=>{let i=e.untransform(n);return t.json(i,o)},getType:()=>t.getType()};return Object.assign(Object.assign({},r),Poe(r))}});var Z_=S(f0=>{"use strict";Object.defineProperty(f0,"__esModule",{value:!0});f0.ParseError=f0.JsonError=f0.transform=f0.optional=f0.getSchemaUtils=void 0;var RXe=Rsr();Object.defineProperty(f0,"getSchemaUtils",{enumerable:!0,get:function(){return RXe.getSchemaUtils}});Object.defineProperty(f0,"optional",{enumerable:!0,get:function(){return RXe.optional}});Object.defineProperty(f0,"transform",{enumerable:!0,get:function(){return RXe.transform}});var hzn=OXe();Object.defineProperty(f0,"JsonError",{enumerable:!0,get:function(){return hzn.JsonError}});var gzn=PXe();Object.defineProperty(f0,"ParseError",{enumerable:!0,get:function(){return gzn.ParseError}})});var Asr=S(IXe=>{"use strict";Object.defineProperty(IXe,"__esModule",{value:!0});IXe.bigint=vzn;var yzn=Uh(),Isr=e_(),bzn=mE(),_zn=Z_();function vzn(){let t={parse:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e=="bigint"?{ok:!0,value:e}:typeof e=="number"?{ok:!0,value:BigInt(e)}:{ok:!1,errors:[{path:r,message:(0,Isr.getErrorMessageForIncorrectType)(e,"bigint | number")}]},json:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="bigint"?{ok:!1,errors:[{path:r,message:(0,Isr.getErrorMessageForIncorrectType)(e,"bigint")}]}:{ok:!0,value:e},getType:()=>yzn.SchemaType.BIGINT};return Object.assign(Object.assign({},(0,bzn.maybeSkipValidation)(t)),(0,_zn.getSchemaUtils)(t))}});var Nsr=S(DCe=>{"use strict";Object.defineProperty(DCe,"__esModule",{value:!0});DCe.bigint=void 0;var wzn=Asr();Object.defineProperty(DCe,"bigint",{enumerable:!0,get:function(){return wzn.bigint}})});var Dsr=S(NXe=>{"use strict";Object.defineProperty(NXe,"__esModule",{value:!0});NXe.date=Ozn;var Szn=Uh(),AXe=e_(),Czn=mE(),xzn=Z_(),Tzn=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(0
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){return joe(this,void 0,void 0,function*(){var o;yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};Hg.StreamUtils=lZe;function Eur(t,e){return Loe(this,arguments,function*(){var n,o,i,a;if(!t.body)throw e?.abort(),new l8.CohereError({message:"Attempted to iterate over a response with no body"});let s=new cZe,u=new Mk,l=dZe(t.body);try{for(var c=!0,d=$oe(O2n(l)),f;f=yield Jl(d.next()),n=f.done,!n;c=!0){a=f.value,c=!1;let p=a;for(let m of u.decode(p)){let h=s.decode(m);h&&(yield yield Jl(h))}}}catch(p){o={error:p}}finally{try{!c&&!n&&(i=d.return)&&(yield Jl(i.call(d)))}finally{if(o)throw o.error}}for(let p of u.flush()){let m=s.decode(p);m&&(yield yield Jl(m))}})}function O2n(t){return Loe(this,arguments,function*(){var r,n,o,i;let a=new Uint8Array;try{for(var s=!0,u=$oe(t),l;l=yield Jl(u.next()),r=l.done,!r;s=!0){i=l.value,s=!1;let c=i;if(c==null)continue;let d=c instanceof ArrayBuffer?new Uint8Array(c):typeof c=="string"?new TextEncoder().encode(c):c,f=new Uint8Array(a.length+d.length);f.set(a),f.set(d,a.length),a=f;let p;for(;(p=E2n(a))!==-1;)yield yield Jl(a.slice(0,p)),a=a.slice(p)}}catch(c){n={error:c}}finally{try{!s&&!r&&(o=u.return)&&(yield Jl(o.call(u)))}finally{if(n)throw n.error}}a.length>0&&(yield yield Jl(a))})}function E2n(t){for(let n=0;n<t.length-2;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var cZe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=M2n(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},Mk=class t{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let r=this.decodeText(e);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);return n&&o.pop(),o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(e){var r;if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new l8.CohereError({message:`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`})}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return(r=this.textDecoder)!==null&&r!==void 0||(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new l8.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new l8.CohereError({message:"Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error."})}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};Hg.LineDecoder=Mk;Mk.NEWLINE_CHARS=new Set([`
`,"\r"]);Mk.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function P2n(t){let e=new Mk,r=[];for(let n of t)r.push(...e.decode(n));return r}function M2n(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function dZe(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return joe(this,void 0,void 0,function*(){try{let r=yield e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}})},return(){return joe(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}});var koe=S(hE=>{"use strict";var R2n=hE&&hE.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),I2n=hE&&hE.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),A2n=hE&&hE.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&R2n(r,e,n[o]);return I2n(r,e),r}}();Object.defineProperty(hE,"__esModule",{value:!0});hE.Document=void 0;var Foe=A2n(se());hE.Document=Foe.serialization.object({data:Foe.serialization.record(Foe.serialization.string(),Foe.serialization.unknown()),id:Foe.serialization.string().optional()})});var fZe=S(gE=>{"use strict";var N2n=gE&&gE.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),D2n=gE&&gE.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),j2n=gE&&gE.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&N2n(r,e,n[o]);return D2n(r,e),r}}();Object.defineProperty(gE,"__esModule",{value:!0});gE.V2ChatStreamRequestDocumentsItem=void 0;var Mur=j2n(se()),$2n=koe();gE.V2ChatStreamRequestDocumentsItem=Mur.serialization.undiscriminatedUnion([Mur.serialization.string(),$2n.Document])});var pZe=S(yE=>{"use strict";var L2n=yE&&yE.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),F2n=yE&&yE.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),k2n=yE&&yE.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&L2n(r,e,n[o]);return F2n(r,e),r}}();Object.defineProperty(yE,"__esModule",{value:!0});yE.V2ChatStreamRequestSafetyMode=void 0;var q2n=k2n(se());yE.V2ChatStreamRequestSafetyMode=q2n.serialization.enum_(["CONTEXTUAL","STRICT","OFF"])});var mZe=S(bE=>{"use strict";var U2n=bE&&bE.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(
`)}}}}catch(P){s={error:P}}finally{try{!b&&!a&&(u=_.return)&&(yield u.call(_))}finally{if(s)throw s.error}}for(let P of O.flush()){let R=(0,uu.parseAWSEvent)(P);if(R){let I=yield(0,uu.mapResponseFromBedrock)(m,d,f,R);E.push(JSON.stringify(I)+`
`)}}return E.end(),{ok:!0,body:E,rawResponse:g.rawResponse}}else{let T=yield g.body;return{ok:!0,body:yield(0,uu.mapResponseFromBedrock)(m,d,f,T),rawResponse:g.rawResponse}}}catch(T){throw T}});uu.fetchOverride=dio});var lD=S(Lxe=>{"use strict";Object.defineProperty(Lxe,"__esModule",{value:!0});Lxe.CohereEnvironment=void 0;Lxe.CohereEnvironment={Production:"https://api.cohere.com"}});var kk=S((Jcr,Fxe)=>{(function(t,e,r){typeof Fxe<"u"&&Fxe.exports?Fxe.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",Jcr,function(){function t(e){var r=[];if(e.length===0)return"";if(typeof e[0]!="string")throw new TypeError("Url must be a string. Received "+e[0]);if(e[0].match(/^[^/:]+:\/*$/)&&e.length>1){var n=e.shift();e[0]=n+e[0]}e[0].match(/^file:\/\/\//)?e[0]=e[0].replace(/^([^/:]+):\/*/,"$1:///"):e[0]=e[0].replace(/^([^/:]+):\/*/,"$1://");for(var o=0;o<e.length;o++){var i=e[o];if(typeof i!="string")throw new TypeError("Url must be a string. Received "+i);i!==""&&(o>0&&(i=i.replace(/^[\/]+/,"")),o<e.length-1?i=i.replace(/[\/]+$/,""):i=i.replace(/[\/]+$/,"/"),r.push(i))}var a=r.join("/");a=a.replace(/\/(\?|&|#[^!])/g,"$1");var s=a.split("?");return a=s.shift()+(s.length>0?"?":"")+s.join("&"),a}return function(){var e;return typeof arguments[0]=="object"?e=arguments[0]:e=[].slice.call(arguments),t(e)}})});var Get=S(tv=>{"use strict";var fio=tv&&tv.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),pio=tv&&tv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),cie=tv&&tv.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&fio(r,e,n[o]);return pio(r,e),r}}(),I8=tv&&tv.__awaiter||function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(c){try{l(n.next(c))}catch(d){a(d)}}function u(c){try{l(n.throw(c))}catch(d){a(d)}}function l(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(t,e||[])).next())})},mio=tv&&tv.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(tv,"__esModule",{value:!0});tv.V2=void 0;var kxe=cie(lD()),oa=cie(se()),Vn=cie(D1()),qk=cie(uD()),qxe=mio(kk()),Jg=cie(kc()),Ket=class{constructor(e={}){this._options=e}chatStream(e,r){return oa.HttpResponsePromise.fromPromise(this.__chatStream(e,r))}__chatStream(e,r){return I8(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:oa.fetcher)({url:(0,qxe.default)((i=(o=yield oa.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield oa.Supplier.get(this._options.environment))!==null&&i!==void 0?i:kxe.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield oa.Supplier.get(this._options.clientName))!=null?yield oa.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.19.0","User-Agent":"cohere-ai/7.19.0","X-Fern-Runtime":oa.RUNTIME.type,"X-Fern-Runtime-Version":oa.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},qk.V2ChatStreamRequest.jsonOrThrow(e,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!0}),responseType:"sse",timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(a.ok)return{data:new oa.Stream({stream:a.body,parse:s=>I8(this,void 0,void
`}}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 400:throw new Ne.BadRequestError(u.error.body,u.rawResponse);case 401:throw new Ne.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new Ne.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new Ne.NotFoundError(u.error.body,u.rawResponse);case 422:throw new Ne.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new Ne.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new Ne.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new Ne.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new Ne.InternalServerError(u.error.body,u.rawResponse);case 501:throw new Ne.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new Ne.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new Ne.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new Do.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new Do.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Do.CohereTimeoutError("Timeout exceeded when calling POST /v1/chat.");case"unknown":throw new Do.CohereError({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}chat(e,r){return ft.HttpResponsePromise.fromPromise(this.__chat(e,r))}__chat(e,r){return sv(this,void 0,void 0,function*(){var n,o,i;let{accepts:a}=e,s=tdr(e,["accepts"]),u=yield((n=this._options.fetcher)!==null&&n!==void 0?n:ft.fetcher)({url:(0,Px.default)((i=(o=yield ft.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ft.Supplier.get(this._options.environment))!==null&&i!==void 0?i:Ex.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield ft.Supplier.get(this._options.clientName))!=null?yield ft.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.19.0","User-Agent":"cohere-ai/7.19.0","X-Fern-Runtime":ft.RUNTIME.type,"X-Fern-Runtime-Version":ft.RUNTIME.version,Accepts:a??void 0},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},pd.ChatRequest.jsonOrThrow(s,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:pd.NonStreamedChatResponse.parseOrThrow(u.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 400:throw new Ne.BadRequestError(u.error.body,u.rawResponse);case 401:throw new Ne.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new Ne.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new Ne.NotFoundError(u.error.body,u.rawResponse);case 422:throw new Ne.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new Ne.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new Ne.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new Ne.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new Ne.InternalServerError(u.error.body,u.rawResponse);case 501:throw new Ne.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new Ne.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new Ne.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new Do.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new Do.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Do.CohereTimeoutError("Timeout exceeded when calling POST
`}}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new Ne.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Ne.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Ne.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Ne.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Ne.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Ne.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Ne.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Ne.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Ne.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Ne.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Ne.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Ne.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new Do.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new Do.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new Do.CohereTimeoutError("Timeout exceeded when calling POST /v1/generate.");case"unknown":throw new Do.CohereError({message:a.error.errorMessage,rawResponse:a.rawResponse})}})}generate(e,r){return ft.HttpResponsePromise.fromPromise(this.__generate(e,r))}__generate(e,r){return sv(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:ft.fetcher)({url:(0,Px.default)((i=(o=yield ft.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ft.Supplier.get(this._options.environment))!==null&&i!==void 0?i:Ex.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield ft.Supplier.get(this._options.clientName))!=null?yield ft.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.19.0","User-Agent":"cohere-ai/7.19.0","X-Fern-Runtime":ft.RUNTIME.type,"X-Fern-Runtime-Version":ft.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},pd.GenerateRequest.jsonOrThrow(e,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(a.ok)return{data:pd.Generation.parseOrThrow(a.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new Ne.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Ne.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Ne.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Ne.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Ne.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Ne.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Ne.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Ne.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Ne.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Ne.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Ne.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Ne.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new Do.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new Do.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new Do.CohereTimeoutError("Timeout exceeded when calling POST /v1/generate.");case"unknown":throw new
`).filter(Boolean).reduce((n,o)=>{let[i,a,...s]=o.split(" "),u=Number.parseInt(a,10);return s.forEach((l,c)=>n[l]=u+c),n},{});for(let[n,o]of Object.entries(r)){let i=_dr.default.toByteArray(n);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[o,i])=>(n[i]=this.textEncoder.encode(o),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),o=gtt.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),s=new Set(r==="all"?Object.keys(this.specialTokens).filter(l=>!a.has(l)):r);if(s.size>0){let l=gtt.specialTokenRegex([...s]),c=t.match(l);if(c!=null)throw new Error(`The text contains a special token that is not allowed: ${c[0]}`)}let u=0;for(;;){let l=null,c=u;for(;o.lastIndex=c,l=o.exec(t),!(l==null||a.has(l[0]));)c=l.index+1;let d=l?.index??t.length;for(let p of t.substring(u,d).matchAll(n)){let m=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...aao(m,this.rankMap))}if(l==null)break;let f=this.specialTokens[l[0]];i.push(f),u=l.index+l[0].length}return i}decode(t){let e=[],r=0;for(let i=0;i<t.length;++i){let a=t[i],s=this.textMap.get(a)??this.inverseSpecialTokens[a];s!=null&&(e.push(s),r+=s.length)}let n=new Uint8Array(r),o=0;for(let i of e)n.set(i,o),o+=i.length;return this.textDecoder.decode(n)}},Gxe=gtt;oao(Gxe,"specialTokenRegex",t=>new RegExp(t.map(e=>sao(e)).join("|"),"g"))});var wdr=v(()=>{vdr()});async function btt(t){return t in Xxe||(Xxe[t]=lao.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new Gxe(e)).catch(e=>{throw delete Xxe[t],e})),await Xxe[t]}async function Zxe(t){return btt(ytt(t))}var uao,Xxe,lao,_tt=v(()=>{Jo();Jz();wdr();uao={};$t(uao,{encodingForModel:()=>Zxe,getEncoding:()=>btt});Xxe={},lao=new ES({})});function Aw(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 cao,Yxe,dao,Sdr,Cdr,fao,k8,bV,Nw=v(()=>{Jo();UC();Jz();Pg();lte();bdr();_tt();cao={};$t(cao,{BaseLangChain:()=>k8,BaseLanguageModel:()=>bV,calculateMaxTokens:()=>Cdr,getEmbeddingContextSize:()=>dao,getModelContextSize:()=>Sdr,getModelNameForTiktoken:()=>Yxe,isOpenAITool:()=>Aw});Yxe=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,dao=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},Sdr=t=>{switch(Yxe(t)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};Cdr=async({prompt:t,modelName:e})=>{let r;try{r=(awa
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function ufr(t){var e,r,n,o;let i=[];if(!((r=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||r===void 0)&&r.parts)for(let a of(o=(n=t.candidates)===null||n===void 0?void 0:n[0].content)===null||o===void 0?void 0:o.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}function aTe(t){return!!t.finishReason&&Xao.includes(t.finishReason)}function Hk(t){var e,r,n;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}`),!((r=t.promptFeedback)===null||r===void 0)&&r.blockReasonMessage&&(o+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((n=t.candidates)===null||n===void 0)&&n[0]){let i=t.candidates[0];aTe(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function Pie(t){return this instanceof Pie?(this.v=t,this):new Pie(t)}function Zao(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),o,i=[];return o={},a("next"),a("throw"),a("return"),o[Symbol.asyncIterator]=function(){return this},o;function a(f){n[f]&&(o[f]=function(p){return new Promise(function(m,h){i.push([f,p,m,h])>1||s(f,p)})})}function s(f,p){try{u(n[f](p))}catch(m){d(i[0][3],m)}}function u(f){f.value instanceof Pie?Promise.resolve(f.value.v).then(l,c):d(i[0][2],f)}function l(f){s("next",f)}function c(f){s("throw",f)}function d(f,p){f(p),i.shift(),i.length&&s(i[0][0],i[0][1])}}function Yao(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=tso(e),[n,o]=r.tee();return{stream:eso(n),response:Qao(o)}}async function Qao(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return Ftt(rso(e));e.push(o)}}function eso(t){return Zao(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield Pie(r.read());if(o)break;yield yield Pie(Ftt(n))}})}function tso(t){let e=t.getReader();return new ReadableStream({start(n){let o="";return i();function i(){return e.read().then(({value:a,done:s})=>{if(s){if(o.trim()){n.error(new Hh("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(lfr),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new Hh(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(lfr)}return i()}).catch(a=>{let s=a;throw s.stack=a.stack,s.name==="AbortError"?s=new uTe("Request aborted when reading from the stream"):s=new Hh("Error reading from the stream"),s})}}})}function rso(t){let e=t[t.length-1],r={promptFeedback:e?.promptFeedback};for(let n of t){if(n.candidates){let o=0;for(let i of n.candidates)if(r.candidates||(r.candidates=[]),r.candidates[o]||(r.candidates[o]={index:o}),r.candidates[o].citationMetadata=i.citationMetadata,r.candidates[o].groundingMetadata=i.groundingMetadata,r.candidates[o].finishReason=i.finishReason,r.candidates[o].finishMessage=i.finishMessage,r.candidates[o].safetyRatings=i.safetyRatings,i.content&&i.content.parts){r.candidates[o].content||(r.candidates[o].content={role:i.content.role||"user",parts:[]});let a={};for(let s of i.content.parts)s.text&&(a.text=s.text),s.functionCall&&(a.functionCall=s.functionCall),s.executableCode&&(a.executableCode=s.executableCode),s.codeExecutionResult&&(a.codeExecutionResult=s.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),r.candidates[o].content.parts.push(a)}o++}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function mfr(t,e,r,n){let o=await Rie(e,xV.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return Yao(o)}async function hfr(t,e,r,n){let i=await(await Rie(e,xV.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:Ftt(i)}}function gfr(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
`)===0?n.substr(1,n.length):n}).forEach(function(n){var o=n.split(":"),i=o.shift().trim();if(i){var a=o.join(":").trim();try{e.append(i,a)}catch(s){console.warn("Response "+s.message)}}}),e}function eA(t,e){if(!(this instanceof eA))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 zm(e.headers),this.url=e.url||"",this._initBody(t)}function Lfr(t,e){return new Promise(function(r,n){var o=new EV(t,e);if(o.signal&&o.signal.aborted)return n(new OV("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:Mso(i.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(i.status<200||i.status>599)?l.status=200:l.status=i.status,l.url="responseURL"in i?i.responseURL:l.headers.get("X-Request-URL");var c="response"in i?i.response:i.responseText;setTimeout(function(){r(new eA(c,l))},0)},i.onerror=function(){setTimeout(function(){n(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){n(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){n(new OV("Aborted","AbortError"))},0)};function s(l){try{return l===""&&ey.location.href?ey.location.href:l}catch{return l}}if(i.open(o.method,s(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(r_.blob?i.responseType="blob":r_.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof zm||ey.Headers&&e.headers instanceof ey.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(q8(l)),i.setRequestHeader(l,Jtt(e.headers[l]))}),o.headers.forEach(function(l,c){u.indexOf(c)===-1&&i.setRequestHeader(c,l)})}else o.headers.forEach(function(l,c){i.setRequestHeader(c,l)});o.signal&&(o.signal.addEventListener("abort",a),i.onreadystatechange=function(){i.readyState===4&&o.signal.removeEventListener("abort",a)}),i.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}var ey,r_,Afr,Dfr,Oso,Rso,OV,Ffr=v(()=>{ey=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},r_={searchParams:"URLSearchParams"in ey,iterable:"Symbol"in ey&&"iterator"in Symbol,blob:"FileReader"in ey&&"Blob"in ey&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in ey,arrayBuffer:"ArrayBuffer"in ey};r_.arrayBuffer&&(Afr=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Dfr=ArrayBuffer.isView||function(t){return t&&Afr.indexOf(Object.prototype.toString.call(t))>-1});zm.prototype.append=function(t,e){t=q8(t),e=Jtt(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};zm.prototype.delete=function(t){delete this.map[q8(t)]};zm.prototype.get=function(t){return t=q8(t),this.has(t)?this.map[t]:null};zm.prototype.has=function(t){return this.map.hasOwnProperty(q8(t))};zm.prototype.set=function(t,e){this.map[q8(t)]=Jtt(e)};zm.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};zm.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),Ktt(t)};zm.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),Ktt(t)};zm.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),Ktt(t)};r_.iterable&&(zm.prototype[Symbol.iterator]=zm.prototype.entries);Oso=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];EV.prototype.clone=function(){return new EV(this,{body:this._bodyInit})};$fr.call(EV.prototype);$fr.call(eA.pro
`);r=a.pop()??"";for(let s of a)try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}}r+=e.decode();for(let o of r.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},kso=t=>{if(!t)return qfr;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let r=new URL(t),n=r.port;n||(e?n=r.protocol==="https:"?"443":"80":n=kfr);let o="";r.username&&(o=r.username,r.password&&(o+=`:${r.password}`),o+="@");let i=`${r.protocol}//${o}${r.hostname}:${n}${r.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i},qso=Object.defineProperty,Uso=(t,e,r)=>e in t?qso(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ztt=(t,e,r)=>(Uso(t,typeof e!="symbol"?e+"":e,r),r),U8=class{constructor(e){Ztt(this,"config"),Ztt(this,"fetch"),Ztt(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=kso(e?.host??qfr)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,r){r.stream=r.stream??!1;let n=`${this.config.host}/api/${e}`;if(r.stream){let i=new AbortController,a=await Wk(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=Fso(a.body),u=new Qtt(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await Wk(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let r=new Uint8Array(e),n="",o=r.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(r[i]);return btoa(n)}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 r of e.messages)r.images&&(r.images=await Promise.all(r.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 Lso(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await Wk(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Xtt(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await Wk(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await Wk(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await Wk(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Xtt(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Xtt(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 Wk(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 Wk(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},CIa=new U8});function Ix(t,e){if(t.function===void 0)return;let r;if(e?.partial)try{r=Mz(t.function.arguments??"{}")}catch{return}else try{r=JSON.parse(t.function.arguments)}catch(o){throw new Ih([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${o.message}`].join(`
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function Jk(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function _0(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var rrt,lv,Ufr=v(()=>{NQ();vS();QN();MJ();dF();A3e();rrt=class extends cF{constructor(e){super(e);x(this,"returnId",!1);x(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);x(this,"lc_serializable",!0);this.returnId=e?.returnId??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,r=!0){let n=e[0].message,o;if(kl(n)&&n.tool_calls?.length?o=n.tool_calls.map(a=>{let{id:s,...u}=a;return this.returnId?{id:s,...u}:u}):n.additional_kwargs.tool_calls!==void 0&&(o=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(s=>Ix(s,{returnId:this.returnId,partial:r}))),!o)return[];let i=[];for(let a of o)if(a!==void 0){let s={type:a.name,args:a.args,id:a.id};i.push(s)}return i}},lv=class extends rrt{constructor(e){super(e);x(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);x(this,"lc_serializable",!0);x(this,"returnId",!1);x(this,"keyName");x(this,"returnSingle",!1);x(this,"zodSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){if(this.zodSchema===void 0)return e;let r=await tF(this.zodSchema,e);if(r.success)return r.data;throw new Ih(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let n=(await super.parsePartialResult(e)).filter(i=>i.type===this.keyName),o=n;if(n.length)return this.returnId||(o=n.map(i=>i.args)),this.returnSingle?o[0]:o}async parseResult(e){let n=(await super.parsePartialResult(e,!1)).filter(a=>a.type===this.keyName),o=n;return n.length?(this.returnId||(o=n.map(a=>a.args)),this.returnSingle?this._validateResult(o[0]):await Promise.all(o.map(a=>this._validateResult(a)))):void 0}}});var Bso,PV=v(()=>{Jo();Ufr();Bso={};$t(Bso,{JsonOutputKeyToolsParser:()=>lv,JsonOutputToolsParser:()=>rrt,convertLangChainToolCallToOpenAI:()=>Jk,makeInvalidToolCall:()=>_0,parseToolCall:()=>Ix})});var nrt,Bfr=v(()=>{Ifr();ta();YI();fTe();Ed();sw();pD();nO();fO();PV();au();uv();Ny();nrt=class extends jd{constructor(e){super(e??{});x(this,"model","llama3");x(this,"numa");x(this,"numCtx");x(this,"numBatch");x(this,"numGpu");x(this,"mainGpu");x(this,"lowVram");x(this,"f16Kv");x(this,"logitsAll");x(this,"vocabOnly");x(this,"useMmap");x(this,"useMlock");x(this,"embeddingOnly");x(this,"numThread");x(this,"numKeep");x(this,"seed");x(this,"numPredict");x(this,"topK");x(this,"topP");x(this,"tfsZ");x(this,"typicalP");x(this,"repeatLastN");x(this,"temperature");x(this,"repeatPenalty");x(this,"presencePenalty");x(this,"frequencyPenalty");x(this,"mirostat");x(this,"mirostatTau");x(this,"mirostatEta");x(this,"penalizeNewline");x(this,"streaming");x(this,"format");x(this,"keepAlive");x(this,"client");x(this,"checkOrPullModel",!1);x(this,"baseUrl","http://127.0.0.1:11434");x(this,"think");this.baseUrl=e?.baseUrl??Xr("OLLAMA_BASE_URL")??this.baseUrl,this.client=new U8({fetch:e?.fetch,host:this.baseUrl,headers:e?.headers}),this.model=e?.model??this.model,this.numa=e?.numa,this.numCtx=e?.numCtx,this.numBatch=e?.numBatch,this.numGpu=e?.numGpu,this.mainGpu=e?.mainGpu,this.lowVram=e?.lowVram,this.f16Kv=e?.f16Kv,this.logitsAll=e?.logitsAll,this.vocabOnly=e?.vocabOnly,this.useMmap=e?.useMmap,this.useMlock=e?.useMlock,this.embeddingOnly=e?.embeddingOnly,this.numThread=e?.numThread,this.numKeep=e?.numKeep,this.seed=e?.seed,this.numPredict=e?.numPredict,this.topK=e?.topK,this.topP=e?.topP,this.tfsZ=e?.tfsZ,this.typicalP
2026-01-21 08:46:13 +08:00
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
2026-02-24 07:55:02 +08:00
`,t}var Hfr=v(()=>{});function Kr(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="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 n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function Pe(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var v0=v(()=>{});var art,srt=v(()=>{art=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return art=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}});function Nie(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Die,pTe=v(()=>{Die=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 Gt,Vm,zc,Kk,tA,B8,z8,V8,H8,W8,J8,K8,G8,X8,Z8,rA,nA=v(()=>{pTe();Gt=class extends Error{},Vm=class t extends Gt{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let i=r;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new Kk({message:n,cause:Die(r)});let i=r?.error;return e===400?new B8(e,i,n,o):e===401?new z8(e,i,n,o):e===403?new V8(e,i,n,o):e===404?new H8(e,i,n,o):e===409?new W8(e,i,n,o):e===422?new J8(e,i,n,o):e===429?new K8(e,i,n,o):e>=500?new G8(e,i,n,o):new t(e,i,n,o)}},zc=class extends Vm{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Kk=class extends Vm{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},tA=class extends Kk{constructor({message:e}={}){super({message:e??"Request timed out."})}},B8=class extends Vm{},z8=class extends Vm{},V8=class extends Vm{},H8=class extends Vm{},W8=class extends Vm{},J8=class extends Vm{},K8=class extends Vm{},G8=class extends Vm{},X8=class extends Gt{constructor(){super("Could not parse response content as the length limit was reached")}},Z8=class extends Gt{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},rA=class extends Error{constructor(e){super(e)}}});function lrt(t){return typeof t!="object"?{}:t??{}}function Jfr(t){if(!t)return!0;for(let e in t)return!1;return!0}function Kfr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Y8(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Vso,Wfr,nb,urt,Gfr,Xfr,hD=v(()=>{nA();Vso=/^[a-z][a-z0-9+.-]*:/i,Wfr=t=>Vso.test(t),nb=t=>(nb=Array.isArray,nb(t)),urt=nb;Gfr=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Gt(`${t} must be an integer`);if(e<0)throw new Gt(`${t} must be a positive integer`);return e},Xfr=t=>{try{return JSON.parse(t)}catch{return}}});var oA,Q8=v(()=>{oA=t=>new Promise(e=>setTimeout(e,t))});var Gk,crt=v(()=>{Gk="6.16.0"});function Hso(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function Jso(){if(typeof navigator>"
`):[]}};Dw=new WeakMap,jw=new WeakMap;MV.NEWLINE_CHARS=new Set([`
`,"\r"]);MV.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function $ie(){}function vTe(t,e,r){return!e||wTe[t]>wTe[r]?$ie:e[t].bind(e)}function md(t){let e=t.logger,r=t.logLevel??"off";if(!e)return euo;let n=vpr.get(e);if(n&&n[0]===r)return n[1];let o={error:vTe("error",e,r),warn:vTe("warn",e,r),info:vTe("info",e,r),debug:vTe("debug",e,r)};return vpr.set(e,[r,o]),o}var wTe,wrt,euo,vpr,gD,Lie=v(()=>{hD();wTe={off:0,error:200,warn:300,info:400,debug:500},wrt=(t,e,r)=>{if(t){if(Kfr(wTe,t))return t;md(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(wTe))}`)}};euo={error:$ie,warn:$ie,info:$ie,debug:$ie},vpr=new WeakMap;gD=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,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*tuo(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Gt("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 Gt("Attempted to iterate over a response with no body");let r=new Srt,n=new MV,o=prt(t.body);for await(let i of ruo(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*ruo(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?eG(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=bpr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function nuo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var Fie,aA,Srt,Crt=v(()=>{v0();nA();jie();_pr();jie();pTe();_Te();Lie();nA();aA=class t{constructor(e,r,n){this.iterator=e,Fie.set(this,void 0),this.controller=r,Kr(this,Fie,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?md(n):console;async function*a(){if(o)throw new Gt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of tuo(e,r))if(!s){if(u.data.startsWith("[DONE]")){s=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let l;try{l=JSON.parse(u.data)}catch(c){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),c}if(l&&l.error)throw new Vm(void 0,l.error,void 0,e.headers);yield l}else{let l;try{l=JSON.parse(u.data)}catch(c){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),c}if(u.event=="error")throw new Vm(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(Nie(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*i(){let s=new MV,u=prt(e);for await(let l of u)for(let c of s.decode(l))yield c;for(let l of s.flush())yield l}async function*a(){if(o)throw new Gt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of i())s||u&&(yield JSON.parse(u));s=!0}catch(u){if(Nie(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(Fie=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller,Pe(this,Fie,"f")),new t(()=>o(r),this.controller,Pe(this,Fie,"f"))]}toReadableStream(){let e=this,r;return frt({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:i}=await r.next();if(i)return n.close();let a=eG(JSON.stringify(o)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};Srt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=nuo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function STe(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return md(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):aA.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let d=await r.json();return xrt(d,r)}return await r.text()})();return md(t).debug(`[${n}] response parsed`,gD({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function xrt(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Trt=v(()=>{Crt();Lie()});var kie,RV,CTe=v(()=>{v0();Trt();RV=class t extends Promise{constructor(e,r,n=STe){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,kie.set(this,void 0),Kr(this,kie,e,"f")}_thenUnwrap(e){return new t(Pe(this,kie,"f"),this.responsePromise,async(r,n)=>xrt(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Pe(this,kie,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};kie=new WeakMap});var xTe,qie,Uie,sA,ci,yD,Lu=v(()=>{v0();nA();Trt();CTe();hD();qie=class{constructor(e,r,n,o){xTe.set(this,void 0),Kr(this,xTe,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Gt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Pe(this,xTe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(xTe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Uie=class extends RV{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await STe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},sA=class extends qie{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},ci=class extends qie{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...lrt(this.options.query),after:r}}:null}},yD=class extends qie{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...lrt(this.options.query),after:e}}:null}}});function tG(t,e,r){return Prt(),new File(t,e??"unknown_file",r)}function Bie(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}function iuo(t){let e=typeof t=="fu
2026-01-05 13:03:55 +08:00
${i.map(f=>f.error).join(`
`)}
${a}
2026-02-24 07:55:02 +08:00
${d}`)}return a},Le=duo(Epr)});var IV,OTe=v(()=>{Vr();Lu();is();IV=class extends Je{list(e,r={},n){return this._client.getAPIList(Le`/chat/completions/${e}/messages`,ci,{query:r,...n})}}});var Ax=v(()=>{nA()});function Vie(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Ppr(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Hie(t){return t?.$brand==="auto-parseable-response-format"}function AV(t){return t?.$brand==="auto-parseable-tool"}function Mpr(t,e){return!e||!Art(e)?{...t,choices:t.choices.map(r=>(Ipr(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:Wie(t,e)}function Wie(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new X8;if(n.finish_reason==="content_filter")throw new Z8;return Ipr(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>huo(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?muo(e,n.message.content):null}}});return{...t,choices:r}}function muo(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 huo(t,e){let r=t.tools?.find(n=>Vie(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:AV(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Rpr(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>Vie(n)&&n.function?.name===e.function.name);return Vie(r)&&(AV(r)||r?.function.strict||!1)}function Art(t){return Hie(t.response_format)?!0:t.tools?.some(e=>AV(e)||e.type==="function"&&e.function.strict===!0)??!1}function Ipr(t){for(let e of t||[])if(e.type!=="function")throw new Gt(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Apr(t){for(let e of t??[]){if(e.type!=="function")throw new Gt(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Gt(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var rG=v(()=>{Ax()});var nG,Nrt,Drt=v(()=>{nG=t=>t?.role==="assistant",Nrt=t=>t?.role==="tool"});var jrt,ETe,PTe,Jie,Kie,MTe,Gie,bD,Xie,RTe,ITe,oG,Npr,Xk,ATe=v(()=>{v0();Ax();Xk=class{constructor(){jrt.add(this),this.controller=new AbortController,ETe.set(this,void 0),PTe.set(this,()=>{}),Jie.set(this,()=>{}),Kie.set(this,void 0),MTe.set(this,()=>{}),Gie.set(this,()=>{}),bD.set(this,{}),Xie.set(this,!1),RTe.set(this,!1),ITe.set(this,!1),oG.set(this,!1),Kr(this,ETe,new Promise((e,r)=>{Kr(this,PTe,e,"f"),Kr(this,Jie,r,"f")}),"f"),Kr(this,Kie,new Promise((e,r)=>{Kr(this,MTe,e,"f"),Kr(this,Gie,r,"f")}),"f"),Pe(this,ETe,"f").catch(()=>{}),Pe(this,Kie,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Pe(this,jrt,"m",Npr).bind(this))},0)}_connected(){this.ended||(Pe(this,PTe,"f").call(this),this._emit("connect"))}get ended(){return Pe(this,Xie,"f")}get errored(){return Pe(this,RTe,"f")}get aborted(){return Pe(this,ITe,"f")}abort(){this.controller.abort()}on(e,r){return(Pe(this,bD,"f")[e]||(Pe(this,bD,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=Pe(this,bD,"f")[e];if(!n)return this;let o=n.findIndex(i=>i.listener===r);return o>=0&&n.splice(o,1),this}once(e,r){return(Pe(this,bD,"f")[e]||(Pe(this,bD,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{Kr(this,oG,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){Kr(this,oG,!0,"f"),await Pe(this,Kie,"f")}_emit(e,...r){if(Pe(this,Xie,"f"))return;e==="end"&&(Kr(this,Xie,!0,"f"),Pe(this,MTe,"f").call(this));let n=Pe(this,bD,"f")[e];if(n&&(Pe(this,bD,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!Pe(this,oG,"f")&&!n?.length
\r `.includes(t[n]);)n++};return a()},Hrt=t=>yuo(t,Wh.ALL^Wh.NUM)});var Wrt=v(()=>{Crt()});function _uo(t,e){let{id:r,choices:n,created:o,model:i,system_fingerprint:a,...s}=t,u={...s,id:r,choices:n.map(({message:l,finish_reason:c,index:d,logprobs:f,...p})=>{if(!c)throw new Gt(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:y,...g}=l,b=l.role;if(!b)throw new Gt(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new Gt(`missing function_call.arguments for choice ${d}`);if(!w)throw new Gt(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:_,name:w},role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return y?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:b,content:m,refusal:l.refusal??null,tool_calls:y.map((_,w)=>{let{function:T,type:O,id:E,...P}=_,{arguments:R,name:I,...N}=T||{};if(E==null)throw new Gt(`missing choices[${d}].tool_calls[${w}].id
${$Te(t)}`);if(O==null)throw new Gt(`missing choices[${d}].tool_calls[${w}].type
${$Te(t)}`);if(I==null)throw new Gt(`missing choices[${d}].tool_calls[${w}].function.name
${$Te(t)}`);if(R==null)throw new Gt(`missing choices[${d}].tool_calls[${w}].function.arguments
${$Te(t)}`);return{...P,id:E,type:O,function:{...N,name:I,arguments:R}}})}}:{...p,message:{...g,content:m,role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Mpr(u,e)}function $Te(t){return JSON.stringify(t)}var Wm,_D,aG,Zk,Jrt,DTe,Krt,Grt,Xrt,jTe,Zrt,Fpr,NV,LTe=v(()=>{v0();Lpr();Ax();rG();Wrt();Urt();NV=class t extends iG{constructor(e){super(),Wm.add(this),_D.set(this,void 0),aG.set(this,void 0),Zk.set(this,void 0),Kr(this,_D,e,"f"),Kr(this,aG,[],"f")}get currentChatCompletionSnapshot(){return Pe(this,Zk,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),Pe(this,Wm,"m",Jrt).call(this);let i=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of i)Pe(this,Wm,"m",Krt).call(this,a);if(i.controller.signal?.aborted)throw new zc;return this._addChatCompletion(Pe(this,Wm,"m",jTe).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Pe(this,Wm,"m",Jrt).call(this),this._connected();let o=aA.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Pe(this,Wm,"m",jTe).call(this)),Pe(this,Wm,"m",Krt).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new zc;return this._addChatCompletion(Pe(this,Wm,"m",jTe).call(this))}[(_D=new WeakMap,aG=new WeakMap,Zk=new WeakMap,Wm=new WeakSet,Jrt=function(){this.ended||Kr(this,Zk,void 0,"f")},DTe=function(r){let n=Pe(this,aG,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Pe(this,aG,"f")[r.index]=n,n)},Krt=function(r){if(this.ended)return;let n=Pe(this,Wm,"m",Fpr).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let i=n.choices[o.index];o.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",o.delta.content,i.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),o.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.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=Pe(this,Wm,"m",DTe).call(this,i);i.finish_reason&&(Pe(this,Wm,"m",Xrt).call(this,i),a.current_tool_call_index!=null&&Pe(this,Wm,"m",Grt).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Pe(this,Wm,"m",Xrt).call(this,i),a.current_tool_call_index!=null&&Pe(this,Wm,"m",Grt).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=s.index;for(let s of o.delta.tool_calls??[]){let u=i.message.tool_calls?.[s.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:s.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:s.function?.arguments??""}):(u?.type,void 0))}}},Grt=function(r,n){if(Pe(this,Wm,"m",DTe).call(this,r).done_tool_calls.has(n))return;let i=r.message.tool_calls?.[n];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let a=Pe(this,_D,"f")?.tools?.find(s=>Vie(s)&&s.func
2026-01-05 13:03:55 +08:00
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 });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
2026-02-24 07:55:02 +08:00
`);this.baseURL=s.baseURL,this.timeout=s.timeout??iot.DEFAULT_TIMEOUT,this.logger=s.logger??console;let u="warn";this.logLevel=u,this.logLevel=wrt(s.logLevel,"ClientOptions.logLevel",this)??wrt(Nx("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??rpr(),Kr(this,KTe,opr,"f"),this._options=s,this.apiKey=typeof r=="string"?r:"Missing Key",this.organization=n,this.project=o,this.webhookSecret=i}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,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}async authHeaders(e){return gt([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return _rt(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Gk}`}defaultIdempotencyKey(){return`stainless-node-retry-${art()}`}makeStatusError(e,r,n,o){return Vm.generate(e,r,n,o)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof Gt?n:new Gt(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new Gt(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!Pe(this,oot,"m",umr).call(this)&&n||this.baseURL,i=Wfr(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Jfr(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new RV(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,i=o.maxRetries??this.maxRetries;r==null&&(r=i),await this.prepareOptions(o);let{req:a,url:s,timeout:u}=await this.buildRequest(o,{retryCount:i-r});await this.prepareRequest(a,{url:s,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(md(this).debug(`[${l}] sending request`,gD({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new zc;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(Die),m=Date.now();if(p instanceof globalThis.Error){let g=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new zc;let b=Nie(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return md(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${g}`),md(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${g})`,gD({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),this.retryRequest(o,r,n??l);throw md(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),md(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,gD({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),b?new tA:new Kk({cause:p})}let h=[...p.headers.entries()].filter(([g])=>g==="x-request-id").map(([g,b])=>", "+g+": "+JSON.stringify(b)).join(""),y=`[${l}${c}${h}] ${a.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let g=await this.shouldRetry(p);if(r&&g){let E=`retrying, ${r} attempts remaining`;return await npr(p.body),md(this).info(`${y} - ${E}`),md(this).debug(`[${l}] response error (${E})`,gD({retryOfRequestLogID:n,url:p.ur
`)}function hmr(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${XTe(o,e)},`):r.push(`${n}?: ${XTe(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function XTe(t,e){if(dlo(t))return t.anyOf.map(r=>XTe(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",hmr(t,e+2),"}"].join(`
`);case"array":return t.items?`${XTe(t.items,e)}[]`:"any[]";default:return""}}function ZTe(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function $G(t){return"type"in t&&t.type!=="function"}function gmr(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function ymr(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function QV(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function YTe(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function bmr(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function _mr(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function vmr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function wmr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function Smr(t){let e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function Cmr(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var LG=v(()=>{pD();uv();Ny()});var sot=v(()=>{Iy()});var nOe={};En(nOe,{ZodISODate:()=>eOe,ZodISODateTime:()=>QTe,ZodISODuration:()=>rOe,ZodISOTime:()=>tOe,date:()=>lot,datetime:()=>uot,duration:()=>dot,time:()=>cot});function uot(t){return JVe(QTe,t)}function lot(t){return KVe(eOe,t)}function cot(t){return GVe(tOe,t)}function dot(t){return XVe(rOe,t)}var QTe,eOe,tOe,rOe,oOe=v(()=>{Iy();iOe();QTe=xe("ZodISODateTime",(t,e)=>{X2e.init(t,e),Qu.init(t,e)});eOe=xe("ZodISODate",(t,e)=>{Z2e.init(t,e),Qu.init(t,e)});tOe=xe("ZodISOTime",(t,e)=>{Y2e.init(t,e),Qu.init(t,e)});rOe=xe("ZodISODuration",(t,e)=>{Q2e.init(t,e),Qu.init(t,e)})});var Tmr,plo,FG,fot=v(()=>{Iy();Iy();Tmr=(t,e)=>{Tee.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Eee(t,r)},flatten:{value:r=>Oee(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},plo=xe("ZodError",Tmr),FG=xe("ZodError",Tmr,{Parent:Error})});var pot,mot,hot,got,yot=v(()=>{Iy();fot();pot=Rhe(FG),mot=Ihe(FG),hot=Ahe(FG),got=Nhe(FG)});function bot(t){return VVe(iae,t)}function hlo(t){return Jhe(wot,t)}function glo(t){return $ee(aOe,t)}function ylo(t){return Khe(PD,t)}function blo(t){return Ghe(PD,t)}function _lo(t){return Xhe(PD,t)}function vlo(t){return Zhe(PD,t)}function wlo(t){return Yhe(Sot,t)}function Slo(t){return Qhe(Cot,t)}function Clo(t){return ege(xot,t)}function xlo(t){return tge(Tot,t)}function Tlo(t){return rge(Oot,t)}function Olo(t){return nge(Eot,t)}function Elo(t){return oge(Pot,t)}function Plo(t){return ige(Mot,t)}function Mlo(t){return age(Rot,t)}function Rlo(t){return sge(Iot,t)}function Ilo(t){return uge(Aot,t)}function Alo(t){return lge(Not,t)}function Nlo(t){return cge(Dot,t)}function Dlo(t){return dge(jot,t)}function jlo(t){return fge($ot,t)}function $lo(t){return pge(Lot,t)}function Llo(t,e,r={}){return PHe(Omr,t,e,r)}function Emr(t){return ZVe(aae,t)}function _ot(t){return QVe(kG,t)}function Flo(
2026-01-21 08:46:13 +08:00
]))`;continue}else if(o[l]==="$"){i+=`($|(?=[\r
]))`;continue}}if(n.s&&o[l]==="."){i+=s?`${o[l]}\r
`:`[${o[l]}\r
2026-02-24 07:55:02 +08:00
]`;continue}i+=o[l],o[l]==="\\"?a=!0:s&&o[l]==="]"?s=!1:!s&&o[l]==="["&&(s=!0)}try{let l=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`),r.source}return i}});function _Oe(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===Ae.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Dn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Dn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Ae.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(yOe(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===Ae.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}var vOe=v(()=>{cO();$d();bOe()});function Dhr(t,e){if(e.mapStrategy==="record")return _Oe(t,e);let r=Dn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=Dn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var fit=v(()=>{$d();vOe()});function jhr(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var pit=v(()=>{});function $hr(){return{not:{}}}var mit=v(()=>{});function Lhr(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var hit=v(()=>{});function khr(t,e){if(e.target==="openApi3")return Fhr(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in cae&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=cae[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];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(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Fhr(t,e)}var cae,Fhr,wOe=v(()=>{$d();cae={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Fhr=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Dn(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function qhr(t,e){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:cae[t.innerType._def.typeName],nullable:!0}:{type:[cae[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Dn(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Dn(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var git=v(()=>{$d();wOe()});function Uhr(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Zot(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?
Details: ${m.message}`),_ge(m)&&(h=`${h}
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
${Yt.prettifyError(m)}`),new H6(h,JSON.stringify(e))}else{let m=Ku(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
2026-01-21 08:46:13 +08:00
Details: ${m.errors.map(y=>`${y.keywordLocation}: ${y.error}`).join(`
2026-02-24 07:55:02 +08:00
`)}`),new H6(h,JSON.stringify(e))}i=o}let a=HN(r),u=await mc.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName);delete a.runId;let l;try{l=await this._call(i,u,a)}catch(m){throw await u?.handleToolError(m),m}let c,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[c,d]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(l)}`);else c=l;let f;qL(e)&&(f=e.id),!f&&DCt(a)&&(f=a.toolCall.id);let p=Jco({content:c,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(p),p}},Bit=class extends Uit{constructor(e){super(e);x(this,"schema",wt.object({input:wt.string().optional()}).transform(e=>e.input))}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},zit=class extends Bit{constructor(e){super(e);x(this,"name");x(this,"description");x(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,r){let n=HN(r);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}async _call(e,r,n){return this.func(e,r,n)}},wgr=class extends Uit{constructor(e){super(e);x(this,"description");x(this,"func");x(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,r,n){let o=HN(r);return o.runName===void 0&&(o.runName=this.name),super.call(e,o,n)}_call(e,r,n){return this.func(e,r,n)}},Wco=class{getTools(){return this.tools}}});var Vit=v(()=>{dA();au();mq()});var Sgr=v(()=>{});var Cgr=v(()=>{});var xgr=v(()=>{});var Tgr=v(()=>{});var Ogr=v(()=>{});var Gco,Xco,Zco,Yco,Qco,edo,tdo,rdo,ndo,odo,Z4a,Egr=v(()=>{ta();mq();eH();Gco=Yt.object({type:Yt.literal("screenshot")}),Xco=Yt.object({type:Yt.literal("click"),x:Yt.number(),y:Yt.number(),button:Yt.enum(["left","right","wheel","back","forward"]).default("left")}),Zco=Yt.object({type:Yt.literal("double_click"),x:Yt.number(),y:Yt.number(),button:Yt.enum(["left","right","wheel","back","forward"]).default("left")}),Yco=Yt.object({type:Yt.literal("drag"),path:Yt.array(Yt.object({x:Yt.number(),y:Yt.number()}))}),Qco=Yt.object({type:Yt.literal("keypress"),keys:Yt.array(Yt.string())}),edo=Yt.object({type:Yt.literal("move"),x:Yt.number(),y:Yt.number()}),tdo=Yt.object({type:Yt.literal("scroll"),x:Yt.number(),y:Yt.number(),scroll_x:Yt.number(),scroll_y:Yt.number()}),rdo=Yt.object({type:Yt.literal("type"),text:Yt.string()}),ndo=Yt.object({type:Yt.literal("wait"),duration:Yt.number().optional()}),odo=Yt.discriminatedUnion("type",[Gco,Xco,Zco,Yco,Qco,edo,tdo,rdo,ndo]),Z4a=Yt.object({action:odo})});var ido,t2a,Pgr=v(()=>{mq();eH();ido=Yt.object({type:Yt.literal("exec"),command:Yt.array(Yt.string()),env:Yt.record(Yt.string(),Yt.string()).optional(),working_directory:Yt.string().optional(),timeout_ms:Yt.number().optional(),user:Yt.string().optional()}),t2a=Yt.discriminatedUnion("type",[ido])});var i2a,Mgr=v(()=>{mq();eH();i2a=Yt.object({commands:Yt.array(Yt.string()).describe("Array of shell commands to execute"),timeout_ms:Yt.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:Yt.number().optional().describe("Optional maximum number of characters to return from each command")})});var ado,sdo,udo,l2a,Rgr=v(()=>{mq();eH();ado=Yt.object({type:Yt.literal("create_file"),path:Yt.string(),diff:Yt.string()}),sdo=Yt.object({type:Yt.literal("update_file"),path:Yt.string(),diff:Yt.string()}),udo=Yt.object({type:Yt.literal("delete_file"),path:Yt.string()}),l2a=Yt.discriminatedUnion("type",[ado,sdo,udo])});var Igr=v(()=>{Vit();Sgr();Cgr();xgr();Tgr();Ogr();Egr();Pgr();Mgr();Rgr()});var Agr=v(()=>{sw();mq();Vz()});var Ngr=v(()=>{qG()});var Dgr=v(()=>{qG();EOe()});var iH=v(()=>{uq();lq();cq();dae();qG();COe();Nit();EOe();MOe();$it();Lit();bgr();Fit();_gr();kit();vgr();Vit();Igr();Agr();Ngr();Dgr();dA()});var $gr=S((EVa,jgr)=>{jgr.exports={createRequire:function(t){return typeof require<"u"?require:function(r){throw new Error('Dynamic require of "'+r+'" is not supported in this environment')}}}});var ldo,cdo,Lgr,Fgr=v(()=>{ldo=$($gr(),1),cdo=Object.defineProperty,Lgr=(t,e)=>{for(var r in e)cdo(t,r,{get:e[r],enumerable:!0})}});var ddo,Hit,kgr=v(()=>{Fgr();au();vV();zk();ddo={};Lgr(ddo,{JinaEmbeddings:()=>Hit});Hit=class extends y0{co
without CORS Error: `+zr(n)+`
with CORS Error: `+zr(o);throw new Error(i)}}}}});var Bgr,AOe,zgr=v(()=>{Xe();Ye();Bt();Bgr=require("obsidian"),AOe=class t{constructor(){this.cachedBaseUrl=null}static getInstance(){return t.instance||(t.instance=new t),t.instance}async resolveBaseUrl(e={}){let r=(e.overrideUrl||"").trim();if(r.length>0)return this.normalizeBaseUrl(r);if(this.cachedBaseUrl&&!e.forceRefresh)return this.cachedBaseUrl;if(!Bgr.Platform.isDesktopApp)return null;let n=await this.readServiceConfig();if(!n)return this.cachedBaseUrl=null,null;let o=this.normalizeBaseUrl(`http://${n.host}:${n.port}`);return this.cachedBaseUrl=o,o}normalizeBaseUrl(e){return e.trim().replace(/\/+$/,"")}getServiceFilePath(){let e=this.getNodeRequire();if(!e)return null;let r=e("os");return e("path").join(r.homedir(),"Library","Application Support","Miyo","service.json")}async readServiceConfig(){let e=this.getServiceFilePath();if(!e)return null;try{let r=this.getNodeRequire();if(!r)return null;let o=await r("fs").promises.readFile(e,"utf8"),i=JSON.parse(o);return!i.host||typeof i.host!="string"?(Te("Miyo service discovery missing host"),null):typeof i.port!="number"||Number.isNaN(i.port)?(Te("Miyo service discovery missing port"),null):(te().debug&&F(`Miyo service discovery resolved host=${i.host} port=${i.port}`),i)}catch(r){return te().debug&&Te(`Miyo service discovery failed: ${zr(r)}`),null}}getNodeRequire(){let e=globalThis?.require;return typeof e=="function"?e:null}}});var Vgr,S0,BG=v(()=>{Xe();Ye();Bt();Vgr=require("obsidian");zgr();S0=class{constructor(){this.discovery=AOe.getInstance()}async resolveBaseUrl(e){let r=await this.discovery.resolveBaseUrl({overrideUrl:e});if(!r)throw new Error("Miyo base URL not available");return r}async isBackendAvailable(e){try{let r=await this.resolveBaseUrl(e);return(await this.requestJson(r,"/v0/health",{method:"GET"}))?.status==="ok"}catch(r){return te().debug&&Te(`Miyo backend availability check failed: ${zr(r)}`),!1}}async upsertDocuments(e,r,n){let o={vault:r,documents:n};return(await this.requestJson(e,"/v0/index/upsert",{method:"POST",body:o}))?.upserted??0}async deleteByPath(e,r,n){let o={vault:r,path:n};return(await this.requestJson(e,"/v0/index/by_path",{method:"DELETE",body:o}))?.deleted??0}async clearIndex(e,r){let n={vault:r};await this.requestJson(e,"/v0/index/clear",{method:"POST",body:n})}async listFiles(e,r,n,o){return this.requestJson(e,"/v0/index/files",{method:"GET",query:{vault:r,offset:n,limit:o}})}async getStats(e,r){return this.requestJson(e,"/v0/index/stats",{method:"GET",query:{vault:r}})}async getDocumentsByPath(e,r,n){return this.requestJson(e,"/v0/index/documents",{method:"GET",query:{vault:r,path:n}})}async search(e,r,n,o,i){let a={query:n,vault:r,limit:o,...i&&i.length>0?{filters:i}:{}};return te().debug&&F("Miyo search request:",{baseUrl:e,payload:a}),this.requestJson(e,"/v0/search",{method:"POST",body:a})}async searchRelated(e,r,n){let o={file_path:r,...n?.sourceId?{vault:n.sourceId}:{},...typeof n?.limit=="number"?{limit:n.limit}:{},...n?.filters&&n.filters.length>0?{filters:n.filters}:{}};return te().debug&&F("Miyo related search request:",{baseUrl:e,payload:o}),this.requestJson(e,"/v0/search/related",{method:"POST",body:o})}async parseDoc(e,r){return this.requestJson(e,"/v0/parse-doc",{method:"POST",body:{path:r}})}buildHeaders(){let e=te().selfHostApiKey,r={};return e&&(r.Authorization=`Bearer ${e}`,r["X-API-Key"]=e),r}async requestJson(e,r,n){let o=new URL(r,e);n.query&&Object.entries(n.query).forEach(([u,l])=>{l!=null&&o.searchParams.set(u,String(l))});let i=n.body?JSON.stringify(n.body):void 0;F("Miyo request:",{method:n.method,url:o.toString(),hasBody:!!i,...te().debug&&n.method==="POST"?{postBody:n.body}:{}});let a=await(0,Vgr.requestUrl)({url:o.toString(),method:n.method,headers:this.buildHeaders(),contentType:i?"application/json":void 0,body:i,throw:!1});if(a.status>=400){let u=a.text?a.text:"";throw Te(`Miyo request failed (${a.status}): ${u}`),new Error(`Miyo request failed with status ${a.status}`)}let s=this.parseResponseJson(a.json,a.text);return te().debug&&F(`Miyo request
- `),Edo={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
2026-01-05 13:03:55 +08:00
Supported languages are:
2026-02-24 07:55:02 +08:00
- ${Odo}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
2026-01-05 13:03:55 +08:00
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
2026-02-24 07:55:02 +08:00
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});function syr(t){return{raw:Number(t),formatted:lH(t)}}function uyr(t){if(t.id){if(typeof t.id!="string")throw Ur("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return gae()}function Qit(t,e){for(let[r,n]of Object.entries(e)){let o=t[r];if(!(typeof o>"u")&&!(n==="geopoint"&&typeof o=="object"&&typeof o.lon=="number"&&typeof o.lat=="number")&&!(n==="enum"&&(typeof o=="string"||typeof o=="number"))){if(n==="enum[]"&&Array.isArray(o)){let i=o.length;for(let a=0;a<i;a++)if(typeof o[a]!="string"&&typeof o[a]!="number")return r+"."+a;continue}if(ID(n)){let i=tat(n);if(!Array.isArray(o)||o.length!==i)throw Ur("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(KG(n)){if(!Array.isArray(o))return r;let i=eat(n),a=o.length;for(let s=0;s<a;s++)if(typeof o[s]!==i)return r+"."+s;continue}if(typeof n=="object"){if(!o||typeof o!="object")return r;let i=Qit(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function lyr(t){return t==="geopoint"}function ID(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function KG(t){return typeof t=="string"&&Pdo[t]}function eat(t){return Mdo[t]}function tat(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw Ur("INVALID_VECTOR_VALUE",t);case e<=0:throw Ur("INVALID_VECTOR_SIZE",t);default:return e}}var Pdo,Mdo,yae=v(()=>{Jh();gd();gd();Pdo={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Mdo={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function cyr(){return{idToInternalId:new Map,internalIdToId:[],save:Rdo,load:Ido}}function Rdo(t){return{internalIdToId:t.internalIdToId}}function Ido(t,e){let{internalIdToId:r}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let n=r.length;for(let o=0;o<n;o++){let i=r[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}function cu(t,e){if(typeof e=="string"){let r=t.idToInternalId.get(e);if(r)return r;let n=t.idToInternalId.size+1;return t.idToInternalId.set(e,n),t.internalIdToId.push(e),n}return e>t.internalIdToId.length?cu(t,e.toString()):e}function C0(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var x0=v(()=>{});function Ndo(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function Ddo(t,e){let r=cu(t.sharedInternalDocumentStore,e);return t.docs[r]}function jdo(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=cu(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function $do(t){return t.docs}function Ldo(t,e,r){let n=cu(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function Fdo(t,e){let r=cu(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function kdo(t){return t.count}function qdo(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function Udo(t){return{docs:t.docs,count:t.count}}function dyr(){return{create:Ndo,get:Ddo,getMultiple:jdo,getAll:$do,store:Ldo,remove:Fdo,count:kdo,load:qdo,save:Udo}}var rat=v(()=>{x0()});function pyr(t,e){let r=[],n=t.plugins?.length;if(!n)return r;for(let o=0;o<n;o++)try{let i=t.plugins[o];typeof i[e]=="function"&&r.push(i[e])}catch(i){throw console.error("Caught error in getAllPluginsByHook:",i),Ur("PLUGIN_CRASHED")}return r}var fyr,myr=v(()=>{Jh();fyr=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function qx(t,e,r,n){if(t.some(Ld))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function cH(t,e,r){if(t.some(Ld))return(async()=>{for(let o of t)await o(e,r)})();for(let o o
which is longer than the specified ${this.chunkSize}`),o.length>0)){let l=this.joinDocs(o,r);for(l!==null&&n.push(l);i>this.chunkOverlap||i+u+o.length*r.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(s),i+=u}let a=this.joinDocs(o,r);return a!==null&&n.push(a),n}},Hat=class Vat extends k_r{constructor(r){super(r);x(this,"separators",[`
2026-01-05 13:03:55 +08:00
`,`
2026-02-24 07:55:02 +08:00
`," ",""]);this.separators=r?.separators??this.separators,this.keepSeparator=r?.keepSeparator??!0}static lc_name(){return"RecursiveCharacterTextSplitter"}async _splitText(r,n){let o=[],i=n[n.length-1],a;for(let c=0;c<n.length;c+=1){let d=n[c];if(d===""){i=d;break}if(r.includes(d)){i=d,a=n.slice(c+1);break}}let s=this.splitOnSeparator(r,i),u=[],l=this.keepSeparator?"":i;for(let c of s)if(await this.lengthFunction(c)<this.chunkSize)u.push(c);else{if(u.length){let d=await this.mergeSplits(u,l);o.push(...d),u=[]}if(!a)o.push(c);else{let d=await this._splitText(c,a);o.push(...d)}}if(u.length){let c=await this.mergeSplits(u,l);o.push(...c)}return o}async splitText(r){return this._splitText(r,this.separators)}static fromLanguage(r,n){return new Vat({...n,separators:Vat.getSeparatorsForLanguage(r)})}static getSeparatorsForLanguage(r){if(r==="cpp")return[`
2026-01-05 13:03:55 +08:00
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`
`,`
`," ",""];if(r==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`
`,`
`," ",""];if(r==="python")return[`
class `,`
def `,`
def `,`
`,`
`," ",""];if(r==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`
`,`
`," ",""];if(r==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`
`,`
`," ",""];if(r==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`
`,`
`," ",""];if(r==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`
`,`
`," ",""];if(r==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`
***
`,`
---
`,`
___
`,`
`,`
`," ",""];if(r==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`
`,`
`," ",""];if(r==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(r==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`
`,`
2026-02-24 07:55:02 +08:00
`," ",""];throw new Error(`Language ${r} is not supported.`)}}});var U_r=v(()=>{q_r()});function Sq(t){return Wat||(Wat=new Jat(t)),Wat}var zEe,BEe,Jat,Wat,Oae=v(()=>{Xe();mr();zEe=require("obsidian");U_r();BEe={maxChars:wye,overlap:0,maxBytesTotal:10*1024*1024},Jat=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0}getCacheKey(e,r){return`${e}:${r.maxChars}:${r.overlap}`}createSplitter(e){return Hat.fromLanguage("markdown",{chunkSize:e.maxChars,chunkOverlap:e.overlap,separators:[`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`,`
`,". "," ",""],keepSeparator:!1})}async getChunks(e,r={}){try{if(!Array.isArray(e))return Te("ChunkManager: Invalid notePaths provided"),[];if(e.length===0)return[];e.length>1e3&&(Te("ChunkManager: Too many note paths, limiting to 1000"),e=e.slice(0,1e3));let n=e.filter(u=>!(!u||typeof u!="string"||u.startsWith("/")||u.startsWith("../")||u.includes("/../")||u.endsWith("/..")));if(n.length===0)return Te("ChunkManager: No valid note paths provided"),[];let o={...BEe,...r},i=[],a=0,s=0;for(let u of n){let l=this.getCacheKey(u,o),c=this.cache.get(l);if(c&&c.length>0){let d=this.app.vault.getAbstractFileByPath(u);if(d&&d instanceof zEe.TFile&&d.stat.mtime>c[0].mtime){let f=this.calculateChunkBytes(c);this.cache.delete(l),this.memoryUsage-=f,c=void 0}}if(!c&&(c=await this.generateChunksForNote(u,o),c.length>0)){let d=this.calculateChunkBytes(c);this.memoryUsage+d<=o.maxBytesTotal?(this.cache.set(l,c),this.memoryUsage+=d):(a+=1,s+=d)}i.push(...c)}if(a>0){let u=(s/1024/1024).toFixed(1);F(`ChunkManager: Cache budget reached, skipped caching ${a} notes (${u}MB total)`)}return F(`ChunkManager: Retrieved ${i.length} chunks from ${n.length} notes (${this.formatMemoryUsage()})`),i}catch(n){return Te("ChunkManager: Failed to get chunks",n),[]}}async getChunkText(e){return(await this.ensureChunkExists(e))?.content||""}async ensureChunkExists(e){let[r]=e.split("#"),o=(await this.getValidatedChunks(r)).find(i=>i.id===e);return o||Te(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}async getValidatedChunks(e){let r;for(let[o,i]of this.cache.entries())if(o.startsWith(e+":")){r=i;break}if(!r&&(F(`ChunkManager: Cache miss for ${e}, regenerating...`),r=await this.regenerateChunks(e),!r||r.length===0))return Te(`ChunkManager: Failed to regenerate chunks for ${e}`),[];let n=this.app.vault.getAbstractFileByPath(e);return n&&n instanceof zEe.TFile&&r.length>0&&n.stat.mtime>r[0].mtime&&(F(`ChunkManager: File ${e} modified, regenerating chunks`),r=await this.regenerateChunks(e),!r||r.length===0)?(Te(`ChunkManager: Failed to regenerate chunks after modification for ${e}`),[]):r}getChunkTextSync(e){let[r]=e.split("#");for(let[n,o]of this.cache.entries())if(n.startsWith(r+":")){let i=o.find(a=>a.id===e);if(i)return i.content}return Te(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),""}async regenerateChunks(e){try{let r=await this.generateChunksForNote(e,BEe),n=this.getCacheKey(e,BEe);if(r.length>0){let o=this.calculateChunkBytes(r);if(this.memoryUsage+o<=BEe.maxBytesTotal){let i=this.cache.get(n);i&&(this.memoryUsage-=this.calculateChunkBytes(i)),this.cache.set(n,r),this.memoryUsage+=o}else F(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}return r}catch(r){return Te(`ChunkManager: Failed to regenerate chunks for ${e}`,r),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,F("ChunkManager: Cache cleared")}async generateChunksForNote(e,r){try{let n=this.app.vault.getAbstractFileByPath(e);if(!n||!(n instanceof zEe.TFile))return[];let o=await this.safeReadFile(n);if(!o?.trim())return[];let i=this.app.metadataCache.getFileCache(n),a=(i?.headings||[]).slice().sort((p,m)=>p.position.start.offset-m.position.start.offset),s=[],u=0,l=this.findFrontmatterEnd(o,i?.frontmatter),c=o.substring(l),d=a.length>0?a[0].heading:"";if(`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
NOTE TITLE: [[${n.basename}]]
2026-01-05 13:03:55 +08:00
NOTE BLOCK CONTENT:
2026-02-24 07:55:02 +08:00
`.length+c.length<=r.maxChars){let p=await this.processContentSection(c,d,n,u,r);return s.push(...p),s}if(a.length===0){let p=await this.processContentSection(c,"",n,u,r);return s.push(...p),s}for(let p=0;p<a.length;p++){let m=a[p],h=a[p+1],y=p===0?l:m.position.start.offset,g=h?.position.start.offset||o.length,b=o.substring(y,g),_=await this.processContentSection(b,m.heading,n,u,r);s.push(..._),u+=_.length}return s}catch(n){return Te(`ChunkManager: Failed to chunk note ${e}`,n),[]}}async processContentSection(e,r,n,o,i){let a=n.basename,s=[],u=`
2026-01-05 13:03:55 +08:00
NOTE TITLE: [[${a}]]
NOTE BLOCK CONTENT:
2026-02-24 07:55:02 +08:00
`,l=u+e;if(l.length<=i.maxChars){let c=this.generateChunkId(n.path,o),d=this.calculateContentHash(l);s.push({id:c,notePath:n.path,chunkIndex:o,content:l,contentHash:d,title:a,heading:r,mtime:n.stat.mtime})}else try{let d=await this.createSplitter(i).createDocuments([e],[],{chunkHeader:u,appendChunkOverlapHeader:i.overlap>0});this.coalesceTinySplitChunks(d.map(p=>p.pageContent),u,i.maxChars).forEach((p,m)=>{let h=o+m,y=this.generateChunkId(n.path,h),g=this.calculateContentHash(p);s.push({id:y,notePath:n.path,chunkIndex:h,content:p,contentHash:g,title:a,heading:r,mtime:n.stat.mtime})})}catch(c){Te(`ChunkManager: Failed to split section in ${n.path}`,c);let d=this.generateChunkId(n.path,o),f=this.calculateContentHash(l);s.push({id:d,notePath:n.path,chunkIndex:o,content:l,contentHash:f,title:a,heading:r,mtime:n.stat.mtime})}return s}coalesceTinySplitChunks(e,r,n){if(e.length<=1)return e;let o=[...e],i=0;for(;i<o.length-1;){if(this.isTinyStructuralChunk(o[i],r)){let a=this.mergeChunkContents(o[i],o[i+1],r);if(a.length<=n){o.splice(i,2,a);continue}}i++}if(o.length>1){let a=o.length-1;if(this.isTinyStructuralChunk(o[a],r)){let s=this.mergeChunkContents(o[a-1],o[a],r);s.length<=n&&o.splice(a-1,2,s)}}return o}isTinyStructuralChunk(e,r){let n=this.stripChunkHeader(e,r).trim();if(!n)return!0;let o=n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);return o.length===1&&/^#{1,6}\s+\S+/.test(o[0])}mergeChunkContents(e,r,n){let o=this.stripChunkHeader(e,n).replace(/\s+$/,""),i=this.stripChunkHeader(r,n).replace(/^\s+/,"");return`${n}${o}${o&&i?`
`:""}${i}`}stripChunkHeader(e,r){return e.startsWith(r)?e.slice(r.length):e}calculateChunkBytes(e){return e.reduce((r,n)=>r+Buffer.byteLength(n.content,"utf8"),0)}async safeReadFile(e){try{return(await this.app.vault.cachedRead(e))?.trim()||""}catch(r){return Te(`ChunkManager: Failed to read ${e.path}`,r),""}}generateChunkId(e,r){return`${e}#${r}`}calculateContentHash(e){let r=e.length.toString(16),n=e.slice(0,32).replace(/\s/g,"").substring(0,8);return r+n}formatMemoryUsage(){return`${(this.memoryUsage/1024/1024).toFixed(1)}MB`}findFrontmatterEnd(e,r){if(!r||!e.startsWith("---"))return 0;let n=e.match(/\n---(\r?\n|$)/);return n&&n.index!==void 0?n.index+n[0].length:0}},Wat=null});var B_r,VEe,Eae,z_r=v(()=>{ra();sH();Xe();$_r();Oae();Ye();Bt();B_r=$(gH()),VEe=require("obsidian");ob();Eae=class{constructor(e,r,n){this.app=e;this.indexBackend=r;this.embeddingsManager=n;this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:0,processedFiles:new Set};this.refreshRuntimeIndexingConfig(),this.chunkManager=Sq(e),hl(async()=>{this.refreshRuntimeIndexingConfig()})}refreshRuntimeIndexingConfig(){let e=te();this.rateLimiter=new UEe(e.embeddingRequestsPerMin),this.embeddingBatchSize=Math.max(1,e.embeddingBatchSize),this.checkpointInterval=8*this.embeddingBatchSize}async indexVaultToVectorStore(e,r){if(!te().enableSemanticSearchV3)return Te("indexVaultToVectorStore called with semantic search disabled, skipping."),0;let n=[];JWe();try{let o=this.indexBackend.requiresEmbeddings(),i=o?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(o&&!i)return ne("Embedding instance not found."),WWe({isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:["Embedding model not available. Please check your Copilot settings to make sure you have a working embedding model."],completionStatus:"error"}),0;(o?await this.indexBackend.checkAndHandleEmbeddingModelChange(i):!1)&&(e=!0),e?(await this.indexBackend.clearIndex(i),this.indexBackend.clearFilesMissingEmbeddings()):await this.indexBackend.garbageCollect();let s=await this.getFilesToIndex(e);if(s.length===0)return r?.userInitiated&&Ig({completionStatus:"success"}),0;this.initializeIndexingState(s.length),this.indexBackend.clearFilesMissingEmbeddings();let u=o&&i?hd.getModelName(i):"",l=await this.prepareAllChunks(s,u);if(l.length===0)return JWe(),0;if(this.state.isIndexingCancelled||u5().isCancelled)return Ig({isActive:!1,completionStatus:"cancelled"}),0;let c=new Set(l.map(f=>f.fileInfo.path)).size;this.state.totalFilesToIndex=c,Ig({totalFiles:c});let d=0;for(;d<l.length&&!(this.state.isIndexingCancelled||u5().isCancelled);){await this.handlePause();let f=l.slice(d,d+this.embeddingBatchSize);try{let p=[];if(o&&i){await this.rateLimiter.wait();let y=await i.embedDocuments(f.map(g=>g.content));if(!y||y.length!==f.length)throw new Error(`Embedding model returned ${y?.length??0} embeddings for ${f.length} documents`);for(let g=0;g<f.length;g++){let b=f[g],_=y[g];if(!_||!Array.isArray(_)||_.length===0){ne(`Invalid embedding for document ${b.fileInfo.path}: ${_}`),this.indexBackend.markFileMissingEmbeddings(b.fileInfo.path);continue}p.push({doc:{...b.fileInfo,id:this.getDocHash(b.content),content:b.content,embedding:_,created_at:Date.now(),nchars:b.content.length},filePath:b.fileInfo.path})}}else for(let y of f)p.push({doc:{...y.fileInfo,id:this.getDocHash(y.content),content:y.content,embedding:[],created_at:Date.now(),nchars:y.content.length},filePath:y.fileInfo.path});if(p.length>0)try{await this.indexBackend.upsertBatch(p.map(y=>y.doc)),p.forEach(y=>this.state.processedFiles.add(y.filePath))}catch(y){ne("Batch upsert failed; falling back to per-document upserts.",y);for(let g of p)try{await this.indexBackend.upsert(g.doc),this.state.processedFiles.add(g.filePath)}catch(b){this.handleError(b,{filePath:g.filePath,errors:n}),o&&this.indexBackend.markFileMissingEmbeddings(g.filePath)}}this.state.indexedCount=this.state.processedFiles.size,vDt(this.state.indexedCount);let m=Math.floor((this.state.indexedCount-f.length)/this.checkpointInterval);Math.
`,m=l.content.indexOf("NOTE BLOCK CONTENT:"),h=m>0?l.content.slice(0,m)+p+l.content.slice(m):l.content;n.push({content:h,chunkId:l.id,fileInfo:f})}}}return n}getDocHash(e){return(0,B_r.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=el(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>Hs(c,r,n));let i=new Set(await this.indexBackend.getIndexedFiles()),a=await this.indexBackend.getLatestFileMtime(),s=new Set(this.indexBackend.getFilesMissingEmbeddings()),u=new Set,l=new Set;for(let c of o){if(!Hs(c,r,n))continue;let d=await this.app.vault.cachedRead(c);if(!d||d.trim().length===0){l.add(c.path);continue}let f=i.has(c.path),p=s.has(c.path);(!f||p||c.stat.mtime>a)&&u.add(c)}return F([`Files to index: ${u.size}`,`Previously indexed: ${i.size}`,`Empty files skipped: ${l.size}`,`Files missing embeddings: ${s.size}`].join(`
`)),Array.from(u)}initializeIndexingState(e){this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:e,processedFiles:new Set},WWe({isActive:!0,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:e,errors:[],completionStatus:"none"})}async handlePause(){let e=u5();if(this.state.isIndexingPaused=e.isPaused,this.state.isIndexingCancelled=e.isCancelled,this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.state.isIndexingCancelled;){await new Promise(n=>setTimeout(n,100));let r=u5();this.state.isIndexingPaused=r.isPaused,this.state.isIndexingCancelled=r.isCancelled}if(!this.state.isIndexingCancelled){this.refreshRuntimeIndexingConfig();let r=await this.getFilesToIndex();if(r.length===0){F("No files to index after filter change, stopping indexing"),this.cancelIndexing();return}let n=Math.max(this.state.indexedCount+r.length,1);this.state.totalFilesToIndex=n,Ig({totalFiles:n})}}}isStringLengthError(e){if(!e)return!1;if(e instanceof RangeError&&e.message.toLowerCase().includes("string length"))return!0;let n=(e.message||e.toString()).toLowerCase();return n.includes("string length")||n.includes("rangeerror")}handleError(e,r){let n=r?.filePath;if(n?(r.batch?console.error("Batch processing error:",{error:e,batchSize:r.batch.length||0,firstChunk:r.batch[0]?{path:r.batch[0].fileInfo?.path,contentLength:r.batch[0].content?.length,hasFileInfo:!!r.batch[0].fileInfo}:"No chunks in batch",errorType:e?.constructor?.name,errorMessage:e?.message}):console.error(`Error indexing file ${n}:`,e),r.errors?.push(n)):console.error("Fatal error during indexing:",e),this.isStringLengthError(e)){new VEe.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}}isRateLimitError(e){return e?.message?.includes?.("rate limit")||!1}finalizeIndexing(e){if(wDt(),this.state.isIndexingCancelled||u5().isCancelled){Ig({isActive:!1,completionStatus:"cancelled",errors:e});return}Ig({isActive:!1,completionStatus:e.length>0?"error":"success",errors:e,indexedCount:this.state.indexedCount})}async reindexFile(e){try{let r=this.indexBackend.requiresEmbeddings(),n=r?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(r&&!n)return;if(await this.indexBackend.removeByPath(e.path),r&&n&&await this.indexBackend.checkAndHandleEmbeddingModelChange(n)){await this.indexVaultToVectorStore(!0);return}let o=r&&n?hd.getModelName(n):"",i=await this.prepareAllChunks([e],o);if(i.length===0)return;if(r&&n){let a=await n.embedDocuments(i.map(s=>s.content));for(let s=0;s<i.length;s++){let u=i[s];await this.indexBackend.upsert({...u.fileInfo,id:this.getDocHash(u.content),content:u.content,embedding:a[s],created_at:Date.now(),nchars:u.content.length})}}else for(let a of i)await this.indexBackend.upsert({...a.fileInfo,id:this.getDocHash(a.content),content:a.content,embedding:[],created_at:Date.now(),nchars:a.content.length});this.indexBackend.markUnsavedChanges(),te().debug&&console.log(`Reindexed file: ${e.path}`)}catch(r){this.handleError(r,{filePath:e.path})}}async cancelIndexing(){F("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,Ig({isCancelled:!0,isActive:!1,completionStatus:"cancelled"}),await new Promise(e=>setTimeout(e,100))}}});var Vc={};En(Vc,{default:()=>O0});var Pae,O0,Pl=v(()=>{ra();lw();Xe();sH();Fc();Ye();Pae=require("obsidian");Zgr();D_r();j_r();Bat();z_r();O0=class t{constructor(){this.embeddingsManager=hd.getInstance(),this.oramaBackend=new kEe(app),this.miyoBackend=new DOe(app),this.activeBackendKey=this.getBackendKey(te()),this.indexBackend=this.activeBackendKey==="miyo"?this.miyoBackend:this.oramaBackend,this.indexOps=new Eae(app,this.indexBackend,this.embeddingsManager),this.eventHandler=new xae(app,this.indexOps,this.indexBackend),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}static getInstance(){return t.instance||(t.instance=new t),t.instance}setupSettingsSubscription(){this.lastKnownSettings={...te()};let e=async()=>{let r=te(),n=this.lastKnownSettings;if(this.lastKnownSettings={...r},r.enableI
2026-01-21 08:46:13 +08:00
1. SALIENT TERMS from the original query (for ranking)
2. Alternative queries and related terms (for finding more results)
Query: "{query}"
2026-01-05 13:03:55 +08:00
Instructions:
2026-01-21 08:46:13 +08:00
SALIENT TERMS (for ranking - ONLY from original query):
- Extract meaningful words FROM THE ORIGINAL QUERY ONLY
- Include: nouns, proper nouns, technical terms, domain concepts
- Exclude: action verbs (find, search, get), pronouns (my, your), articles (the, a), prepositions (in, on, for), conjunctions (and, or)
- These terms determine search ranking - must be from original query
2026-02-24 07:55:02 +08:00
ALTERNATIVE QUERIES (for recall - specific alternative phrasings):
- Alternative phrasings of the query (specific enough to be useful for search)
2026-01-05 13:03:55 +08:00
Example: "find my piano notes"
2026-01-21 08:46:13 +08:00
- Salient (from original): piano, notes
2026-02-24 07:55:02 +08:00
- Queries: "piano lesson notes", "piano practice sheets"
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
Example: "\u67E5\u627E\u6211\u7684\u5B66\u4E60\u7B14\u8BB0"
- Salient (from original): \u5B66\u4E60, \u7B14\u8BB0
2026-02-24 07:55:02 +08:00
- Queries: "\u4E2A\u4EBA\u7B14\u8BB0\u6587\u6863"
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
Format:
<salient>
<term>word_from_original_query</term>
</salient>
2026-01-05 13:03:55 +08:00
<queries>
2026-01-21 08:46:13 +08:00
<query>alternative query</query>
2026-02-24 07:55:02 +08:00
</queries>`;g9=dPe});var y9,fPe,Pvr=v(()=>{Xe();ob();y9=class y9{constructor(e){this.app=e}async batchCachedReadGrep(e,r){let{inclusions:n,exclusions:o}=el(),a=this.app.vault.getMarkdownFiles().filter(h=>Hs(h,n,o)),s=y9.CONFIG.BATCH_SIZE,u=e.map(h=>h.toLowerCase()).filter(h=>this.isGrepWorthy(h)),l=[],c=y9.CONFIG.YIELD_INTERVAL;for(let h=0;h<a.length;h++){let y=a[h],g=y.path.toLowerCase(),b=0;for(let _ of u)g.includes(_)&&b++;b>0&&l.push({path:y.path,matchCount:b}),h>0&&h%c===0&&await new Promise(_=>setTimeout(_,0))}l.sort((h,y)=>y.matchCount-h.matchCount);let d=new Set(l.map(h=>h.path)),f=Math.max(0,r-d.size),p=new Set;if(f>0)for(let h=0;h<a.length&&p.size<f;h+=s){let y=a.slice(h,h+s);await Promise.all(y.map(async g=>{if(!(p.size>=f)&&!d.has(g.path))try{let _=(await this.app.vault.cachedRead(g)).toLowerCase();for(let w of u)if(_.includes(w)){p.add(g.path);break}}catch(b){F(`GrepScanner: Skipping file ${g.path}: ${b}`)}})),h%y9.CONFIG.YIELD_INTERVAL===0&&await new Promise(g=>setTimeout(g,0))}let m=[...d,...p].slice(0,r);if(m.length>0){let h=Math.min(d.size,r),y=m.length-h;F(` Grep: ${m.length} files match (${h} path, ${y} content) [${e.slice(0,3).join(", ")}${e.length>3?"...":""}]`)}return m}async grep(e,r=200){return this.batchCachedReadGrep([e],r)}isGrepWorthy(e){return!(!e||e.length<=1)}async fileContainsAny(e,r){try{let n=e.path.toLowerCase(),o=0;for(let s of r)n.includes(s.toLowerCase())&&o++;if(o>0)return!0;let a=(await this.app.vault.cachedRead(e)).toLowerCase();return r.some(s=>a.includes(s.toLowerCase()))}catch{return!1}}};y9.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};fPe=y9});function Bx(t){let e=t.lastIndexOf("#");return e===-1?t:t.substring(0,e)}var pPe=v(()=>{});var amo,mPe,Mvr=v(()=>{Xe();pPe();amo={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},mPe=class{constructor(e){this.config=amo;this.app=e||null}setConfig(e){this.config={...this.config,...e}}applyBoosts(e){if(!this.config.enabled||e.length===0)return e;let r=this.calculateFolderStats(e);return this.logBoostedFolders(r),e.map(n=>{let o=Bx(n.id),i=this.extractFolder(o),a=r.get(i);if(a){let s=n.score*a.boostFactor;return{...n,score:s,explanation:n.explanation?{...n.explanation,folderBoost:{folder:a.folderPath,documentCount:a.documentCount,totalDocsInFolder:a.totalDocsInFolder,relevanceRatio:a.relevanceRatio,boostFactor:a.boostFactor},finalScore:s}:void 0}}return n})}calculateFolderStats(e){let r=new Map;for(let a of e){let s=Bx(a.id),u=this.extractFolder(s);r.has(u)||r.set(u,new Set),r.get(u).add(s)}let n=new Map;for(let[a,s]of r.entries())n.set(a,s.size);let o=this.getTotalDocsPerFolder(),i=new Map;for(let[a,s]of n.entries()){let u=o.get(a)||s,l=s/u;if(s>=this.config.minDocsForBoost&&l>=this.config.minRelevanceRatio){let d=1+(1+Math.log2(s+1)-1)*Math.sqrt(l),f=Math.min(d,this.config.maxBoostFactor);i.set(a,{folderPath:a,documentCount:s,totalDocsInFolder:u,relevanceRatio:l,boostFactor:f})}}return i}getTotalDocsPerFolder(){let e=new Map;if(!this.app)return e;let r=this.app.vault.getMarkdownFiles();for(let n of r){let o=this.extractFolder(n.path);e.set(o,(e.get(o)||0)+1)}return e}extractFolder(e){return e.substring(0,e.lastIndexOf("/"))||""}logBoostedFolders(e){let r=Array.from(e.values()).sort((n,o)=>o.relevanceRatio-n.relevanceRatio);r.length>0&&(F(`Folder boost: Boosting ${r.length} folders with significant relevance`),r.slice(0,5).forEach(n=>{let o=(n.relevanceRatio*100).toFixed(1);F(` ${n.folderPath||"(root)"}: ${n.documentCount}/${n.totalDocsInFolder} docs (${o}% relevant, ${n.boostFactor.toFixed(2)}x boost)`)}))}getFolderBoosts(e){return this.config.enabled?this.calculateFolderStats(e):new Map}}});var smo,hPe,Rvr=v(()=>{Xe();pPe();smo={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},hPe=class{constructor(e,r={}){this.metadataCache=e.metadataCache,this.config={...smo,...r}}applyBoost(e){if(!this.config.enabled||e.length===0)return e;let r=this.filterCandidates(e);if(r.length<2)return e;let n=new Set(r.map(s=>Bx(s.id))),o=new Map;for(let s of n){let
Explicit Chunks: `,a),console.log("Orama Chunks: ",s),console.log("Combined Chunks: ",u),console.log("Max Orama Score: ",c),f?console.log("Reranked Chunks: ",l):console.log("No reranking applied.")),l})}async getExplicitChunks(r){let n=[];for(let o of r){let i=await O0.getInstance().getDocumentsByPath(o.path);if(i.length===0)continue;let a=i.map(s=>new tl({pageContent:s.content,metadata:{...s.metadata,score:1,path:s.path,mtime:s.mtime,ctime:s.ctime,title:s.title,id:s.id,embeddingModel:s.embeddingModel,tags:s.tags,extension:s.extension,created_at:s.created_at,nchars:s.nchars,chunkId:s.metadata?.chunkId}}));n.push(...a)}return n}async getOramaChunks(r,n,o){let i;try{i=await this.convertQueryToVector(r)}catch(l){throw console.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",l,`
Query:`,r),l}let a=await O0.getInstance().getDb(),s={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(n.length>0){let l;o||(o=.5),l=1-o;let c=!0;for(let d of n)if(!d.startsWith("#")){c=!1;break}c&&(te().debug&&console.log("Tag only query detected, setting textWeight to 1 and vectorWeight to 0."),o=1,l=0),s.mode="hybrid",s.term=n.join(" "),s.vector={value:i,property:"embedding"},s.hybridWeights={text:o,vector:l}}else s.mode="vector",s.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:l,endTime:c}=this.options.timeRange,d=this.generateDailyNoteDateRange(l,c);F("Daily note date range:",d[0],d[d.length-1]);let f=kS(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(_=>({..._,metadata:{..._.metadata,includeInContext:!0}}));F("Modified time range:",l,c),s.where={mtime:{between:[l,c]}};let y=(await cv(a,s)).hits.map(_=>new tl({pageContent:_.document.content,metadata:{..._.document.metadata,score:_.score,path:_.document.path,mtime:_.document.mtime,ctime:_.document.ctime,title:_.document.title,id:_.document.id,embeddingModel:_.document.embeddingModel,tags:_.document.tags,extension:_.document.extension,created_at:_.document.created_at,nchars:_.document.nchars,chunkId:_.document.metadata?.chunkId}})),g=[...m,...y];return Array.from(new Set(g.map(_=>_.metadata.id))).map(_=>g.find(w=>w.metadata.id===_)).filter(_=>_!==void 0)}F(`Orama search params:
`,s);let u=await cv(a,s);return!u||!u.hits?(console.warn("Search results or hits are undefined"),[]):u.hits.map(l=>!l||!l.document?(console.warn("Invalid hit or document in search results"),null):((typeof l.score!="number"||isNaN(l.score))&&console.warn("NaN/invalid score detected:",{score:l.score,path:l.document.path,title:l.document.title}),new tl({pageContent:l.document.content||"",metadata:{...l.document.metadata||{},score:l.score,path:l.document.path||"",mtime:l.document.mtime,ctime:l.document.ctime,title:l.document.title||"",id:l.document.id,embeddingModel:l.document.embeddingModel,tags:l.document.tags||[],extension:l.document.extension,created_at:l.document.created_at,nchars:l.document.nchars,chunkId:l.document.metadata?.chunkId}}))).filter(l=>l!==null)}async convertQueryToVector(r){let o=await(await hd.getInstance().getEmbeddingsAPI()).embedQuery(r);if(o.length===0)throw new Error("Query embedding returned an empty vector");return o}generateDailyNoteDateRange(r,n){let o=[],i=new Date(r),a=new Date(n),s=new Date(i);for(;s<=a;)o.push(`[[${s.toLocaleDateString("en-CA")}]]`),s.setDate(s.getDate()+1);return o}filterAndFormatChunks(r,n){let o=this.options.minSimilarityScore,i=r.filter(u=>{let l=u.metadata.score;return typeof l!="number"||isNaN(l)?!0:l>=o}),a=new Set(n.map(u=>u.pageContent)),s=[...n];for(let u of i){let l=u.pageContent;a.has(l)||(a.add(l),s.push(u))}return s.map(u=>({...u,metadata:{...u.metadata,includeInContext:!0}}))}}});function Pst(t){let e=[];for(let r of t)r.type==="tool_use"&&e.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});return e}var Est,Mst=v(()=>{uv();fO();Est=class extends v4{constructor(e){super(e);x(this,"lc_namespace",["langchain","anthropic","output_parsers"]);x(this,"returnId",!1);x(this,"keyName");x(this,"returnSingle",!1);x(this,"zodSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}static lc_name(){return"AnthropicToolsOutputParser"}async _validateResult(e){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch(o){throw new Ih(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(o.message)}`,e)}else r=e;if(this.zodSchema===void 0)return r;let n=await tF(this.zodSchema,r);if(n.success)return n.data;throw new Ih(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(r,null,2))}async parseResult(e){let r=e.flatMap(i=>{let{message:a}=i;return Array.isArray(a.content)?Pst(a.content)[0]:[]});if(r[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[n]=r;return await this._validateResult(n.args)}}});function Dvr(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}var jvr=v(()=>{});function $vr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Lvr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Fvr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function kvr(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}var qvr,Uvr=v(()=>{ta();qvr={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){let e=Cy({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata
2026-01-05 13:03:55 +08:00
`))}if(r.protocol==="http:"||r.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(r.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(`
2026-02-24 07:55:02 +08:00
`))}function hmo(t){let e=[];for(let r of t)if(r._getType()==="tool")if(typeof r.content=="string"){let n=e[e.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"in n.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}):e.push(new qs({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new qs({content:[{type:"tool_result",...r.content!=null?{content:Ast(r)}:{},tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function Kvr(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*gmo(t){let e=["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 n of t){Ph(n)&&(yield GT(n,qvr));let o="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let i;typeof n.image_url=="string"?i=Jvr(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(i=Jvr(n.image_url.url)),i&&(yield{type:"image",source:i,...o?{cache_control:o}:{}})}else{if(kvr(n))return n;if(n.type==="document")yield{...n,...o?{cache_control:o}:{}};else if($vr(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...o?{cache_control:o}:{}};else if(Lvr(n))yield{type:"redacted_thinking",data:n.data,...o?{cache_control:o}:{}};else if(Fvr(n))yield{type:"search_result",title:n.title,source:n.source,..."cache_control"in n&&n.cache_control?{cache_control:n.cache_control}:{},..."citations"in n&&n.citations?{citations:n.citations}:{},content:n.content};else if(r.find(i=>i===n.type)&&"text"in n)yield{type:"text",text:n.text,...o?{cache_control:o}:{},..."citations"in n&&n.citations?{citations:n.citations}:{}};else if(e.find(i=>i===n.type)){let i={...n};if("index"in i&&delete i.index,i.type==="input_json_delta"&&(i.type="tool_use"),"input"in i&&typeof i.input=="string")try{i.input=JSON.parse(i.input)}catch{i.input={}}yield{...i,...o?{cache_control:o}:{}}}else n.type==="container_upload"&&(yield{...n,...o?{cache_control:o}:{}})}}}function Ast(t){let{content:e}=t;return typeof e=="string"?e:Array.from(gmo(e))}function vPe(t){let e=hmo(t),r;e.length>0&&e[0]._getType()==="system"&&(r=t[0].content);let o=(r!==void 0?e.slice(1):e).map(i=>{let a;if(i._getType()==="human")a="user";else if(i._getType()==="ai")a="assistant";else if(i._getType()==="tool")a="user";else throw i._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${i.type}" is not supported.`);if(kl(i)&&i.response_metadata?.output_version==="v1")return{role:a,content:Hvr(i)};if(kl(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(Kvr)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(Kvr)]};{let{content:s}=i;return!i.tool_calls.every(l=>s.find(c=>(c.type==="tool_use"||c.type==="input_json_delta"||c.type==="server_tool_use")&&c.id===l.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:Ast(i)}}}else return{role:a,content:Ast(i)}});return{messages:ymo(o),system:r}}function ymo(t){if(!t||t.length<=1)return t;let e=[],r=t[0],n=i=>typeof i=="string"?[{type:"text",text:i}]:i,o=i=>i.role!=="user"||typeof i.content=="string"?!1:Array.isArray(i.content)&&i.content.every(a=>a.type==="tool_result");for(let i=1;i<t.length;i+=1){let a=t[i];o(r)&&o(a)?r={...r,content:[...n(r.content),...n(a.content)]}:(e.push(r),r=a)}return e.push(r),e}var Nst=v(()=>{Uvr();Wvr();ta()});function Gvr(t,e){let r={model_provider:"anthropic"};if(t.type==="message_start"){let{content:n,usage:o,...i}=t.message,a={};for(let[d,f]of Object.entries(i))f!=null&&(a[d]=f);let{input_tokens:s,output_tokens:u,...l}=o??{},c={input_tokens:s,output_tokens:u,total_tokens:s+u,input_token_details:{
2026-01-05 13:03:55 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2026-02-24 07:55:02 +08:00
`,t}function Dst(t){let e;return t.status===400&&t.message.includes("tool")?e=wPe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=wPe(t,"MODEL_AUTHENTICATION"):t.status===404?e=wPe(t,"MODEL_NOT_FOUND"):t.status===429?e=wPe(t,"MODEL_RATE_LIMIT"):e=t,e}var Yvr=v(()=>{});function hr(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="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 n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function Ie(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var $D=v(()=>{});var jst,Qvr=v(()=>{jst=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return jst=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}});function LD(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var kae,_9=v(()=>{kae=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 un,Kh,oy,Pq,v9,w9,S9,C9,x9,T9,O9,E9,P9,zx=v(()=>{_9();un=class extends Error{},Kh=class t extends un{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("request-id"),this.error=r}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new Pq({message:n,cause:kae(r)});let i=r;return e===400?new w9(e,i,n,o):e===401?new S9(e,i,n,o):e===403?new C9(e,i,n,o):e===404?new x9(e,i,n,o):e===409?new T9(e,i,n,o):e===422?new O9(e,i,n,o):e===429?new E9(e,i,n,o):e>=500?new P9(e,i,n,o):new t(e,i,n,o)}},oy=class extends Kh{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Pq=class extends Kh{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},v9=class extends Pq{constructor({message:e}={}){super({message:e??"Request timed out."})}},w9=class extends Kh{},S9=class extends Kh{},C9=class extends Kh{},x9=class extends Kh{},T9=class extends Kh{},O9=class extends Kh{},E9=class extends Kh{},P9=class extends Kh{}});function Fst(t){return typeof t!="object"?{}:t??{}}function twr(t){if(!t)return!0;for(let e in t)return!1;return!0}function rwr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var _mo,ewr,$st,Lst,nwr,SPe,SH=v(()=>{zx();_mo=/^[a-z][a-z0-9+.-]*:/i,ewr=t=>_mo.test(t),$st=t=>($st=Array.isArray,$st(t)),Lst=$st;nwr=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new un(`${t} must be an integer`);if(e<0)throw new un(`${t} must be a positive integer`);return e},SPe=t=>{try{return JSON.parse(t)}catch{return}}});var owr,iwr=v(()=>{owr=t=>new Promise(e=>setTimeout(e,t))});var Mq,kst=v(()=>{Mq="0.65.0"});function vmo(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function Smo(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+
`):[]}};kw=new WeakMap,qw=new WeakMap;FD.NEWLINE_CHARS=new Set([`
`,"\r"]);FD.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Bae(){}function xPe(t,e,r){return!e||TPe[t]>TPe[r]?Bae:e[t].bind(e)}function Gh(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Omo;let n=_wr.get(e);if(n&&n[0]===r)return n[1];let o={error:xPe("error",e,r),warn:xPe("warn",e,r),info:xPe("info",e,r),debug:xPe("debug",e,r)};return _wr.set(e,[r,o]),o}var TPe,Hst,Omo,_wr,kD,OPe=v(()=>{SH();TPe={off:0,error:200,warn:300,info:400,debug:500},Hst=(t,e,r)=>{if(t){if(rwr(TPe,t))return t;Gh(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(TPe))}`)}};Omo={error:Bae,warn:Bae,info:Bae,debug:Bae},_wr=new WeakMap;kD=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,r])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*Emo(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new un("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 un("Attempted to iterate over a response with no body");let r=new Wst,n=new FD,o=qae(t.body);for await(let i of Pmo(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*Pmo(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Uae(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=bwr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Mmo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var zae,vA,Wst,Jst=v(()=>{$D();zx();M9();Vst();M9();_9();SH();zst();OPe();zx();vA=class t{constructor(e,r,n){this.iterator=e,zae.set(this,void 0),this.controller=r,hr(this,zae,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?Gh(n):console;async function*a(){if(o)throw new un("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of Emo(e,r)){if(u.event==="completion")try{yield JSON.parse(u.data)}catch(l){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),l}if(u.event==="message_start"||u.event==="message_delta"||u.event==="message_stop"||u.event==="content_block_start"||u.event==="content_block_delta"||u.event==="content_block_stop")try{yield JSON.parse(u.data)}catch(l){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),l}if(u.event!=="ping"&&u.event==="error")throw new Kh(void 0,SPe(u.data)??u.data,void 0,e.headers)}s=!0}catch(u){if(LD(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*i(){let s=new FD,u=qae(e);for await(let l of u)for(let c of s.decode(l))yield c;for(let l of s.flush())yield l}async function*a(){if(o)throw new un("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of i())s||u&&(yield JSON.parse(u));s=!0}catch(u){if(LD(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(zae=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller,Ie(this,zae,"f")),new t(()=>o(r),this.controller,Ie(this,zae,"f"))]}toReadableStream(){let e=this,r;return Ust({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:i}=await r.next();if(i)return n.close();let a=Uae(JSON.stringify(o)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};Wst=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=Mmo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function EPe(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Gh(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):vA.fromSSEResponse(r,e.controller);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let d=await r.json();return Kst(d,r)}return await r.text()})();return Gh(t).debug(`[${n}] response parsed`,kD({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function Kst(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 Gst=v(()=>{Jst();OPe()});var Vae,CH,PPe=v(()=>{$D();Gst();CH=class t extends Promise{constructor(e,r,n=EPe){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Vae.set(this,void 0),hr(this,Vae,e,"f")}_thenUnwrap(e){return new t(Ie(this,Vae,"f"),this.responsePromise,async(r,n)=>Kst(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Ie(this,Vae,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Vae=new WeakMap});var MPe,Xst,Hae,P0,Rq=v(()=>{$D();zx();Gst();PPe();SH();Xst=class{constructor(e,r,n,o){MPe.set(this,void 0),hr(this,MPe,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new un("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Ie(this,MPe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(MPe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Hae=class extends CH{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await EPe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},P0=class extends Xst{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let r=this.first_id;return r?{...this.options,query:{...Fst(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...Fst(this.options.query),after_id:e}}:null}}});function xH(t,e,r){return Yst(),new File(t,e??"unknown_file",r)}function Wae(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}function Imo(t){let e=typeof t=="function"?t:t.fetch,r=vwr.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return vwr.set(e,n),n}var Yst,Qst,wwr,vwr,Amo,Nmo,Zst,RPe=v(()=>{M9();Yst=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versi
2026-01-05 13:03:55 +08:00
${i.map(f=>f.error).join(`
`)}
${a}
2026-02-24 07:55:02 +08:00
${d}`)}return a},ib=kmo(Ewr)});var I9,rut=v(()=>{wA();Rq();SA();RPe();R9();I9=class extends Fd{list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/files",P0,{query:o,...r,headers:ia([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};return this._client.delete(ib`/v1/files/${e}`,{...n,headers:ia([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,r={},n){let{betas:o}=r??{};return this._client.get(ib`/v1/files/${e}/content`,{...n,headers:ia([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},n){let{betas:o}=r??{};return this._client.get(ib`/v1/files/${e}`,{...n,headers:ia([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,r){let{betas:n,...o}=e;return this._client.post("/v1/files",wwr({body:o,...r,headers:ia([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])},this._client))}}});var A9,nut=v(()=>{wA();Rq();SA();R9();A9=class extends Fd{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(ib`/v1/models/${e}?beta=true`,{...n,headers:ia([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/models?beta=true",P0,{query:o,...r,headers:ia([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var N9,out=v(()=>{zx();M9();Vst();N9=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new FD;for await(let r of this.iterator)for(let n of e.decode(r))yield JSON.parse(n);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new un("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 un("Attempted to iterate over a response with no body");return new t(qae(e.body),r)}}});var Jae=v(()=>{zx()});var D9,iut=v(()=>{wA();Rq();SA();out();Jae();R9();D9=class extends Fd{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/messages/batches?beta=true",{body:o,...r,headers:ia([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(ib`/v1/messages/batches/${e}?beta=true`,{...n,headers:ia([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",P0,{query:o,...r,headers:ia([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};return this._client.delete(ib`/v1/messages/batches/${e}?beta=true`,{...n,headers:ia([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,r={},n){let{betas:o}=r??{};return this._client.post(ib`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:ia([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,r={},n){let o=await this.retrieve(e);if(!o.results_url)throw new un(`No batch \`results_url\`; Has it finished processing? ${o.processing_status} - ${o.id}`);let{betas:i}=r??{};return this._client.get(o.results_url,{...n,headers:ia([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,s)=>N9.fromResponse(s.response,s.controller))}}});var aut=v(()=>{Jst()});var zmo,j9,Vmo,Hmo,APe,sut=v(()=>{zmo=t=>{let e=0,r=[];for(;e<t.length;){let n=t[e];if(n==="\\"){e++;continue}if(n==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(n==="["){r.push({type:"paren",value:"["}),e+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let i=this._client._options.timeout;if(!o.stream&&i==null){let a=UPe[o.model]??void 0;i=this._client.calculateNonstreamingTimeout(o.max_tokens,a)}return this._client.post("/v1/messages?beta=true",{body:o,timeout:i??6e5,...r,headers:ia([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}stream(e,r){return qPe.createMessage(this,e,r)}countTokens(e,r){let{betas:n,...o}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:o,...r,headers:ia([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},r?.headers])})}toolRunner(e,r){return new F9(this._client,e,r)}};Nq.Batches=D9;Nq.BetaToolRunner=F9});var xA,gut=v(()=>{wA();rut();rut();nut();nut();hut();hut();xA=class extends Fd{constructor(){super(...arguments),this.models=new A9(this._client),this.messages=new Nq(this._client),this.files=new I9(this._client)}};xA.Models=A9;xA.Messages=Nq;xA.Files=I9});var OH,yut=v(()=>{wA();SA();OH=class extends Fd{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/complete",{body:o,timeout:this._client._options.timeout??6e5,...r,headers:ia([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}}});function Fwr(t){return t.type==="tool_use"||t.type==="server_tool_use"}var R0,Dq,tse,zPe,rse,nse,VPe,ose,BD,ise,HPe,WPe,k9,JPe,KPe,but,jwr,_ut,vut,wut,Sut,$wr,Lwr,GPe,kwr=v(()=>{$D();_9();Jae();aut();sut();Lwr="__json_buf";GPe=class t{constructor(){R0.add(this),this.messages=[],this.receivedMessages=[],Dq.set(this,void 0),this.controller=new AbortController,tse.set(this,void 0),zPe.set(this,()=>{}),rse.set(this,()=>{}),nse.set(this,void 0),VPe.set(this,()=>{}),ose.set(this,()=>{}),BD.set(this,{}),ise.set(this,!1),HPe.set(this,!1),WPe.set(this,!1),k9.set(this,!1),JPe.set(this,void 0),KPe.set(this,void 0),_ut.set(this,e=>{if(hr(this,HPe,!0,"f"),LD(e)&&(e=new oy),e instanceof oy)return hr(this,WPe,!0,"f"),this._emit("abort",e);if(e instanceof un)return this._emit("error",e);if(e instanceof Error){let r=new un(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new un(String(e)))}),hr(this,tse,new Promise((e,r)=>{hr(this,zPe,e,"f"),hr(this,rse,r,"f")}),"f"),hr(this,nse,new Promise((e,r)=>{hr(this,VPe,e,"f"),hr(this,ose,r,"f")}),"f"),Ie(this,tse,"f").catch(()=>{}),Ie(this,nse,"f").catch(()=>{})}get response(){return Ie(this,JPe,"f")}get request_id(){return Ie(this,KPe,"f")}async withResponse(){let e=await Ie(this,tse,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let o=new t;for(let i of r.messages)o._addMessageParam(i);return o._run(()=>o._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},Ie(this,_ut,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){let o=n?.signal,i;o&&(o.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),o.addEventListener("abort",i));try{Ie(this,R0,"m",vut).call(this);let{response:a,data:s}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(a);for await(let u of s)Ie(this,R0,"m",wut).call(this,u);if(s.controller.signal?.aborted)throw new oy;Ie(this,R0,"m",Sut).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(hr(this,JPe,e,"f"),hr(this,KPe,e?.headers.get("request-id"),"f"),Ie(this,zPe,"f").call(this,e),this._emit("connect"))}get ended(){return Ie(this,ise,"f")}get errored(){return Ie(this,HPe,"f")}get aborted(){return Ie(this,WPe,"f")}abort(){this.controller.abort()}on(e,r){return(Ie(this,BD,"f")[e]||(Ie(this,BD,"f")[e]=[])).pu
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){let o=UPe[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...r,stream:e.stream??!1})}stream(e,r){return GPe.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},qwr={"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-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};jq.Batches=q9});var EH,Tut=v(()=>{wA();Rq();SA();R9();EH=class extends Fd{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(ib`/v1/models/${e}`,{...n,headers:ia([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/models",P0,{query:o,...r,headers:ia([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var Uwr=v(()=>{xwr();gut();yut();xut();Tut()});var ase,Bwr=v(()=>{ase=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()}});var Out,Eut,XPe,zwr,Vwr,Hwr,Tc,TA,Put=v(()=>{$D();Qvr();SH();iwr();_9();qst();M9();mwr();kst();zx();Rq();tut();Uwr();PPe();yut();Tut();gut();xut();qst();SA();Bwr();OPe();SH();Vwr="\\n\\nHuman:",Hwr="\\n\\nAssistant:",Tc=class{constructor({baseURL:e=ase("ANTHROPIC_BASE_URL"),apiKey:r=ase("ANTHROPIC_API_KEY")??null,authToken:n=ase("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){Out.add(this),XPe.set(this,void 0);let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&lwr())throw new un(`It looks like you're running in a browser-like environment.
2026-01-05 13:03:55 +08:00
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 });
2026-02-24 07:55:02 +08:00
`);this.baseURL=i.baseURL,this.timeout=i.timeout??Eut.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a="warn";this.logLevel=a,this.logLevel=Hst(i.logLevel,"ClientOptions.logLevel",this)??Hst(ase("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??dwr(),hr(this,XPe,pwr,"f"),this._options=i,this.apiKey=r,this.authToken=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,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return ia([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return ia([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return ia([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new un(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Mq}`}defaultIdempotencyKey(){return`stainless-node-retry-${jst()}`}makeStatusError(e,r,n,o){return Kh.generate(e,r,n,o)}buildURL(e,r,n){let o=!Ie(this,Out,"m",zwr).call(this)&&n||this.baseURL,i=ewr(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return twr(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new un("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new CH(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,i=o.maxRetries??this.maxRetries;r==null&&(r=i),await this.prepareOptions(o);let{req:a,url:s,timeout:u}=await this.buildRequest(o,{retryCount:i-r});await this.prepareRequest(a,{url:s,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Gh(this).debug(`[${l}] sending request`,kD({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new oy;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(kae),m=Date.now();if(p instanceof globalThis.Error){let g=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new oy;let b=LD(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Gh(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${g}`),Gh(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${g})`,kD({retryOfRequestLogID:n,url:s,durationMs:m-d,messag
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},kut=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=dho(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},z9=class t{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let r=this.decodeText(e);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);return o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new iy(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new iy(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new iy("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};z9.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);z9.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g});async function But(t,e,r){if(t=await t,cSr(t))return t;if(lSr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=yse(o)?[await o.arrayBuffer()]:[o];return new ZPe(i,e,r)}let n=await pho(t);if(e||(e=hho(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new ZPe(n,e,r)}async function pho(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(yse(t))e.push(await t.arrayBuffer());else if(gho(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${mho(t)}`);return e}function mho(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function hho(t){return qut(t.name)||qut(t.filename)||qut(t.path)?.split(/[\\/]/).pop()}var lSr,cSr,yse,fho,qut,gho,zut,IH,dSr,Uut,rMe=v(()=>{sse();sse();lSr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",cSr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&yse(t),yse=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",fho=t=>cSr(t)||lSr(t)||$ut(t);qut=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},gho=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",zut=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",IH=async t=>{let e=await dSr(t.body);return Dut(e,t)},dSr=async t=>{let e=new Aut;return await Promise.all(Object.entries(t||{}).map(([r,n])=>Uut(e,r,n))),e},Uut=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(fho(r)){let n=await But(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>Uut(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Uut(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});async function ySr(t){let{response:e}=t;if(t.options.stream)return V9("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):tMe.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let n=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){let a=await e.json();return V9("response",e.status,e.url,e.headers,a),a}let i=await e.text();return V9("response",e.status,e.url,e.headers,i),i}function Sho(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}return null}function Pho(t){if(!t)return!0;for(let e in t)return!1;return!0}function Mho(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function gSr(t,e){for(let r in e){if(!Mho(e,r))continue;let n=r.toLowerCase();if(!n)continue;let o=e[r];o===null?delete t[n]:o!==void 0&&(t[n]=o)}}function V9(t,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Groq:DEBUG:${t}`,...e)}var bho,_ho,nMe,iMe,aMe,fSr,Hut,vho,who,pSr,mSr,hSr,Cho,xho,T
2026-01-05 13:03:55 +08:00
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.,
2026-02-24 07:55:02 +08:00
new Groq({ apiKey, dangerouslyAllowBrowser: true })`);super({baseURL:o.baseURL,timeout:o.timeout??6e4,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new NH(this),this.chat=new Lq(this),this.embeddings=new DH(this),this.audio=new OA(this),this.models=new $H(this),this.batches=new AH(this),this.files=new jH(this),this._options=o,this.apiKey=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}};wSr=_u;_u.Groq=wSr;_u.DEFAULT_TIMEOUT=6e4;_u.GroqError=iy;_u.APIError=Xh;_u.APIConnectionError=$q;_u.APIConnectionTimeoutError=U9;_u.APIUserAbortError=RH;_u.NotFoundError=dse;_u.ConflictError=fse;_u.RateLimitError=mse;_u.BadRequestError=use;_u.AuthenticationError=lse;_u.InternalServerError=hse;_u.PermissionDeniedError=cse;_u.UnprocessableEntityError=pse;_u.toFile=But;_u.fileFromPath=YPe;_u.Completions=NH;_u.Chat=Lq;_u.Embeddings=DH;_u.Audio=OA;_u.Models=$H;_u.Batches=AH;_u.Files=jH;SSr=_u});function qho(t){if(t.role!=="system"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function")throw new Error(`Unsupported message role: ${t.role}. Expected "system", "assistant", "user", or "function"`);return t.role}function TSr(t){switch(t.type){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Td.isInstance(t))throw new Error("Invalid generic chat message");return qho(t);default:throw new Error(`Unknown message type: ${t.type}`)}}function xSr(t){return t.map(e=>{let r={role:TSr(e),content:e.content,name:e.name,function_call:e.additional_kwargs.function_call,tool_calls:e.additional_kwargs.tool_calls,tool_call_id:e.tool_call_id};return kl(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(Jk):(e.additional_kwargs.tool_calls!=null&&(r.tool_calls=e.additional_kwargs.tool_calls),e.tool_call_id!=null&&(r.tool_call_id=e.tool_call_id)),r})}function Uho(t,e,r){let n=t.tool_calls;switch(t.role){case"assistant":{let o=[],i=[];for(let a of n??[])try{o.push(Ix(a,{returnId:!0}))}catch(s){i.push(_0(a,s.message))}return new Pn({content:t.content||"",additional_kwargs:{tool_calls:n},tool_calls:o,invalid_tool_calls:i,usage_metadata:e,response_metadata:r})}default:return new Td(t.content||"",t.role??"unknown")}}function Bho(t,e,r,n){let o=t.role??e,i=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},t.audio&&(a.audio={...t.audio,index:r.choices[0].index});let s,u=n,l,c=r.x_groq;c?.usage&&(s={input_tokens:c.usage.prompt_tokens,output_tokens:c.usage.completion_tokens,total_tokens:c.usage.total_tokens},l={completion_time:c.usage.completion_time,prompt_time:c.usage.prompt_time,queue_time:c.usage.queue_time,total_time:c.usage.total_time}),c?.id&&(u=c.id);let d={usage:s,timing:l};if(o==="user")return new rw({content:i,response_metadata:d});if(o==="assistant"){let f=[];if(Array.isArray(t.tool_calls))for(let p of t.tool_calls)f.push({name:p.function?.name,args:p.function?.arguments,id:p.id,index:p.index,type:"tool_call_chunk"});return new Er({content:i,tool_call_chunks:f,additional_kwargs:a,id:u,response_metadata:d})}else return o==="system"?new Rb({content:i,response_metadata:d}):o==="developer"?new Rb({content:i,response_metadata:d,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new tw({content:i,additional_kwargs:a,name:t.name,response_metadata:d}):o==="tool"?new _S({content:i,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:d}):new ew({content:i,role:o,response_metadata:d})}function zho(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}var Lho,Fho,kho,olt,OSr=v(()=>{Ny();YI();ta();Ed();au();uv();CSr();sw();fO();PV();pD();Lho=["frequency_penalty","function_call","functions","logit_bias","logprobs","max_completion_tokens","max_tokens","n","parallel_tool_calls","presence_penalty","reasoning_format"
${Ult(this.cause)}`:this.toString()}};Wx.SDKValidationError=qlt;function Ult(t,e=0){let r=" ".repeat(e);r=e>0?`\u2502${r}`:r,r+=" ".repeat(e);let n="",o=s=>n+=`
${r}${s}`,i=t.issues.length,a=i===1?`${i} issue found`:`${i} issues found`;i&&o(`\u250C ${a}:`);for(let s of t.issues){let u=s.path.join(".");switch(u=u?`<root>.${u}`:"<root>",o(`\u2502 \u2022 [${u}]: ${s.message} (${s.code})`),s.code){case"invalid_literal":case"invalid_type":{o(`\u2502 Want: ${s.expected}`),o(`\u2502 Got: ${s.received}`);break}case"unrecognized_keys":{o(`\u2502 Keys: ${s.keys.join(", ")}`);break}case"invalid_enum_value":{o(`\u2502 Allowed: ${s.options.join(", ")}`),o(`\u2502 Got: ${s.received}`);break}case"invalid_union_discriminator":{o(`\u2502 Allowed: ${s.options.join(", ")}`);break}case"invalid_union":{let l=s.unionErrors.length;o(`\u2502 \u2716\uFE0E Attemped to deserialize into one of ${l} union members:`),s.unionErrors.forEach((c,d)=>{o(`\u2502 \u2716\uFE0E Member ${d+1} of ${l}`),o(`${Ult(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var zlt=S(AA=>{"use strict";var Sbo=AA&&AA.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Cbo=AA&&AA.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xbo=AA&&AA.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Sbo(r,e,n[o]);return Cbo(r,e),r}}();Object.defineProperty(AA,"__esModule",{value:!0});AA.ResponseValidationError=void 0;var Tbo=xbo(ae()),Obo=MMe(),Ebo=RMe(),Blt=class extends Obo.MistralError{constructor(e,r){super(e,r),this.name="ResponseValidationError",this.cause=r.cause,this.rawValue=r.rawValue,this.rawMessage=r.rawMessage}pretty(){return this.cause instanceof Tbo.ZodError?`${this.rawMessage}
${(0,Ebo.formatZodError)(this.cause)}`:this.toString()}};AA.ResponseValidationError=Blt});var Hlt=S(IMe=>{"use strict";Object.defineProperty(IMe,"__esModule",{value:!0});IMe.SDKError=void 0;var Pbo=MMe(),Vlt=class extends Pbo.MistralError{constructor(e,r){e&&(e+=": "),e+=`Status ${r.response.status}`;let n=r.response.headers.get("content-type")||'""';n!=="application/json"&&(e+=` Content-Type ${n.includes(" ")?`"${n}"`:n}`);let o=r.body||'""';e+=o.length>100?`
`:". ";let i=o;if(o.length>1e4){let a=o.substring(0,1e4),s=o.length-1e4;i=`${a}...and ${s} more chars`}e+=`Body: ${i}`,e=e.trim(),super(e,r),this.name="SDKError"}};IMe.SDKError=Vlt});var gr=S(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});Km.jsonErr=Ibo;Km.json=Abo;Km.jsonl=Nbo;Km.jsonlErr=Dbo;Km.textErr=jbo;Km.text=$bo;Km.bytesErr=Lbo;Km.bytes=Fbo;Km.streamErr=kbo;Km.stream=qbo;Km.sseErr=Ubo;Km.sse=Bbo;Km.nilErr=zbo;Km.nil=Vbo;Km.fail=Hbo;Km.match=Wbo;Km.unpackHeaders=AMe;var Mbo=zlt(),O0r=Hlt(),E0r=kd(),P0r=X9(),M0r=Alt(),Rbo={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function Ibo(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function Abo(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function Nbo(t,e,r){return{...r,enc:"jsonl",codes:t,schema:e}}function Dbo(t,e,r){return{...r,err:!0,enc:"jsonl",codes:t,schema:e}}function jbo(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function $bo(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function Lbo(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function Fbo(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function kbo(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function qbo(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function Ubo(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function Bbo(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function zbo(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function Vbo(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function Hbo(t){return{enc:"fail",codes:t}}function Wbo(...t){return async function(r,n,o){let i,a;for(let d of t){let{codes:f}=d,p="ctype"in d?d.ctype:Rbo[d.enc];if(p&&(0,P0r.matchResponse)(r,f,p)){a=d;break}else if(!p&&(0,P0r.matchStatusCode)(r,f)){a=d;break}}if(!a)return[{ok:!1,error:new O0r.SDKError("Unexpected Status or Content-Type",{response:r,request:n,body:await r.text().catch(()=>"")})},i];let s=a.enc,u="";switch(s){case"json":u=await r.text(),i=JSON.parse(u);break;case"jsonl":i=r.body;break;case"bytes":i=new Uint8Array(await r.arrayBuffer());break;case"stream":i=r.body;break;case"text":u=await r.text(),i=u;break;case"sse":i=r.body;break;case"nil":u=await r.text(),i=void 0;break;case"fail":u=await r.text(),i=u;break;default:throw new Error(`Unsupported response type: ${s}`)}if(a.enc==="fail")return[{ok:!1,error:new O0r.SDKError("API error occurred",{request:n,response:r,body:u})},i];let l=a.key||o?.resultKey,c;if("err"in a?c={...o?.extraFields,...a.hdrs?{Headers:AMe(r.headers)}:null,...(0,M0r.isPlainObject)(i)?i:null,request$:n,response$:r,body$:u}:l?c={...o?.extraFields,...a.hdrs?{Headers:AMe(r.headers)}:null,[l]:i}:a.hdrs?c={...o?.extraFields,...a.hdrs?{Headers:AMe(r.headers)}:null,...(0,M0r.isPlainObject)(i)?i:null}:c=i,"err"in a){let d=R0r(c,f=>a.schema.parse(f),"Response validation failed",{request:n,response:r,body:u});return[d.ok?{ok:!1,error:d.value}:d,i]}else return[R0r(c,d=>a.schema.parse(d),"Response validation failed",{request:n,response:r,body:u}),i]}}var Jbo=/, */;function AMe(t){let e={};for(let[r,n]of t.entries())e[r]=n.split(Jbo);return e}function R0r(t,e,r,n){try{return(0,E0r.OK)(e(t))}catch(o){return(0,E0r.ERR)(new Mbo.ResponseValidationError(r,{cause:o,rawValue:t,rawMessage:r,...n}))}}});var ce=S(Wq=>{"use strict";Object.defineProperty(Wq,"__esModule",{value:!0});Wq.invariant=Kbo;Wq.remap=Gbo;Wq.combineSignals=Xbo;Wq.abortSignalAny=I0r;Wq.compactMap=Zbo;Wq.allRequired=Ybo;var Wlt=class extends Error{constructor(e){super(e),this.name="InvariantError"}};function Kbo(t,e){if(!t)throw new Wlt(e)}function Gbo(t,e){let r={};if(!Object.keys(e).length)return r=t,r;for(let[n,o]of Object.entries(t)){let i=e[n];i!==null&&(r[i??n]=o)}return r}function Xbo(...t){let e=[];for(let r of t)r&&e.push(r);switch(e.length){case 0:case 1:return e[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(e):I0r(e)}}function I0r(t){let e=new AbortController,r=e.signal;i
`)),e(i)}});var gjr=S(nj=>{"use strict";var Mko=nj&&nj.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Rko=nj&&nj.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),AAe=nj&&nj.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Mko(r,e,n[o]);return Rko(r,e),r}}();Object.defineProperty(nj,"__esModule",{value:!0});nj.agentsStream=kko;var Iko=AAe(ae()),Ako=Cr(),Nko=yU(),Kse=AAe(gr()),Dko=ce(),jko=ee(),mjr=yr(),$ko=fr(),hjr=AAe(Vt()),Lko=AAe(Qn()),Fko=br();function kko(t,e,r){return new Fko.APIPromise(qko(t,e,r))}async function qko(t,e,r){let n=(0,jko.safeParse)(e,b=>hjr.AgentsCompletionStreamRequest$outboundSchema.parse(b),"Input validation failed");if(!n.ok)return[n,{status:"invalid"}];let o=n.value,i=(0,Ako.encodeJSON)("body",o,{explode:!0}),a=(0,$ko.pathToFunc)("/v1/agents/completions#stream")(),s=new Headers((0,Dko.compactMap)({"Content-Type":"application/json",Accept:"text/event-stream"})),u=await(0,mjr.extractSecurity)(t._options.apiKey),l=u==null?{}:{apiKey:u},c=(0,mjr.resolveGlobalSecurity)(l),d={options:t._options,baseURL:r?.serverURL??t._baseURL??"",operationID:"stream_agents",oAuth2Scopes:[],resolvedSecurity:c,securitySource:t._options.apiKey,retryConfig:r?.retries||t._options.retryConfig||{strategy:"none"},retryCodes:r?.retryCodes||["429","500","502","503","504"]},f=t._createRequest(d,{security:c,method:"POST",baseURL:r?.serverURL,path:a,headers:s,body:i,userAgent:t._options.userAgent,timeoutMs:r?.timeoutMs||t._options.timeoutMs||-1},r);if(!f.ok)return[f,{status:"invalid"}];let p=f.value,m=await t._do(p,{context:d,errorCodes:["422","4XX","5XX"],retryConfig:d.retryConfig,retryCodes:d.retryCodes});if(!m.ok)return[m,{status:"request-error",request:p}];let h=m.value,y={HttpMeta:{Response:h,Request:p}},[g]=await Kse.match(Kse.sse(200,Iko.instanceof(ReadableStream).transform(b=>new Nko.EventStream(b,_=>_.data==="[DONE]"?{done:!0}:{value:hjr.CompletionEvent$inboundSchema.parse(_)}))),Kse.jsonErr(422,Lko.HTTPValidationError$inboundSchema),Kse.fail("4XX"),Kse.fail("5XX"))(h,p,{extraFields:y});return g.ok?[g,{status:"complete",request:p,response:h}]:[g,{status:"complete",request:p,response:h}]}});var bjr=S(NAe=>{"use strict";Object.defineProperty(NAe,"__esModule",{value:!0});NAe.Agents=void 0;var Uko=pjr(),Bko=gjr(),zko=Wc(),yjr=kd(),ydt=class extends zko.ClientSDK{async complete(e,r){return(0,yjr.unwrapAsync)((0,Uko.agentsComplete)(this,e,r))}async stream(e,r){return(0,yjr.unwrapAsync)((0,Bko.agentsStream)(this,e,r))}};NAe.Agents=ydt});var Gse=S(bdt=>{"use strict";Object.defineProperty(bdt,"__esModule",{value:!0});bdt.isReadableStream=Vko;function Vko(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.getReader=="function"&&typeof e.cancel=="function"&&typeof e.tee=="function"}});var Sjr=S(oj=>{"use strict";var Hko=oj&&oj.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Wko=oj&&oj.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),wjr=oj&&oj.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null
2026-01-05 13:03:55 +08:00
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
`:`[${n[u]}\r
2026-02-24 07:55:02 +08:00
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!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 b1e=S(y1e=>{"use strict";Object.defineProperty(y1e,"__esModule",{value:!0});y1e.parseRecordDef=void 0;var jue=ae(),hUr=wm(),J8o=g1e(),K8o=u1e();function G8o(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===jue.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,hUr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,hUr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===jue.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,J8o.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===jue.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===jue.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===jue.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,K8o.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}y1e.parseRecordDef=G8o});var nft=S(_1e=>{"use strict";Object.defineProperty(_1e,"__esModule",{value:!0});_1e.parseMapDef=void 0;var gUr=wm(),X8o=b1e();function Z8o(t,e){if(e.mapStrategy==="record")return(0,X8o.parseRecordDef)(t,e);let r=(0,gUr.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,gUr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}_1e.parseMapDef=Z8o});var oft=S(v1e=>{"use strict";Object.defineProperty(v1e,"__esModule",{value:!0});v1e.parseNativeEnumDef=void 0;function Y8o(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}v1e.parseNativeEnumDef=Y8o});var ift=S(w1e=>{"use strict";Object.defineProperty(w1e,"__esModule",{value:!0});w1e.parseNeverDef=void 0;function Q8o(){return{not:{}}}w1e.parseNeverDef=Q8o});var aft=S(S1e=>{"use strict";Object.defineProperty(S1e,"__esModule",{value:!0});S1e.parseNullDef=void 0;function eGo(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}S1e.parseNullDef=eGo});var C1e=S(wU=>{"use strict";Object.defineProperty(wU,"__esModule",{value:!0});wU.parseUnionDef=wU.primitiveMappings=void 0;var tGo=wm();wU.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function rGo(t,e){if(e.target==="openApi3")return yUr(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in wU.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=wU.primitiveMappings[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];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(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(
2026-01-05 13:03:55 +08:00
Received: ${JSON.stringify(i,null,2)}`)};if(typeof i=="string")return i;if(Array.isArray(i)){let u=e(a),l=[];return i.forEach(c=>{if(c.type==="text"||c.type==="image_url")l.push(s(c,u));else throw new Error('Mistral only supports types "text" or "image_url" for complex message types.')}),l}throw new Error(`Message content must be a string or an array.
2026-02-24 07:55:02 +08:00
Received: ${JSON.stringify(i,null,2)}`)},n=i=>{if(kl(i)&&i.tool_calls?.length)return i.tool_calls.map(a=>({...a,id:bse(a.id??"")})).map(Jk)},o=new Set;for(let i of t)"tool_call_id"in i&&typeof i.tool_call_id=="string"&&o.add(bse(i.tool_call_id));return t.flatMap(i=>{let a=n(i),s=r(i.content,i.getType());if("tool_call_id"in i&&typeof i.tool_call_id=="string")return[{role:e(i.getType()),content:s,name:i.name,toolCallId:bse(i.tool_call_id)}];if(kl(i)){if(a===void 0)return[{role:e(i.getType()),content:s}];{let u=a.filter(l=>o.has(bse(l.id??"")));return u.length===0?typeof s=="string"&&s.trim()===""||Array.isArray(s)&&s.length===0?[]:[{role:e(i.getType()),content:s}]:[{role:e(i.getType()),toolCalls:u}]}}return[{role:e(i.getType()),content:s}]})}function KQo(t,e){let{message:r}=t;if(r===void 0)throw new Error("No message found in response");let n=[];"toolCalls"in r&&Array.isArray(r.toolCalls)&&(n=r.toolCalls);let o=ilt(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=Ix(s,{returnId:!0});i.push({...u,id:u.id??cMe().replace(/-/g,"")})}catch(u){a.push(_0(s,u.message))}return new Pn({content:o,tool_calls:i,invalid_tool_calls:a,additional_kwargs:{},usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void 0})}default:return new qs({content:o})}}function GQo(t,e){if(!t.content&&!t.toolCalls)return e?new Er({content:"",usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void 0}):null;let r=t.toolCalls?.length?t.toolCalls?.map((s,u)=>({...s,index:u,id:s.id??cMe().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=ilt(t.content),i,a=[];if(r!==void 0)for(let s of r){let u=s.function?.arguments,l=u===void 0||typeof u=="string"?u:JSON.stringify(u);a.push({name:s.function?.name,args:l,id:s.id,index:s.index,type:"tool_call_chunk"})}else i={};return n==="user"?new rw({content:o}):n==="assistant"?new Er({content:o,tool_call_chunks:a,additional_kwargs:i,usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void 0}):n==="tool"?new _S({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new tw({content:o,additional_kwargs:i}):new ew({content:o,role:n})}function ozr(t){if(!(!t||!t.length))return t.map(e=>{if("function"in e)return{type:e.type??"function",function:e.function};if(Xg(e)){let r=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:Ii(e.schema)?Ci(e.schema):e.schema}}}throw new Error(`Unknown tool type passed to ChatMistral: ${JSON.stringify(e,null,2)}`)})}var izr,azr,Qft,szr=v(()=>{PSr();DSr();izr=$(nzr(),1),azr=$(X9(),1);ta();YI();Ed();Jz();au();fO();PV();sw();Ny();pD();uv();Qft=class extends jd{constructor(e){super(e??{});x(this,"lc_namespace",["langchain","chat_models","mistralai"]);x(this,"model","mistral-small-latest");x(this,"apiKey");x(this,"endpoint");x(this,"serverURL");x(this,"temperature",.7);x(this,"streaming",!1);x(this,"topP",1);x(this,"maxTokens");x(this,"safeMode",!1);x(this,"safePrompt",!1);x(this,"randomSeed");x(this,"seed");x(this,"maxRetries");x(this,"lc_serializable",!0);x(this,"streamUsage",!0);x(this,"beforeRequestHooks");x(this,"requestErrorHooks");x(this,"responseHooks");x(this,"httpClient");x(this,"presencePenalty");x(this,"frequencyPenalty");x(this,"numCompletions");let r=e?.apiKey??Xr("MISTRAL_API_KEY");if(!r)throw new Error("API key MISTRAL_API_KEY is missing for MistralAI, but it is required.");this.apiKey=r,this.streaming=e?.streaming??this.streaming,this.serverURL=e?.serverURL??this.serverURL,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokens??this.maxTokens,this.safePrompt=e?.safePrompt??this.safePrompt,this.randomSeed=e?.seed??e?.randomSeed??this.seed,this.seed=this.randomSeed,this.maxRetries=e?.maxRetries,this.httpClient=e?.httpClient,this.model=e?.model??e?.modelName??this.model,this.streamUsage=e?.streamUsage??this.streamUsage,this.beforeRequestHooks=
`):[]}};Gw=new WeakMap;P3.NEWLINE_CHARS=new Set([`
`,"\r"]);P3.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function mpt(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var Izr=v(()=>{});async function*dei(t,e){if(!t.body)throw e.abort(),new jr("Attempted to iterate over a response with no body");let r=new hpt,n=new P3,o=mpt(t.body);for await(let i of fei(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*fei(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=Mzr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function pei(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var YA,hpt,vDe=v(()=>{Gue();Kw();Rzr();Izr();Xi();Kw();YA=class t{constructor(e,r){this.iterator=e,this.controller=r}static fromSSEResponse(e,r){let n=!1;async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of dei(e,r))if(!i){if(a.data.startsWith("[DONE]")){i=!0;continue}if(a.event===null||a.event.startsWith("response.")||a.event.startsWith("transcript.")){let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(s&&s.error)throw new Zm(void 0,s.error,void 0,gpt(e.headers));yield s}else{let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(a.event=="error")throw new Zm(void 0,s.error,s.message,void 0);yield{event:a.event,data:s}}}i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||r.abort()}}return new t(o,r)}static fromReadableStream(e,r){let n=!1;async function*o(){let a=new P3,s=mpt(e);for await(let u of s)for(let l of a.decode(u))yield l;for(let u of a.flush())yield u}async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let s of o())a||s&&(yield JSON.parse(s));a=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{a||r.abort()}}return new t(i,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller),new t(()=>o(r),this.controller)]}toReadableStream(){let e=this,r,n=new TextEncoder;return new upt({async start(){r=e[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:a}=await r.next();if(a)return o.close();let s=n.encode(JSON.stringify(i)+`
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}};hpt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=pei(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function _pt(t,e,r){if(t=await t,Nzr(t))return t;if(Azr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=ole(o)?[await o.arrayBuffer()]:[o];return new hDe(i,e,r)}let n=await hei(t);if(e||(e=yei(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new hDe(n,e,r)}async function hei(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(ole(t))e.push(await t.arrayBuffer());else if(bei(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${gei(t)}`);return e}function gei(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function yei(t){return ypt(t.name)||ypt(t.filename)||ypt(t.path)?.split(/[\\/]/).pop()}var Azr,Nzr,ole,mei,ypt,bei,vpt,Q0,Dzr,bpt,wDe=v(()=>{Gue();Gue();Azr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",Nzr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&ole(t),ole=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",mei=t=>Nzr(t)||Azr(t)||dpt(t);ypt=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},bei=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",vpt=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",Q0=async t=>{let e=await Dzr(t.body);return lpt(e,t)},Dzr=async t=>{let e=new spt;return await Promise.all(Object.entries(t||{}).map(([r,n])=>bpt(e,r,n))),e},bpt=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(mei(r)){let n=await _pt(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>bpt(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>bpt(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});async function qzr(t){let{response:e}=t;if(t.options.stream)return g$("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):YA.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let n=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){let a=await e.json();return g$("response",e.status,e.url,e.headers,a),Uzr(a,e)}let i=await e.text();return g$("response",e.status,e.url,e.headers,i),i}function Uzr(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}function xei(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}return null}function Bzr(t){if(!t)return!0;for(let e in t)return!1;return!0}function zzr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Fzr(t,e){fo
\r `.includes(t[n]);)n++};return a()},Hpt=t=>kei(t,rg.ALL^rg.NUM)});function Uei(t,e){let{id:r,choices:n,created:o,model:i,system_fingerprint:a,...s}=t,u={...s,id:r,choices:n.map(({message:l,finish_reason:c,index:d,logprobs:f,...p})=>{if(!c)throw new jr(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:y,...g}=l,b=l.role;if(!b)throw new jr(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new jr(`missing function_call.arguments for choice ${d}`);if(!w)throw new jr(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:_,name:w},role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return y?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:b,content:m,refusal:l.refusal??null,tool_calls:y.map((_,w)=>{let{function:T,type:O,id:E,...P}=_,{arguments:R,name:I,...N}=T||{};if(E==null)throw new jr(`missing choices[${d}].tool_calls[${w}].id
${$De(t)}`);if(O==null)throw new jr(`missing choices[${d}].tool_calls[${w}].type
${$De(t)}`);if(I==null)throw new jr(`missing choices[${d}].tool_calls[${w}].function.name
${$De(t)}`);if(R==null)throw new jr(`missing choices[${d}].tool_calls[${w}].function.arguments
${$De(t)}`);return{...P,id:E,type:O,function:{...N,name:I,arguments:R}}})}}:{...p,message:{...g,content:m,role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Xzr(u,e)}function $De(t){return JSON.stringify(t)}var eX,xu,Ym,v$,tX,IU,Wpt,DDe,Jpt,Kpt,Gpt,jDe,Xpt,n4r,rX,Zpt=v(()=>{Kw();Bpt();vDe();hle();r4r();eX=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="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 n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},xu=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},rX=class t extends Q7{constructor(e){super(),Ym.add(this),v$.set(this,void 0),tX.set(this,void 0),IU.set(this,void 0),eX(this,v$,e,"f"),eX(this,tX,[],"f")}get currentChatCompletionSnapshot(){return xu(this,IU,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),xu(this,Ym,"m",Wpt).call(this);let i=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of i)xu(this,Ym,"m",Jpt).call(this,a);if(i.controller.signal?.aborted)throw new Sm;return this._addChatCompletion(xu(this,Ym,"m",jDe).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),xu(this,Ym,"m",Wpt).call(this),this._connected();let o=YA.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(xu(this,Ym,"m",jDe).call(this)),xu(this,Ym,"m",Jpt).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Sm;return this._addChatCompletion(xu(this,Ym,"m",jDe).call(this))}[(v$=new WeakMap,tX=new WeakMap,IU=new WeakMap,Ym=new WeakSet,Wpt=function(){this.ended||eX(this,IU,void 0,"f")},DDe=function(r){let n=xu(this,tX,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},xu(this,tX,"f")[r.index]=n,n)},Jpt=function(r){if(this.ended)return;let n=xu(this,Ym,"m",n4r).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let i=n.choices[o.index];o.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",o.delta.content,i.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),o.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.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=xu(this,Ym,"m",DDe).call(this,i);i.finish_reason&&(xu(this,Ym,"m",Gpt).call(this,i),a.current_tool_call_index!=null&&xu(this,Ym,"m",Kpt).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(xu(this,Ym,"m",Gpt).call(this,i),a.current_tool_call_index!=null&&xu(this,Ym,"m",Kpt).call(this,i,a.current_tool_call_index)),a.cu
2026-01-05 13:03:55 +08:00
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 });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
2026-02-24 07:55:02 +08:00
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new $3(this),this.chat=new b$(this),this.embeddings=new L3(this),this.files=new NU(this),this.images=new z3(this),this.audio=new eN(this),this.moderations=new H3(this),this.models=new jU(this),this.fineTuning=new sT(this),this.vectorStores=new Yw(this),this.beta=new aT(this),this.batches=new PU(this),this.uploads=new kU(this),this.responses=new FU(this),this.evals=new oN(this),this._options=a,this.apiKey=r,this.organization=n,this.project=o}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return ipt(e,{arrayFormat:"brackets"})}};C4r=zo;zo.OpenAI=C4r;zo.DEFAULT_TIMEOUT=6e5;zo.OpenAIError=jr;zo.APIError=Zm;zo.APIConnectionError=CU;zo.APIConnectionTimeoutError=xU;zo.APIUserAbortError=Sm;zo.NotFoundError=Que;zo.ConflictError=ele;zo.RateLimitError=rle;zo.BadRequestError=Xue;zo.AuthenticationError=Zue;zo.InternalServerError=nle;zo.PermissionDeniedError=Yue;zo.UnprocessableEntityError=tle;zo.toFile=_pt;zo.fileFromPath=gDe;zo.Completions=$3;zo.Chat=b$;zo.ChatCompletionsPage=EU;zo.Embeddings=L3;zo.Files=NU;zo.FileObjectsPage=q3;zo.Images=z3;zo.Audio=eN;zo.Moderations=H3;zo.Models=jU;zo.ModelsPage=V3;zo.FineTuning=sT;zo.VectorStores=Yw;zo.VectorStoresPage=W3;zo.VectorStoreSearchResponsesPage=J3;zo.Beta=aT;zo.Batches=PU;zo.BatchesPage=M3;zo.Uploads=kU;zo.Responses=FU;zo.Evals=oN;zo.EvalListResponsesPage=k3;x4r=zo});var SX,O4r=v(()=>{ta();Ed();iH();T4r();Xe();SX=class extends RD{constructor(e){let{enableReasoning:r=!1,reasoningEffort:n,...o}=e;super(o),this.enableReasoning=r,this.reasoningEffort=n,this.openaiClient=new x4r({apiKey:e.apiKey,baseURL:e.configuration?.baseURL||"https://openrouter.ai/api/v1",defaultHeaders:e.configuration?.defaultHeaders,fetch:e.configuration?.fetch,dangerouslyAllowBrowser:!0})}invocationParams(e){let r=super.invocationParams(e);if(this.enableReasoning)if(this.reasoningEffort){let n=this.reasoningEffort==="minimal"?"low":this.reasoningEffort;return F(`OpenRouter reasoning enabled with effort: ${n}`),{...r,reasoning:{effort:n}}}else return F("OpenRouter reasoning enabled with max_tokens: 1024"),{...r,reasoning:{max_tokens:1024}};return r}async*_streamResponseChunks(e,r,n){let o=this.invocationParams(r),i=this.toOpenRouterMessages(e),a=await this.openaiClient.chat.completions.create({...o,messages:i,stream:!0,stream_options:{...o.stream_options??{},include_usage:!0}}),s;for await(let u of a){u.usage&&(s=u.usage);let l=u.choices?.[0],c=l?.delta;if(!l||!c)continue;let d=this.normalizeReasoningChunk(c?.reasoning),f=this.extractReasoningDetails(l),p=this.extractDeltaContent(c.content),m=this.buildMessageChunk({rawChunk:u,delta:c,content:p,finishReason:l.finish_reason,reasoningDetails:f,reasoningText:d}),h=new si({message:m,text:typeof m.content=="string"?m.content:"",generationInfo:{finish_reason:l.finish_reason,system_fingerprint:u.system_fingerprint,model:u.model}});yield h,h.text&&await n?.handleLLMNewToken(h.text)}if(s&&(yield this.buildUsageGenerationChunk(s)),r.signal?.aborted)throw new Error("AbortError")}toOpenRouterMessages(e){return e.map(r=>{let n=typeof r._getType=="function"?r._getType():r.role??"user",o=n==="human"?"user":n==="ai"?"assistant":n;return r.tool_call_id?{role:"tool",content:r.content,tool_call_id:r.tool_call_id}:r.additional_kwargs?.function_call?{role:o,content:r.content,function_call:r.additional_kwargs.function_call}:r.additional_kwargs?.tool_calls?{role:o,content:r.content,tool_calls:r.additional_kwargs.tool_calls}:{role:o,content:r.content}})}buildMessageChunk(e){let{rawChunk:r,delta:n,content:o,finishReason:i,reasoningText:a,reasoningDetails:s}=e,u=this.extractToolCallChunks(n.tool_calls),l={};n.function_call&&(l.function_call=n.function_call),Array.isArray(n.tool_calls)&&(l.tool_calls=n.tool_calls);let c={};a&&(c.reaso
`).map(r=>r.trim()).filter(r=>r.length>0):[]}parseEventStreamBuffer(e){let r=[];if(e.length<12)return{messages:r,remainingBytes:e};let n=new DataView(e.buffer,e.byteOffset,e.byteLength),o=0;for(;o+12<=e.length;){let a=n.getUint32(o,!1),s=n.getUint32(o+4,!1);if(o+a>e.length)break;if(a<=0||s<0||s+12>a){Te(`parseEventStreamBuffer: Invalid message structure at offset ${o}: totalLength=${a}, headersLength=${s}`);break}let u=o+12+s,l=o+a-4;if(u>l||l>e.length){Te(`parseEventStreamBuffer: Invalid payload bounds at offset ${o}`);break}if(u<e.length){let c=e.subarray(u,l),d=this.decodeUtf8(c).trim();d.length>0&&r.push(d)}if(o+=a,a===0)break}let i=o<e.length?e.subarray(o):new Uint8Array(0);return{messages:r,remainingBytes:i}}decodeEventStreamMessages(e){let{messages:r}=this.parseEventStreamBuffer(e);return r}buildChunkMetadata(e){let r={provider:"amazon-bedrock"};typeof e?.type=="string"&&(r.event_type=e.type),e?.index!==void 0&&(r.event_index=e.index);let n=this.extractStopReason(e);n&&(r.stop_reason=n);let o=this.extractUsage(e);return o&&(r.usage=o),r}extractStreamText(e){if(!e||typeof e!="object")return null;let r=[e.delta?.thinking,e.content_block_delta?.delta?.thinking,e.contentBlockDelta?.delta?.thinking,e.delta?.reasoning_content,e.reasoning_content];for(let i of r)if(typeof i=="string"&&i.length>0)return i;let n=[e.text,e.outputText,e.completion,e.resultText,e.delta];for(let i of n)if(typeof i=="string"&&i.length>0)return i;let o=[e.delta?.text,e.delta?.output_text,e.delta?.content,e.contentBlockDelta?.delta?.text,e.contentBlockDelta?.delta?.output_text,e.contentBlockDelta?.delta?.content,e.content_block_delta?.delta?.text,e.content_block_delta?.delta?.output_text,e.content_block_delta?.delta?.content,e.message?.content,e.messageStop?.message?.content,e.message_stop?.message?.content,e.content];for(let i of o){let a=this.extractTextFromCandidate(i);if(a)return a}return null}extractTextFromCandidate(e){if(!e)return null;if(typeof e=="string")return e.length>0?e:null;if(Array.isArray(e)){let r=e.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){if(typeof n.text=="string")return n.text;if(typeof n.value=="string")return n.value;if(Array.isArray(n.content))return n.content.map(o=>typeof o?.text=="string"?o.text:"").join("")}return""}).join("");return r.length>0?r:null}if(typeof e=="object"){let r=e;if(typeof r.text=="string")return r.text.length>0?r.text:null;if(r.text&&typeof r.text=="object"){let n=this.extractTextFromCandidate(r.text);if(n)return n}if(typeof r.value=="string")return r.value.length>0?r.value:null;if(Array.isArray(r.content))return this.extractTextFromCandidate(r.content);if(r.delta){let n=this.extractTextFromCandidate(r.delta);if(n)return n}if(r.message&&typeof r.message=="object"){let n=this.extractTextFromCandidate(r.message);if(n)return n}}return null}extractUsage(e){if(!(!e||typeof e!="object")){if(e.usage&&typeof e.usage=="object")return e.usage;if(e.metrics&&typeof e.metrics=="object")return e.metrics;if(e["amazon-bedrock-invocationMetrics"]&&typeof e["amazon-bedrock-invocationMetrics"]=="object")return e["amazon-bedrock-invocationMetrics"];if(e.messageStop&&typeof e.messageStop=="object")return this.extractUsage(e.messageStop);if(e.message_stop&&typeof e.message_stop=="object")return this.extractUsage(e.message_stop)}}extractStopReason(e){if(!e||typeof e!="object")return;let r=e.stop_reason||e.stopReason||e.completionReason||e.completion_reason||e.reason||e.messageStop?.stopReason||e.message_stop?.stop_reason||(e.type==="message_stop"?e.reason:void 0);return typeof r=="string"?r:void 0}buildTerminalMetadataChunk(e,r){let n=r?this.normaliseUsageMetadata(r):void 0,o={provider:"amazon-bedrock"};e&&(o.stop_reason=e),r&&(o.usage=r);let i=new Er({content:"",response_metadata:o,usage_metadata:n});return new si({message:i,text:"",generationInfo:o})}normaliseUsageMetadata(e){let r=this.coerceNumber(e.inputTokens)??this.coerceNumber(e.input_tokens)??this.coerceNumber(e.inputTokenCount)??this.coerceNumber(e.promptTokens)??this.coerceNumber(e.prompt_tokens)??0,n=this.coerceNumber(e.outputTokens)??
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`)),i!==void 0&&(u.max_tokens=i),this.anthropicVersion&&(u.anthropic_version=this.anthropicVersion),this.enableThinking?(u.thinking={type:"enabled",budget_tokens:2048},u.temperature=1,F("[BedrockChatModel] Enabled thinking mode for Claude model with temperature=1")):a!==void 0&&(u.temperature=a),s!==void 0&&(u.top_p=s),u}normaliseMessageContent(e){let{content:r}=e;return typeof r=="string"?r:Array.isArray(r)?r.some(o=>typeof o=="object"&&o!==null&&(o.type==="image_url"||o.type==="image"))?r.map(o=>{if(typeof o=="string")return{type:"text",text:o};if(typeof o=="object"&&o!==null){if(o.type==="text"||o.type==="image_url"||o.type==="image")return o;if("text"in o&&typeof o.text=="string")return{type:"text",text:o.text};if("content"in o&&typeof o.content=="string")return{type:"text",text:o.content}}return null}).filter(o=>o!==null):r.map(o=>{if(typeof o=="string")return o;if(typeof o=="object"&&o!==null){if("text"in o&&typeof o.text=="string")return o.text;if("content"in o&&typeof o.content=="string")return o.content}return""}).join(""):typeof r=="object"&&r!==null&&"text"in r?r.text??"":""}extractText(e){return typeof e?.outputText=="string"?e.outputText:Array.isArray(e?.content)?e.content.map(r=>{if(!r)return"";if(typeof r=="string")return r;if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(r.text&&typeof r.text=="object"&&"text"in r.text)return r.text.text??""}return""}).join(""):typeof e?.completion=="string"?e.completion:typeof e?.resultText=="string"?e.resultText:""}}});function P4r(t){let e,r,n,o,i,a,s;return u(),{feed:l,reset:u};function u(){e=!0,r="",n=0,o=-1,i=void 0,a=void 0,s=""}function l(d){r=r?r+d:d,e&&mti(r)&&(r=r.slice(M4r.length)),e=!1;let f=r.length,p=0,m=!1;for(;p<f;){m&&(r[p]===`
2026-01-21 08:46:13 +08:00
`&&++p,m=!1);let h=-1,y=o,g;for(let b=n;h<0&&b<f;++b)g=r[b],g===":"&&y<0?y=b-p:g==="\r"?(m=!0,h=b-p):g===`
`&&(h=b-p);if(h<0){n=f-p,o=y;break}else n=0,o=-1;c(r,p,y,h),p+=h+1}p===f?r="":p>0&&(r=r.slice(p))}function c(d,f,p,m){if(m===0){s.length>0&&(t({type:"event",id:i,event:a||void 0,data:s.slice(0,-1)}),s="",i=void 0),a=void 0;return}let h=p<0,y=d.slice(f,f+(h?m:p)),g=0;h?g=m:d[f+p+1]===" "?g=p+2:g=p+1;let b=f+g,_=m-g,w=d.slice(b,b+_).toString();if(y==="data")s+=w?"".concat(w,`
`):`
2026-02-24 07:55:02 +08:00
`;else if(y==="event")a=w;else if(y==="id"&&!w.includes("\0"))i=w;else if(y==="retry"){let T=parseInt(w,10);Number.isNaN(T)||t({type:"reconnect-interval",value:T})}}}function mti(t){return M4r.every((e,r)=>t.charCodeAt(r)===e)}var M4r,R4r=v(()=>{M4r=[239,187,191]});function Rmt(t){return t instanceof eC||t instanceof Error&&t.name==="AuthCancelledError"}var eC,Imt=v(()=>{eC=class t extends Error{constructor(r="Authentication cancelled by user."){super(r);this.name="AuthCancelledError";Object.setPrototypeOf(this,t.prototype)}}});var Sle,I4r,hti,gti,yti,j4r,A4r,bti,_ti,N4r,vti,D4r,BU,KDe=v(()=>{Ye();vO();Sle=require("obsidian");R4r();Imt();I4r="Iv1.b507a08c87ecfe98",hti="https://github.com/login/device/code",gti="https://github.com/login/oauth/access_token",yti="https://api.github.com/copilot_internal/v2/token",j4r="https://api.githubcopilot.com",A4r=`${j4r}/chat/completions`,bti=`${j4r}/models`,_ti=60*1e3,N4r=60*60*1e3,vti=3,D4r={401:"Authentication failed - token may be expired",403:"Access denied - check your Copilot subscription",429:"Rate limited - please wait before retrying"},BU=class t{constructor(){this.abortController=null;this.refreshPromise=null;this.refreshAttempts=0;this.authGeneration=0}static getInstance(){return t.instance||(t.instance=new t),t.instance}getAuthState(){let e=te(),r=!!e.githubCopilotAccessToken,n=!!e.githubCopilotToken,o=e.githubCopilotTokenExpiresAt,a=!(typeof o=="number"&&o>0)||o<Date.now();return n&&!a||n&&r?{status:"authenticated"}:r?{status:"pending"}:{status:"idle"}}isAuthenticated(){return this.getAuthState().status==="authenticated"}async startDeviceCodeFlow(){let e=new URLSearchParams({client_id:I4r,scope:"read:user"}).toString(),r=await(0,Sle.requestUrl)({url:hti,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:e,throw:!1}),n=this.getRequestUrlJson(r);if(r.status!==200){let i=typeof n.error_description=="string"?n.error_description:typeof n.error=="string"?n.error:"";throw new Error(i?`Failed to get device code: ${i}`:`Failed to get device code: ${r.status}`)}if(typeof n.device_code!="string"||typeof n.user_code!="string"||typeof n.expires_in!="number")throw new Error("Invalid device code response from GitHub");let o=typeof n.verification_uri=="string"?n.verification_uri:typeof n.verification_uri_complete=="string"?n.verification_uri_complete:null;if(!o)throw new Error("Invalid device code response from GitHub: missing verification URI");return{deviceCode:n.device_code,userCode:n.user_code,verificationUri:o,expiresIn:n.expires_in,interval:typeof n.interval=="number"&&n.interval>0?n.interval:5}}async pollForAccessToken(e,r,n,o){let i=this.authGeneration;this.abortPolling();let a=new AbortController;this.abortController=a;let s=Date.now()+n*1e3,u=0;try{for(;Date.now()<s;){if(a.signal.aborted||this.authGeneration!==i)throw new eC;if(u++,o?.(u),await this.delay(r*1e3,a.signal),a.signal.aborted||this.authGeneration!==i)throw new eC;let l=new URLSearchParams({client_id:I4r,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}).toString(),c=await(0,Sle.requestUrl)({url:gti,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l,throw:!1});if(a.signal.aborted||this.authGeneration!==i)throw new eC;let d=this.getRequestUrlJson(c);if(c.status!==200){let f=typeof d.error_description=="string"?d.error_description:typeof d.error=="string"?d.error:`HTTP ${c.status}`;throw new Error(`Token request failed: ${f}`)}if(typeof d.access_token=="string"&&d.access_token){if(a.signal.aborted||this.authGeneration!==i)throw new eC;return F_({githubCopilotAccessToken:d.access_token}),d.access_token}if(d.error!=="authorization_pending"){if(d.error==="slow_down"){r+=5;continue}if(d.error==="device_code_expired"||d.error==="expired_token")throw new Error("Device code expired. Please restart authentication.");if(d.error==="access_denied")throw new Error("Authorization denied by user.");if(typeof d.error=="string"&&d.error)throw new Error(typeof d.error_description=="string"&&d.error_des
without CORS Error: `+zr(n)+`
with CORS Error: `+zr(o);throw new Error(i)}}}findModelByName(e){return te().activeModels.find(n=>n.name===e)}};bd.ANTHROPIC_THINKING_BUDGET_TOKENS=2048,bd.REASONING_MODEL_TEMPERATURE=1;tC=bd});var Dmt={};En(Dmt,{TieredLexicalRetriever:()=>uT});async function Cti(){try{if(!Amt){let e=await Promise.resolve().then(()=>(CX(),F4r));Amt=()=>e.default.getInstance()}return Amt().getChatModel()}catch{return null}}var Nmt,Amt,uT,xX=v(()=>{Xe();Ye();Bt();ND();f9();Nmt=require("obsidian");Oae();wH();Amt=null;uT=class extends Ux{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["tiered_lexical_retriever"];this.lastQueryExpansion=null;this.searchCore=new yPe(r,Cti),this.chunkManager=Sq(r)}getLastQueryExpansion(){return this.lastQueryExpansion}async getRelevantDocuments(r,n){try{let i=kS(r,this.app.vault).map(f=>f.basename),a=[...new Set([...this.options.salientTerms,...i])];te().debug&&F("TieredLexicalRetriever: Starting search",{query:r,salientTerms:a,maxK:this.options.maxK});let s=te(),u=await this.searchCore.retrieve(r,{maxResults:this.options.maxK,salientTerms:a,enableLexicalBoosts:s.enableLexicalBoosts,preExpandedQuery:this.options.preExpandedQuery}),l=u.results;this.lastQueryExpansion=u.queryExpansion;let c=await this.convertToDocuments(l),d=this.sortResults(c);return te().debug&&F("TieredLexicalRetriever: Search complete",{totalResults:d.length,searchResults:l.length}),d}catch(o){return Te("TieredLexicalRetriever: Error during search",o),[]}}async convertToDocuments(r){let n=[];for(let o of r)try{if(o.id.includes("#")){let[a]=o.id.split("#"),s=this.app.vault.getAbstractFileByPath(a);if(!s||!(s instanceof Nmt.TFile))continue;let u="",l=this.chunkManager;if(typeof l.getChunkText=="function"?u=await l.getChunkText(o.id):typeof l.getChunkTextSync=="function"&&(u=l.getChunkTextSync(o.id)||""),!u)continue;let c=this.app.metadataCache.getFileCache(s);n.push(new tl({pageContent:u,metadata:{path:a,chunkId:o.id,title:s.basename,mtime:s.stat.mtime,ctime:s.stat.ctime,tags:c?.tags?.map(d=>d.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"chunk-v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!0}}))}else{let a=this.app.vault.getAbstractFileByPath(o.id);if(!a||!(a instanceof Nmt.TFile))continue;let s=await this.app.vault.cachedRead(a);if(!s)continue;let u=this.app.metadataCache.getFileCache(a);n.push(new tl({pageContent:s,metadata:{path:o.id,title:a.basename,mtime:a.stat.mtime,ctime:a.stat.ctime,tags:u?.tags?.map(l=>l.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!1}}))}}catch(i){Te(`TieredLexicalRetriever: Failed to convert result ${o.id}`,i)}return F(`TieredLexicalRetriever: Converted ${n.length} results to Documents`),n}sortResults(r){return r.sort((n,o)=>{let i=n.metadata.score||0,s=(o.metadata.score||0)-i;if(Math.abs(s)>.01)return s;if(n.metadata.isChunk&&o.metadata.isChunk&&n.metadata.path===o.metadata.path){let u=parseInt(n.metadata.chunkId?.split("#")[1]||"0"),l=parseInt(o.metadata.chunkId?.split("#")[1]||"0");return u-l}return s})}}});var k4r={};En(k4r,{MergedSemanticRetriever:()=>K3});var zU,K3,jmt=v(()=>{_Pe();wH();xX();ND();f9();zU=class zU extends Ux{constructor(r,n,o){super();this.app=r;this.options=n;this.lc_namespace=["merged_semantic_retriever"];this.originalMaxK=Math.max(1,n.maxK),this.returnAll=!!n.returnAll;let i=this.returnAll?ec:Math.min(this.originalMaxK*2,ec),a={...n,maxK:i,returnAll:this.returnAll};this.lexicalRetriever=new uT(r,a);let s=this.returnAll?ec:Math.min(this.originalMaxK*2,ec);this.semanticRetriever=o||new $ae({minSimilarityScore:n.minSimilarityScore??.1,maxK:s,salientTerms:n.salientTerms,timeRange:n.timeRange,textWeight:n.textWeight,returnAll:this.returnAll,useRerankerThreshold:n.useRerankerThreshold})}async getRelevantDocuments(r){let[n,o]=await Promise.all([this.lexicalRetriever.getRelevantDocuments(r),this.semanticRetriever.getRelevantDocuments(r)]),i=new Map;for(let u of n)this.insertResult(i,u,"lexic
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`);return{...o,[this.documentVariableName]:a}}async _call(r,n){return await this.llmChain.call(this._prepInputs(r),n?.getChild("combine_documents"))}_chainType(){return"stuff_documents_chain"}static async deserialize(r){if(!r.llm_chain)throw new Error("Missing llm_chain");return new d3r({llmChain:await ag.deserialize(r.llm_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize()}}},f3r=class p3r extends hb{constructor(r){super(r);x(this,"llmChain");x(this,"inputKey","input_documents");x(this,"documentVariableName","context");x(this,"returnIntermediateSteps",!1);x(this,"maxTokens",3e3);x(this,"maxIterations",10);x(this,"ensureMapStep",!1);x(this,"combineDocumentChain");this.llmChain=r.llmChain,this.combineDocumentChain=r.combineDocumentChain,this.documentVariableName=r.documentVariableName??this.documentVariableName,this.ensureMapStep=r.ensureMapStep??this.ensureMapStep,this.inputKey=r.inputKey??this.inputKey,this.maxTokens=r.maxTokens??this.maxTokens,this.maxIterations=r.maxIterations??this.maxIterations,this.returnIntermediateSteps=r.returnIntermediateSteps??!1}static lc_name(){return"MapReduceDocumentsChain"}get inputKeys(){return[this.inputKey,...this.combineDocumentChain.inputKeys]}get outputKeys(){return this.combineDocumentChain.outputKeys}async _call(r,n){if(!(this.inputKey in r))throw new Error(`Document key ${this.inputKey} not found.`);let{[this.inputKey]:o,...i}=r,a=o,s=[];for(let c=0;c<this.maxIterations;c+=1){let d=a.map(h=>({[this.documentVariableName]:h.pageContent,...i}));if(c!==0||!this.ensureMapStep){let h=await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({[this.combineDocumentChain.inputKey]:a,...i}));if(await this.combineDocumentChain.llmChain._getNumTokens(h)<this.maxTokens)break}let p=await this.llmChain.apply(d,n?Array.from({length:d.length},(h,y)=>n.getChild(`map_${y+1}`)):void 0),{outputKey:m}=this.llmChain;this.returnIntermediateSteps&&(s=s.concat(p.map(h=>h[m]))),a=p.map(h=>({pageContent:h[m],metadata:{}}))}let u={[this.combineDocumentChain.inputKey]:a,...i},l=await this.combineDocumentChain.call(u,n?.getChild("combine_documents"));return this.returnIntermediateSteps?{...l,intermediateSteps:s}:l}_chainType(){return"map_reduce_documents_chain"}static async deserialize(r){if(!r.llm_chain)throw new Error("Missing llm_chain");if(!r.combine_document_chain)throw new Error("Missing combine_document_chain");return new p3r({llmChain:await ag.deserialize(r.llm_chain),combineDocumentChain:await Zje.deserialize(r.combine_document_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),combine_document_chain:this.combineDocumentChain.serialize()}}},m3r=class h3r extends hb{constructor(r){super(r);x(this,"llmChain");x(this,"inputKey","input_documents");x(this,"outputKey","output_text");x(this,"documentVariableName","context");x(this,"initialResponseName","existing_answer");x(this,"refineLLMChain");x(this,"documentPrompt",this.defaultDocumentPrompt);this.llmChain=r.llmChain,this.refineLLMChain=r.refineLLMChain,this.documentVariableName=r.documentVariableName??this.documentVariableName,this.inputKey=r.inputKey??this.inputKey,this.outputKey=r.outputKey??this.outputKey,this.documentPrompt=r.documentPrompt??this.documentPrompt,this.initialResponseName=r.initialResponseName??this.initialResponseName}static lc_name(){return"RefineDocumentsChain"}get defaultDocumentPrompt(){return new mu({inputVariables:["page_content"],template:"{page_content}"})}get inputKeys(){return[...new Set([this.inputKey,...this.llmChain.inputKeys,...this.refineLLMChain.inputKeys])].filter(r=>r!==this.documentVariableName&&r!==this.initialResponseName)}get outputKeys(){return[this.outputKey]}async _constructInitialInputs(r,n){let o={page_content:r.pageContent,...r.metadata},i={};return this.documentPrompt.inputVariables.forEach(u=>{i[u]=o[u]}),{...{[this.documentVariableName]:await this.documentPrompt.format({...i})},...n}}async _constructRefineInputs(r,n){let o={page_content:r.pageContent,...r.metadata},i={};this.documentPrompt.inputVa
2026-01-05 13:03:55 +08:00
{context}
Question: {question}
2026-02-24 07:55:02 +08:00
Helpful Answer:`,inputVariables:["context","question"]}),Kii=`Use the following pieces of context to answer the users question.
2026-01-05 13:03:55 +08:00
If you don't know the answer, just say that you don't know, don't try to make up an answer.
----------------
2026-02-24 07:55:02 +08:00
{context}`,Gii=[LS.fromTemplate(Kii),$_.fromTemplate("{question}")],Xii=Ah.fromMessages(Gii),T3r=new iZ(Jii,[[aZ,Xii]])});var E3r=v(()=>{FS();e$e()});var P3r=v(()=>{FS();e$e()});function M3r(t,e={}){let{prompt:r=T3r.getPrompt(t),verbose:n}=e,o=new ag({prompt:r,llm:t,verbose:n});return new Zje({llmChain:o,verbose:n})}var R3r=v(()=>{cW();Xce();O3r();E3r();P3r()});var A3r={};En(A3r,{VectorDBQAChain:()=>Zii});var Zii,N3r=v(()=>{nZ();R3r();Zii=class I3r extends hb{constructor(r){super(r);x(this,"k",4);x(this,"inputKey","query");x(this,"vectorstore");x(this,"combineDocumentsChain");x(this,"returnSourceDocuments",!1);this.vectorstore=r.vectorstore,this.combineDocumentsChain=r.combineDocumentsChain,this.inputKey=r.inputKey??this.inputKey,this.k=r.k??this.k,this.returnSourceDocuments=r.returnSourceDocuments??this.returnSourceDocuments}static lc_name(){return"VectorDBQAChain"}get inputKeys(){return[this.inputKey]}get outputKeys(){return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments?["sourceDocuments"]:[])}async _call(r,n){if(!(this.inputKey in r))throw new Error(`Question key ${this.inputKey} not found.`);let o=r[this.inputKey],i=await this.vectorstore.similaritySearch(o,this.k,r.filter,n?.getChild("vectorstore")),a={question:o,input_documents:i},s=await this.combineDocumentsChain.call(a,n?.getChild("combine_documents"));return this.returnSourceDocuments?{...s,sourceDocuments:i}:s}_chainType(){return"vector_db_qa"}static async deserialize(r,n){if(!("vectorstore"in n))throw new Error("Need to pass in a vectorstore to deserialize VectorDBQAChain");let{vectorstore:o}=n;if(!r.combine_documents_chain)throw new Error("VectorDBQAChain must have combine_documents_chain in serialized data");return new I3r({combineDocumentsChain:await hb.deserialize(r.combine_documents_chain),k:r.k,vectorstore:o})}serialize(){return{_type:this._chainType(),combine_documents_chain:this.combineDocumentsChain.serialize(),k:this.k}}static fromLLM(r,n,o){let i=M3r(r);return new this({vectorstore:n,combineDocumentsChain:i,...o})}}});var D3r,j3r,Yii,$3r,L3r=v(()=>{FS();D3r=`You are given the below API Documentation:
2026-01-05 13:03:55 +08:00
{api_docs}
Using this documentation, generate the full API url to call for answering the user question.
You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.
Question:{question}
2026-02-24 07:55:02 +08:00
API url:`,j3r=new mu({inputVariables:["api_docs","question"],template:D3r}),Yii=`${D3r} {api_url}
2026-01-05 13:03:55 +08:00
Here is the response from the API:
{api_response}
Summarize this response to answer the original question.
2026-02-24 07:55:02 +08:00
Summary:`,$3r=new mu({inputVariables:["api_docs","question","api_url","api_response"],template:Yii})});var k3r={};En(k3r,{APIChain:()=>Qii});var Qii,q3r=v(()=>{nZ();cW();L3r();Qii=class F3r extends hb{constructor(r){super(r);x(this,"apiAnswerChain");x(this,"apiRequestChain");x(this,"apiDocs");x(this,"headers",{});x(this,"inputKey","question");x(this,"outputKey","output");this.apiRequestChain=r.apiRequestChain,this.apiAnswerChain=r.apiAnswerChain,this.apiDocs=r.apiDocs,this.inputKey=r.inputKey??this.inputKey,this.outputKey=r.outputKey??this.outputKey,this.headers=r.headers??this.headers}get inputKeys(){return[this.inputKey]}get outputKeys(){return[this.outputKey]}async _call(r,n){let o=r[this.inputKey],i=await this.apiRequestChain.predict({question:o,api_docs:this.apiDocs},n?.getChild("request")),s=await(await fetch(i,{headers:this.headers})).text(),u=await this.apiAnswerChain.predict({question:o,api_docs:this.apiDocs,api_url:i,api_response:s},n?.getChild("response"));return{[this.outputKey]:u}}_chainType(){return"api_chain"}static async deserialize(r){let{api_request_chain:n,api_answer_chain:o,api_docs:i}=r;if(!n)throw new Error("LLMChain must have api_request_chain");if(!o)throw new Error("LLMChain must have api_answer_chain");if(!i)throw new Error("LLMChain must have api_docs");return new F3r({apiAnswerChain:await ag.deserialize(o),apiRequestChain:await ag.deserialize(n),apiDocs:i})}serialize(){return{_type:this._chainType(),api_answer_chain:this.apiAnswerChain.serialize(),api_request_chain:this.apiRequestChain.serialize(),api_docs:this.apiDocs}}static fromLLMAndAPIDocs(r,n,o={}){let{apiUrlPrompt:i=j3r,apiResponsePrompt:a=$3r}=o,s=new ag({prompt:i,llm:r}),u=new ag({prompt:a,llm:r});return new this({apiAnswerChain:u,apiRequestChain:s,apiDocs:n,...o})}}});var hb,nZ=v(()=>{sw();Nw();Ed();WL();hb=class extends k8{get lc_namespace(){return["langchain","chains",this._chainType()]}constructor(t,e,r){if(arguments.length===1&&typeof t=="object"&&!("saveContext"in t)){let{memory:n,callbackManager:o,...i}=t;super({...i,callbacks:o??i.callbacks}),this.memory=n}else super({verbose:e,callbacks:r}),this.memory=t}_selectMemoryInputs(t){let e={...t};return"signal"in e&&delete e.signal,"timeout"in e&&delete e.timeout,e}async invoke(t,e){let r=ai(e),n=await this._formatValues(t),i=await(await mc.configure(r?.callbacks,this.callbacks,r?.tags,this.tags,r?.metadata,this.metadata,{verbose:this.verbose}))?.handleChainStart(this.toJSON(),n,void 0,void 0,void 0,void 0,r?.runName),a;try{if(n.signal){let s;a=await Promise.race([this._call(n,i,r),new Promise((u,l)=>{s=()=>{l(new Error("AbortError"))},n.signal?.addEventListener("abort",s)})]).finally(()=>{n.signal&&s&&n.signal.removeEventListener("abort",s)})}else a=await this._call(n,i,r)}catch(s){throw await i?.handleChainError(s),s}return this.memory!=null&&await this.memory.saveContext(this._selectMemoryInputs(t),a),await i?.handleChainEnd(a),Object.defineProperty(a,JN,{value:i?{runId:i?.runId}:void 0,configurable:!0}),a}_validateOutputs(t){let e=this.outputKeys.filter(r=>!(r in t));if(e.length)throw new Error(`Missing output keys: ${e.join(", ")} from chain ${this._chainType()}`)}async prepOutputs(t,e,r=!1){return this._validateOutputs(e),this.memory&&await this.memory.saveContext(t,e),r?e:{...t,...e}}serialize(){throw new Error("Method not implemented.")}async run(t,e){let r=this.inputKeys.filter(s=>!this.memory?.memoryKeys.includes(s));if(!(r.length<=1))throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `);let o=r.length?{[r[0]]:t}:{},i=await this.call(o,e),a=Object.keys(i);if(a.length===1)return i[a[0]];throw new Error("return values have multiple keys, `run` only supported when one key currently")}async _formatValues(t){let e={...t};if(e.timeout&&!e.signal&&(e.signal=AbortSignal.timeout(e.timeout),delete e.timeout),this.memory!=null){let r=await this.memory.loadMemoryVariables(this._selectMemoryInputs(t));for(let[n,o]of Object.entries(r))e[n]=o}return e}async call(t,e,r){let n={tags:r,...HN(e)};return this.invoke(t,n)}async apply(t,e){return Promise.all(
`;)e--;return t.substring(0,e)}function nGr(t){return rGr(tGr(t))}function bbt(t){return _bt(t,Ydi)}function iGr(t){return _bt(t,oGr)}function Qdi(t){return sGr(t,oGr)}function efi(t){return _bt(t,aGr)}function tfi(t){return sGr(t,aGr)}function _bt(t,e){return e.indexOf(t.nodeName)>=0}function sGr(t,e){return t.getElementsByTagName&&e.some(function(r){return t.getElementsByTagName(r).length})}function NLe(t){return t?t.replace(/(\n+\s*)+/g,`
`):""}function uGr(t){this.options=t,this._keep=[],this._remove=[],this.blankRule={replacement:t.blankReplacement},this.keepReplacement=t.keepReplacement,this.defaultRule={replacement:t.defaultReplacement},this.array=[];for(var e in t.rules)this.array.push(t.rules[e])}function mbt(t,e,r){for(var n=0;n<t.length;n++){var o=t[n];if(rfi(o,e,r))return o}}function rfi(t,e,r){var n=t.filter;if(typeof n=="string"){if(n===e.nodeName.toLowerCase())return!0}else if(Array.isArray(n)){if(n.indexOf(e.nodeName.toLowerCase())>-1)return!0}else if(typeof n=="function"){if(n.call(t,e,r))return!0}else throw new TypeError("`filter` needs to be a string, array, or function")}function nfi(t){var e=t.element,r=t.isBlock,n=t.isVoid,o=t.isPre||function(d){return d.nodeName==="PRE"};if(!(!e.firstChild||o(e))){for(var i=null,a=!1,s=null,u=Q8r(s,e,o);u!==e;){if(u.nodeType===3||u.nodeType===4){var l=u.data.replace(/[ \r\n\t]+/g," ");if((!i||/ $/.test(i.data))&&!a&&l[0]===" "&&(l=l.substr(1)),!l){u=hbt(u);continue}u.data=l,i=u}else if(u.nodeType===1)r(u)||u.nodeName==="BR"?(i&&(i.data=i.data.replace(/ $/,"")),i=null,a=!1):n(u)||o(u)?(i=null,a=!0):i&&(a=!1);else{u=hbt(u);continue}var c=Q8r(s,u,o);s=u,u=c}i&&(i.data=i.data.replace(/ $/,""),i.data||hbt(i))}}function hbt(t){var e=t.nextSibling||t.parentNode;return t.parentNode.removeChild(t),e}function Q8r(t,e,r){return t&&t.parentNode===e||r(e)?e.nextSibling||e.parentNode:e.firstChild||e.nextSibling||e.parentNode}function ofi(){var t=vbt.DOMParser,e=!1;try{new t().parseFromString("","text/html")&&(e=!0)}catch{}return e}function ifi(){var t=function(){};return afi()?t.prototype.parseFromString=function(e){var r=new window.ActiveXObject("htmlfile");return r.designMode="on",r.open(),r.write(e),r.close(),r}:t.prototype.parseFromString=function(e){var r=document.implementation.createHTMLDocument("");return r.open(),r.write(e),r.close(),r},t}function afi(){var t=!1;try{document.implementation.createHTMLDocument("").open()}catch{vbt.ActiveXObject&&(t=!0)}return t}function ufi(t,e){var r;if(typeof t=="string"){var n=lfi().parseFromString('<x-turndown id="turndown-root">'+t+"</x-turndown>","text/html");r=n.getElementById("turndown-root")}else r=t.cloneNode(!0);return nfi({element:r,isBlock:bbt,isVoid:iGr,isPre:e.preformattedCode?cfi:null}),r}function lfi(){return gbt=gbt||new sfi,gbt}function cfi(t){return t.nodeName==="PRE"||t.nodeName==="CODE"}function dfi(t,e){return t.isBlock=bbt(t),t.isCode=t.nodeName==="CODE"||t.parentNode.isCode,t.isBlank=ffi(t),t.flankingWhitespace=pfi(t,e),t}function ffi(t){return!iGr(t)&&!efi(t)&&/^\s*$/i.test(t.textContent)&&!Qdi(t)&&!tfi(t)}function pfi(t,e){if(t.isBlock||e.preformattedCode&&t.isCode)return{leading:"",trailing:""};var r=mfi(t.textContent);return r.leadingAscii&&eGr("left",t,e)&&(r.leading=r.leadingNonAscii),r.trailingAscii&&eGr("right",t,e)&&(r.trailing=r.trailingNonAscii),{leading:r.leading,trailing:r.trailing}}function mfi(t){var e=t.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:e[1],leadingAscii:e[2],leadingNonAscii:e[3],trailing:e[4],trailingNonAscii:e[5],trailingAscii:e[6]}}function eGr(t,e,r){var n,o,i;return t==="left"?(n=e.previousSibling,o=/ $/):(n=e.nextSibling,o=/^ /),n&&(n.nodeType===3?i=o.test(n.nodeValue):r.preformattedCode&&n.nodeName==="CODE"?i=!1:n.nodeType===1&&!bbt(n)&&(i=o.test(n.textContent))),i}function DLe(t){if(!(this instanceof DLe))return new DLe(t);var e={rules:bb,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(r,n){return n.isBlock?`
2026-01-21 08:46:13 +08:00
`:""},keepReplacement:function(r,n){return n.isBlock?`
`+n.outerHTML+`
`:n.outerHTML},defaultReplacement:function(r,n){return n.isBlock?`
`+r+`
2026-02-24 07:55:02 +08:00
`:r}};this.options=Zdi({},e,t),this.rules=new uGr(this.options)}function lGr(t){var e=this;return hfi.call(t.childNodes,function(r,n){n=new dfi(n,e.options);var o="";return n.nodeType===3?o=n.isCode?n.nodeValue:e.escape(n.nodeValue):n.nodeType===1&&(o=bfi.call(e,n)),cGr(r,o)},"")}function yfi(t){var e=this;return this.rules.forEach(function(r){typeof r.append=="function"&&(t=cGr(t,r.append(e.options)))}),t.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function bfi(t){var e=this.rules.forNode(t),r=lGr.call(this,t),n=t.flankingWhitespace;return(n.leading||n.trailing)&&(r=r.trim()),n.leading+e.replacement(r,t,this.options)+n.trailing}function cGr(t,e){var r=rGr(t),n=tGr(e),o=Math.max(t.length-r.length,e.length-n.length),i=`
2026-01-21 08:46:13 +08:00
2026-02-24 07:55:02 +08:00
`.substring(0,o);return r+i+n}function _fi(t){return t!=null&&(typeof t=="string"||t.nodeType&&(t.nodeType===1||t.nodeType===9||t.nodeType===11))}var Ydi,oGr,aGr,bb,vbt,sfi,gbt,hfi,gfi,dGr,fGr=v(()=>{Ydi=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];oGr=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];aGr=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];bb={};bb.paragraph={filter:"p",replacement:function(t){return`
2026-01-21 08:46:13 +08:00
`+t+`
2026-02-24 07:55:02 +08:00
`}};bb.lineBreak={filter:"br",replacement:function(t,e,r){return r.br+`
`}};bb.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(t,e,r){var n=Number(e.nodeName.charAt(1));if(r.headingStyle==="setext"&&n<3){var o=ybt(n===1?"=":"-",t.length);return`
2026-01-21 08:46:13 +08:00
`+t+`
`+o+`
`}else return`
2026-02-24 07:55:02 +08:00
`+ybt("#",n)+" "+t+`
2026-01-21 08:46:13 +08:00
2026-02-24 07:55:02 +08:00
`}};bb.blockquote={filter:"blockquote",replacement:function(t){return t=nGr(t).replace(/^/gm,"> "),`
2026-01-21 08:46:13 +08:00
`+t+`
2026-02-24 07:55:02 +08:00
`}};bb.list={filter:["ul","ol"],replacement:function(t,e){var r=e.parentNode;return r.nodeName==="LI"&&r.lastElementChild===e?`
2026-01-21 08:46:13 +08:00
`+t:`
`+t+`
2026-02-24 07:55:02 +08:00
`}};bb.listItem={filter:"li",replacement:function(t,e,r){var n=r.bulletListMarker+" ",o=e.parentNode;if(o.nodeName==="OL"){var i=o.getAttribute("start"),a=Array.prototype.indexOf.call(o.children,e);n=(i?Number(i)+a:a+1)+". "}var s=/\n$/.test(t);return t=nGr(t)+(s?`
2026-01-21 08:46:13 +08:00
`:""),t=t.replace(/\n/gm,`
`+" ".repeat(n.length)),n+t+(e.nextSibling?`
2026-02-24 07:55:02 +08:00
`:"")}};bb.indentedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="indented"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,r){return`
2026-01-21 08:46:13 +08:00
`+e.firstChild.textContent.replace(/\n/g,`
`)+`
2026-02-24 07:55:02 +08:00
`}};bb.fencedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="fenced"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,r){for(var n=e.firstChild.getAttribute("class")||"",o=(n.match(/language-(\S+)/)||[null,""])[1],i=e.firstChild.textContent,a=r.fence.charAt(0),s=3,u=new RegExp("^"+a+"{3,}","gm"),l;l=u.exec(i);)l[0].length>=s&&(s=l[0].length+1);var c=ybt(a,s);return`
2026-01-21 08:46:13 +08:00
`+c+o+`
`+i.replace(/\n$/,"")+`
`+c+`
2026-02-24 07:55:02 +08:00
`}};bb.horizontalRule={filter:"hr",replacement:function(t,e,r){return`
2026-01-21 08:46:13 +08:00
`+r.hr+`
2026-02-24 07:55:02 +08:00
`}};bb.inlineLink={filter:function(t,e){return e.linkStyle==="inlined"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e){var r=e.getAttribute("href");r&&(r=r.replace(/([()])/g,"\\$1"));var n=NLe(e.getAttribute("title"));return n&&(n=' "'+n.replace(/"/g,'\\"')+'"'),"["+t+"]("+r+n+")"}};bb.referenceLink={filter:function(t,e){return e.linkStyle==="referenced"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e,r){var n=e.getAttribute("href"),o=NLe(e.getAttribute("title"));o&&(o=' "'+o+'"');var i,a;switch(r.linkReferenceStyle){case"collapsed":i="["+t+"][]",a="["+t+"]: "+n+o;break;case"shortcut":i="["+t+"]",a="["+t+"]: "+n+o;break;default:var s=this.references.length+1;i="["+t+"]["+s+"]",a="["+s+"]: "+n+o}return this.references.push(a),i},references:[],append:function(t){var e="";return this.references.length&&(e=`
2026-01-21 08:46:13 +08:00
`+this.references.join(`
`)+`
2026-02-24 07:55:02 +08:00
`,this.references=[]),e}};bb.emphasis={filter:["em","i"],replacement:function(t,e,r){return t.trim()?r.emDelimiter+t+r.emDelimiter:""}};bb.strong={filter:["strong","b"],replacement:function(t,e,r){return t.trim()?r.strongDelimiter+t+r.strongDelimiter:""}};bb.code={filter:function(t){var e=t.previousSibling||t.nextSibling,r=t.parentNode.nodeName==="PRE"&&!e;return t.nodeName==="CODE"&&!r},replacement:function(t){if(!t)return"";t=t.replace(/\r?\n|\r/g," ");for(var e=/^`|^ .*?[^ ].* $|`$/.test(t)?" ":"",r="`",n=t.match(/`+/gm)||[];n.indexOf(r)!==-1;)r=r+"`";return r+e+t+e+r}};bb.image={filter:"img",replacement:function(t,e){var r=NLe(e.getAttribute("alt")),n=e.getAttribute("src")||"",o=NLe(e.getAttribute("title")),i=o?' "'+o+'"':"";return n?"!["+r+"]("+n+i+")":""}};uGr.prototype={add:function(t,e){this.array.unshift(e)},keep:function(t){this._keep.unshift({filter:t,replacement:this.keepReplacement})},remove:function(t){this._remove.unshift({filter:t,replacement:function(){return""}})},forNode:function(t){if(t.isBlank)return this.blankRule;var e;return(e=mbt(this.array,t,this.options))||(e=mbt(this._keep,t,this.options))||(e=mbt(this._remove,t,this.options))?e:this.defaultRule},forEach:function(t){for(var e=0;e<this.array.length;e++)t(this.array[e],e)}};vbt=typeof window<"u"?window:{};sfi=ofi()?vbt.DOMParser:ifi();hfi=Array.prototype.reduce,gfi=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];DLe.prototype={turndown:function(t){if(!_fi(t))throw new TypeError(t+" is not a string, or an element/document/fragment node.");if(t==="")return"";var e=lGr.call(this,new ufi(t,this.options));return yfi.call(this,e)},use:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)this.use(t[e]);else if(typeof t=="function")t(this);else throw new TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(t,e){return this.rules.add(t,e),this},keep:function(t){return this.rules.keep(t),this},remove:function(t){return this.rules.remove(t),this},escape:function(t){return gfi.reduce(function(e,r){return e.replace(r[0],r[1])},t)}};dGr=DLe});function $Z(t){return typeof t=="object"&&t!==null}function LZ(t){if(typeof t=="string")return t;if(t==null)return"";try{return String(t)}catch{return""}}function gGr(t){return t instanceof Error?t.message:LZ(t)}async function vfi(t){await new Promise(e=>setTimeout(e,t))}async function yGr(t,e,r,n){let o=Date.now();for(;;){if(t())return;if(Date.now()-o>=e)throw new iS(`${n} timed out after ${e}ms`);await vfi(r)}}function pGr(t,e){let r=(t??"").trim();if(!r)return"";if(!e)return r;try{return new URL(r,e).href}catch{return r}}function mGr(t){let e=(t??"").trim();return e?/[\s)]/.test(e)?`<${e}>`:e:""}function wfi(t){let e=new dGr({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined"});return e.remove(["script","style","noscript"]),e.addRule("webviewer-link",{filter:"a",replacement:(r,n)=>{let o=n,i=o.getAttribute("href")??"",a=mGr(pGr(i,t)),s=r?.trim()||o.textContent||a;return a?`[${s}](${a})`:s}}),e.addRule("webviewer-image",{filter:"img",replacement:(r,n)=>{let o=n,i=o.getAttribute("alt")??"",a=o.getAttribute("src")??"",s=mGr(pGr(a,t));return s?`![${i}](${s})`:""}}),e}function wbt(t,e){if(!t.trim())return"";let r=wfi(e),i=new DOMParser().parseFromString(`<div>${t}</div>`,"text/html").body.firstElementChild;return i?r.turndown(i).replace(/\n{3,}/g,`
2026-01-21 08:46:13 +08:00
2026-02-24 07:55:02 +08:00
`).trim():""}function Sbt(t){let e=t.commands;return!e||!$Z(e)||typeof e.executeCommandById!="function"?null:e}function bGr(t,e){let r=Sbt(t);if(!r)return!1;if(r.commands){if(r.commands instanceof Map)return r.commands.has(e);if(typeof r.commands=="object")return e in r.commands}return typeof r.listCommands=="function"?r.listCommands().some(o=>o.id===e):!1}function _Gr(t,e){return t.workspace.getLeavesOfType(NW).includes(e)}function hGr(t){if(!$Z(t)||t.enabled!==!0)return null;let e=t.instance;if(!e||!$Z(e))return null;let r=e;return typeof r.openUrl=="function"||typeof r.handleOpenUrl=="function"?r:null}function vGr(t,e){let r=t.internalPlugins;if(!r||!$Z(r))return null;let n=r.plugins;if(!n)return null;let o=n instanceof Map?n.get(NW):$Z(n)?n[NW]:null;if(o){let a=hGr(o);if(a)return a}let i;if(n instanceof Map)i=Array.from(n.values());else if($Z(n))i=Object.values(n);else return e&&e(),null;for(let a of i){let s=hGr(a);if(s)return s}return null}var jLe=v(()=>{fGr();jZ()});function FZ(t){return{url:typeof t.view?.url=="string"?t.view.url:"",title:typeof t.view?.title=="string"?t.view.title:"",faviconUrl:typeof t.view?.faviconUrl=="string"?t.view.faviconUrl:"",mode:t.view?.mode==="reader"?"reader":"webview"}}async function wGr(t,e={}){let{signal:r}=e;if(r?.aborted)throw new PB("Operation was aborted");try{let n=Promise.resolve(t.view.getReaderModeContent());if(!r){let i=await n;return typeof i?.md=="string"?i.md:""}let o=await new Promise((i,a)=>{let s=()=>{a(new PB("Operation was aborted"))};r.addEventListener("abort",s,{once:!0}),n.then(u=>{r.removeEventListener("abort",s),i(u)}).catch(u=>{r.removeEventListener("abort",s),a(u)})});return typeof o?.md=="string"?o.md:""}catch(n){throw n instanceof PB||ne("Failed to get reader mode content:",n),n}}async function $Le(t,e=!0){let r=DZ(t),n='(() => { try { return window.getSelection?.()?.toString?.() ?? ""; } catch { return ""; } })()';try{let o=await r.executeJavaScript(n),i=LZ(o);return e?i.trim():i}catch(o){throw ne("Failed to get selected text:",o),o}}async function LLe(t){let e=DZ(t),r="";try{r=typeof e.getURL=="function"?e.getURL():""}catch{r=t.view?.url??""}let n=`(() => {
2026-01-21 08:46:13 +08:00
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return "";
const div = document.createElement("div");
for (let i = 0; i < sel.rangeCount; i++) div.appendChild(sel.getRangeAt(i).cloneContents());
return div.innerHTML;
2026-02-24 07:55:02 +08:00
})()`,o="";try{let i=await e.executeJavaScript(n);o=LZ(i)}catch(i){throw ne("Failed to get selection HTML:",i),i}try{return wbt(o,r)}catch(i){throw ne("Failed to convert HTML to Markdown:",i),i}}async function SGr(t){let e=DZ(t),r="";try{r=typeof e.getURL=="function"?e.getURL():""}catch{r=t.view?.url??""}let n=`(() => {
2026-01-21 08:46:13 +08:00
const clone = document.body.cloneNode(true);
clone.querySelectorAll('script, style, noscript').forEach(el => el.remove());
return clone.innerHTML;
2026-02-24 07:55:02 +08:00
})()`,o="";try{let i=await e.executeJavaScript(n);o=LZ(i)}catch(i){throw ne("Failed to get page HTML:",i),i}try{return wbt(o,r)}catch(i){throw ne("Failed to convert page HTML to Markdown:",i),i}}async function CGr(t,e=!0){let r=DZ(t),n=e?'(() => { try { return document.documentElement?.outerHTML ?? ""; } catch { return ""; } })()':'(() => { try { return document.body?.outerHTML ?? ""; } catch { return ""; } })()';try{let o=await r.executeJavaScript(n);return LZ(o)}catch(o){throw ne("Failed to get HTML:",o),o}}function FLe(t){try{let e=new URL(t),r=e.hostname.replace(/^www\./,"").replace(/^m\./,"");return r==="youtube.com"&&e.pathname==="/watch"?e.searchParams.get("v"):r==="youtu.be"&&e.pathname.length>1?e.pathname.slice(1).split("/")[0]:(r==="youtube.com"&&e.pathname.startsWith("/shorts/")||r==="youtube.com"&&e.pathname.startsWith("/embed/"))&&e.pathname.split("/")[2]||null}catch{return null}}function xGr(t){return FLe(t)!==null}function Sfi(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.videoId=="string"&&typeof e.title=="string"&&typeof e.channel=="string"&&(e.description===void 0||typeof e.description=="string")&&(e.uploadDate===void 0||typeof e.uploadDate=="string")&&(e.duration===void 0||typeof e.duration=="string")&&(e.genre===void 0||typeof e.genre=="string")&&Array.isArray(e.transcript)&&e.transcript.every(r=>typeof r=="object"&&r!==null&&typeof r.timestamp=="string"&&typeof r.text=="string")}async function TGr(t,e={}){let r=DZ(t),{timeoutMs:n=1e4}=e,o=Math.ceil(n/500),i="";try{i=typeof r.getURL=="function"?r.getURL():""}catch{i=""}i||(i=t.view?.url??"");let a=FLe(i);if(!a)throw new Error("Not a YouTube video page");let s=`(async () => {
2026-01-21 08:46:13 +08:00
const videoId = ${JSON.stringify(a)};
// =========================================================================
// Step 1: Extract video metadata from JSON-LD (structured data)
// JSON-LD is more reliable than DOM selectors as it's machine-readable
// =========================================================================
let title = '';
let channel = '';
let description = '';
let uploadDate = '';
let duration = '';
let genre = '';
// Helper to extract fields from a VideoObject schema
const extractVideoObject = (data) => {
if (!data || data['@type'] !== 'VideoObject') return;
if (!title && data.name && typeof data.name === 'string') {
title = data.name;
}
if (!description && data.description && typeof data.description === 'string') {
description = data.description;
}
if (!uploadDate && data.uploadDate && typeof data.uploadDate === 'string') {
uploadDate = data.uploadDate;
}
// JSON-LD duration is ISO 8601 format (e.g., "PT12M34S"), convert to readable format
if (!duration && data.duration && typeof data.duration === 'string') {
const match = data.duration.match(/PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?/);
if (match) {
const h = match[1] ? match[1] + ':' : '';
const m = match[2] || '0';
const s = match[3] || '0';
duration = h + (h ? m.padStart(2, '0') : m) + ':' + s.padStart(2, '0');
}
}
if (!genre && data.genre) {
genre = Array.isArray(data.genre) ? data.genre.join(', ') : String(data.genre);
}
// author can be string, object {name}, or array [{name}]
if (!channel && data.author) {
const author = data.author;
if (typeof author === 'string') {
channel = author;
} else if (Array.isArray(author) && author[0]?.name) {
channel = String(author[0].name);
} else if (author?.name) {
channel = String(author.name);
}
}
};
// Parse all JSON-LD scripts, handling various formats (@graph, array, single object)
const ldJsonEls = document.querySelectorAll('script[type="application/ld+json"]');
for (const el of ldJsonEls) {
try {
const data = JSON.parse(el.textContent || '');
if (Array.isArray(data)) {
for (const item of data) {
extractVideoObject(item);
}
} else if (data['@graph'] && Array.isArray(data['@graph'])) {
for (const item of data['@graph']) {
extractVideoObject(item);
}
} else {
extractVideoObject(data);
}
// Stop if we have all essential fields
if (title && channel && description) break;
} catch {}
}
// =========================================================================
// Step 2: Fallback to DOM selectors for missing metadata
// =========================================================================
if (!title) {
title = document.querySelector('h1.ytd-watch-metadata yt-formatted-string')?.textContent?.trim()
|| document.querySelector('#title h1')?.textContent?.trim() || '';
}
if (!channel) {
channel = document.querySelector('#owner #channel-name a')?.textContent?.trim()
|| document.querySelector('#channel-name a')?.textContent?.trim()
|| document.querySelector('#channel-name')?.textContent?.trim() || '';
}
if (!duration) {
duration = document.querySelector('#ytd-player .ytp-time-duration')?.textContent?.trim() || '';
}
// =========================================================================
// Step 3: Try to extract transcript
// Check if transcript panel is already open, otherwise click the button
// =========================================================================
let segments = document.querySelectorAll('ytd-transcript-segment-renderer');
let needClose = false;
if (segments.length === 0) {
const btn = document.querySelector('ytd-video-description-transcript-section-renderer button');
if (btn) {
btn.click();
needClose = true;
// Wait for transcript to load (poll every 500ms)
for (let i = 0; i < ${o}; i++) {
await new Promise(r => setTimeout(r, 500));
segments = document.querySelectorAll('ytd-transcript-segment-renderer');
if (segments.length > 0) break;
}
}
}
// Helper to close the transcript panel (called in finally block)
const closePanel = () => {
if (needClose) {
const closeBtn = document.querySelector(
'ytd-engagement-panel-section-list-renderer[target-id="engagement-panel-searchable-transcript"] #visibility-button button'
);
if (closeBtn) closeBtn.click();
}
};
// =========================================================================
// Step 4: Extract transcript segments and return result
// =========================================================================
try {
const transcript = [...segments].map(seg => ({
timestamp: seg.querySelector('.segment-timestamp')?.textContent?.trim() || '',
text: seg.querySelector('yt-formatted-string.segment-text, .segment-text')?.textContent?.trim() || ''
})).filter(t => t.timestamp && t.text);
return { videoId, title, channel, description, uploadDate, duration, genre, transcript };
} finally {
// Step 5: Always close the transcript panel if we opened it
closePanel();
}
2026-02-24 07:55:02 +08:00
})()`,u=await r.executeJavaScript(s);if(!Sfi(u))throw new Error("Invalid transcript data structure");return u}async function OGr(t,e,r={}){let{preferCommand:n=!0,focusLeafBeforeCommand:o=!0}=r;if(n)try{return await e(ALe.SAVE_TO_VAULT,{leaf:t,focusLeaf:o}),F("Saved via webviewer:save-to-vault command"),{method:"command"}}catch(i){Te("save-to-vault command failed, falling back:",i)}try{return await Promise.resolve(t.view.saveAsMarkdown()),F("Saved via view.saveAsMarkdown()"),{method:"view.saveAsMarkdown"}}catch(i){throw ne("Failed to save Web Viewer page:",i),i}}var Cbt=v(()=>{Xe();jZ();jLe()});function _b(t){if(typeof t!="string")return null;let e=t.trim();return e||null}function kZ(t){if(typeof t!="string")return null;let e=t.trim();if(!e)return null;try{let r=new URL(e);r.hash="",(r.protocol==="http:"&&r.port==="80"||r.protocol==="https:"&&r.port==="443")&&(r.port=""),r.pathname!=="/"&&(r.pathname=r.pathname.replace(/\/+$/,""));let n=Array.from(r.searchParams.entries());return n.length>0?(n.sort(([o,i],[a,s])=>o!==a?o.localeCompare(a):i.localeCompare(s)),r.search=`?${new URLSearchParams(n).toString()}`):r.search="",r.toString()}catch{return e}}function PGr(t){return _b(t)??void 0}function xbt(t){let e=_b(t.url);if(!e)return null;let r=PGr(t.title),n=PGr(t.faviconUrl);return{url:e,title:r,faviconUrl:n,isLoaded:t.isLoaded,isActive:t.isActive?!0:void 0}}function DW(t){let e=new Map;for(let r of t){let n=xbt(r);if(!n)continue;let o=e.get(n.url);if(!o){e.set(n.url,n);continue}e.set(n.url,{...o,title:n.title??o.title,faviconUrl:n.faviconUrl??o.faviconUrl,isLoaded:n.isLoaded??o.isLoaded,isActive:o.isActive||n.isActive?!0:void 0})}return Array.from(e.values())}function MGr(t){let e=DW(t),r=!1;return e.map(n=>{if(!n.isActive)return n;if(!r)return r=!0,n;let{isActive:o,...i}=n;return i})}var qZ=v(()=>{});var Cfi,kLe,RGr=v(()=>{Xe();jLe();jZ();qZ();Cfi=["did-finish-load","page-favicon-updated","page-title-updated"],kLe=class t{constructor(e){this.lastActiveLeaf=null;this.activeWebTabState={activeWebTabForMentions:null,activeOrLastWebTab:null};this.activeWebTabLeaf=null;this.activeWebTabListeners=new Set;this.activeWebTabTrackingRefs=null;this.activeWebTabTrackingPreserveViewTypes=[];this.webviewLoadListeners=new Map;this.webviewLoadCallbacks=new Set;this.cancelScheduledWebviewLoadNotify=null;this.app=e.app,this.isSupportedPlatform=e.isSupportedPlatform,this.getActiveLeaf=e.getActiveLeaf,this.getLeaves=e.getLeaves,this.getPageInfo=e.getPageInfo}getLastActiveLeaf(){let e=this.lastActiveLeaf;return!e||!Fde(e)?(this.lastActiveLeaf=null,null):_Gr(this.app,e)?e:(this.lastActiveLeaf=null,null)}findLeafByUrl(e,r={}){let n=e.trim();if(!n)return null;let o=this.getLeaves();for(let c of o)if(c?.view?.url===n)return c;let i=kZ(n);if(!i)return null;let a=[];for(let c of o){let d=c?.view?.url;if(!d)continue;kZ(d)===i&&a.push(c)}if(a.length===0)return null;if(a.length===1)return a[0];let s=(r.title??"").trim();if(s){let c=s.toLowerCase(),d=[];for(let f of a)try{let m=(this.getPageInfo(f).title||"").trim();m&&m.toLowerCase()===c&&d.push(f)}catch{}if(d.length===1)return d[0];if(d.length>1){let f=this.getActiveLeaf();if(f&&d.includes(f))return f;let p=this.getLastActiveLeaf();return p&&d.includes(p)?p:(Te("[WebViewerStateManager] Multiple leaves matched URL + title; returning first match.",{url:n,title:s,matches:d.length}),d[0])}}let u=this.getActiveLeaf();if(u&&a.includes(u))return u;let l=this.getLastActiveLeaf();return l&&a.includes(l)?l:(Te("[WebViewerStateManager] Multiple leaves matched URL; returning first match as fallback.",{url:n,matches:a.length}),a[0])}getActiveWebTabState(){return this.activeWebTabState}subscribeActiveWebTabState(e){return this.activeWebTabListeners.add(e),()=>{this.activeWebTabListeners.delete(e)}}subscribeToWebviewLoad(e){return this.webviewLoadCallbacks.add(e),()=>{this.webviewLoadCallbacks.delete(e)}}startActiveWebTabTracking(e={}){this.activeWebTabTrackingRefs&&this.stopActiveWebTabTracking(),this.activeWebTabTrackingPreserveViewTypes=[...e.preserveOnViewTypes??[]];let r=this.app.workspace.on("active-leaf-chan
2026-01-21 08:46:13 +08:00
- 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.
Title: {title}
Path: {path}
Content:
{content}
2026-02-24 07:55:02 +08:00
Summary:`;this.URL_BASED_TYPES=["url_content","web_tab_context","active_web_tab","youtube_video_context"];this.chatModelManager=tC.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async compact(e){let r=e.length;F(`[ContextCompactor] Starting compaction of ${r} chars`);let n=this.parseItems(e);if(n.length===0)return this.noOpResult(e);let o=await this.summarizeItems(n);if(o.size===0)return this.noOpResult(e);let i=this.rebuild(e,n,o);return F(`[ContextCompactor] Done: ${r} -> ${i.length} chars (${((1-i.length/r)*100).toFixed(0)}% reduction)`),{content:i,wasCompacted:!0,originalCharCount:r,compactedCharCount:i.length,itemsProcessed:n.length,itemsSummarized:o.size}}noOpResult(e){return{content:e,wasCompacted:!1,originalCharCount:e.length,compactedCharCount:e.length,itemsProcessed:0,itemsSummarized:0}}parseItems(e){let r=[];for(let n of this.BLOCK_TYPES){let o=new RegExp(`<${n}>[\\s\\S]*?<\\/${n}>`,"g"),i;for(;(i=o.exec(e))!==null;){let a=this.parseBlock(i[0],n,i.index);a&&r.push(a)}}return r.sort((n,o)=>n.startIndex-o.startIndex),r.filter((n,o)=>!r.some((i,a)=>o!==a&&i.startIndex<=n.startIndex&&i.endIndex>=n.endIndex))}parseBlock(e,r,n){let o=l=>new RegExp(`<${l}>([^<]*)</${l}>`).exec(e)?.[1]||"",i=()=>/<content>([\s\S]*?)<\/content>/.exec(e)?.[1]||"",a=o("path")||o("url"),s=o("title")||a.split("/").pop()||"Untitled",u=i();return{type:r,path:a,title:s,content:u,metadata:{ctime:o("ctime"),mtime:o("mtime")},originalXml:e,startIndex:n,endIndex:n+e.length}}async summarizeItems(e){let r=new Map,n=e.map((o,i)=>({index:i,item:o})).filter(({item:o})=>o.content.length>=this.MIN_ITEM_SIZE);if(n.length===0)return r;F(`[ContextCompactor] Summarizing ${n.length} items`);for(let o=0;o<n.length;o+=this.MAX_CONCURRENCY){let i=n.slice(o,o+this.MAX_CONCURRENCY);(await Promise.all(i.map(async({index:s,item:u})=>{try{return{index:s,summary:await this.summarize(u)}}catch(l){return F(`[ContextCompactor] Failed to summarize item ${s}:`,l),{index:s,summary:null}}}))).forEach(({index:s,summary:u})=>{u&&r.set(s,u)})}return r.size<n.length*.5?(F("[ContextCompactor] High failure rate, aborting compaction"),new Map):r}async summarize(e){let r=e.content;r.length>this.MAX_ITEM_SIZE&&(r=r.slice(0,this.MAX_ITEM_SIZE)+`
[TRUNCATED]`);let n=this.PROMPT.replace("{title}",e.title).replace("{path}",e.path).replace("{content}",r),i=await(await this.chatModelManager.getChatModelWithTemperature(this.TEMPERATURE)).invoke([new qs(n)]);return typeof i.content=="string"?i.content.trim():""}rebuild(e,r,n){let o=e;return Array.from(n.keys()).sort((i,a)=>a-i).forEach(i=>{let a=r[i],s=n.get(i),u=this.buildBlock(a,s);o=o.slice(0,a.startIndex)+u+o.slice(a.endIndex)}),o}buildBlock(e,r){let n=[`<${e.type}>`];if(e.title&&n.push(`<title>${e.title}</title>`),e.path){let o=this.URL_BASED_TYPES.includes(e.type)?"url":"path";n.push(`<${o}>${e.path}</${o}>`)}return e.metadata.ctime&&n.push(`<ctime>${e.metadata.ctime}</ctime>`),e.metadata.mtime&&n.push(`<mtime>${e.metadata.mtime}</mtime>`),n.push(`<content>[SUMMARIZED]
2026-01-21 08:46:13 +08:00
${r}</content>`),n.push(`</${e.type}>`),n.join(`
2026-02-24 07:55:02 +08:00
`)}}});var LCi={};En(LCi,{default:()=>WUe});module.exports=Bpe(LCi);mA();ra();Xe();var G_r=$(gH()),i9=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(){await app.vault.adapter.exists(this.cacheDir)||(F("Creating file cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e,r){let n=`${e.path}:${e.stat.size}:${e.stat.mtime}${r?`:${r}`:""}`;return(0,G_r.MD5)(n).toString()}getCachePath(e){return`${this.cacheDir}/${e}.md`}async get(e){try{let r=this.memoryCache.get(e);if(r)return F("Memory cache hit for file:",e),r.content;let n=this.getCachePath(e);if(await app.vault.adapter.exists(n)){F("File cache hit:",e);let o=await app.vault.adapter.read(n),i,a=o.trim();if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{i=JSON.parse(o)}catch{i=o}else i=o;let s={content:i,timestamp:Date.now()};return this.memoryCache.set(e,s),s.content}return F("Cache miss for file:",e),null}catch(r){return ne("Error reading from file cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCachePath(e),o=Date.now(),i={content:r,timestamp:o};this.memoryCache.set(e,i);let a;typeof r=="string"?a=r:a=JSON.stringify(r,null,2),await app.vault.adapter.write(n,a),F("Cached file content:",e)}catch(n){ne("Error writing to file cache:",n)}}async remove(e){try{this.memoryCache.delete(e);let r=this.getCachePath(e);await app.vault.adapter.exists(r)&&(await app.vault.adapter.remove(r),F("Removed file from cache:",e))}catch(r){ne("Error removing file from cache:",r)}}async clear(){try{if(this.memoryCache.clear(),await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);F("Clearing file cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){ne("Error clearing file cache:",e)}}};Xe();ob();Ye();var Q_r=$(gH()),WEe=require("obsidian"),evr=$(a9());$at();var xq=class xq{constructor(){this.cacheDir=".copilot/project-context-cache";this.memoryCache=new Map;this.projectMutexMap=new Map;this.mutexCreationMutex=new hH;this.handleFileEvent=e=>{e instanceof WEe.TFile&&this.debouncedHandleFileChange(e)};this.handleFileChange=async e=>{try{if(e.extension!=="md")return;let n=te().projectList||[];for(let o of n){let{inclusions:i,exclusions:a}=el({inclusions:o.contextSource.inclusions,exclusions:o.contextSource.exclusions,isProject:!0});Hs(e,i,a,!0)&&(await this.invalidateMarkdownContext(o),F(`Invalidated markdown context for project ${o.name} due to file change: ${e.path}`))}}catch(r){ne("Error handling file change for project context cache:",r)}};this.debouncedHandleFileChange=(0,evr.default)(e=>{this.handleFileChange(e)},xq.DEBOUNCE_DELAY,{leading:!0,trailing:!0});this.vault=app.vault,this.fileCache=i9.getInstance(),this.initializeEventListeners()}static getInstance(){return xq.instance||(xq.instance=new xq),xq.instance}cleanup(){this.debouncedHandleFileChange.cancel(),this.vault.off("create",this.handleFileEvent),this.vault.off("modify",this.handleFileEvent),this.vault.off("delete",this.handleFileEvent),this.vault.off("rename",this.handleFileEvent),this.projectMutexMap.clear()}initializeEventListeners(){this.vault.on("create",this.handleFileEvent),this.vault.on("modify",this.handleFileEvent),this.vault.on("delete",this.handleFileEvent),this.vault.on("rename",this.handleFileEvent)}async ensureCacheDir(){await this.vault.adapter.exists(this.cacheDir)||(F("Creating project context cache directory:",this.cacheDir),await this.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){return(0,Q_r.MD5)(e.id).toString()}getCachePath(e){return`${this.cacheDir}/${e}.json`}async getOrCreateProjectMutex(e){let r=e.id,n=this.projectMutexMap.get(r);return n||await this.mutexCreationMutex.runExclusive(async()=>{let o=this.projectMutexMap.get(r);if(o)return o;let i=new hH;return this.projectMutexMap.set(r,i),F(`Created new mutex for project: ${e.name} (ID: ${r})`),i})}async get(e){try{let r=this
${e.join(`
`)}`)}};mA();vO();Xe();Ye();var Rpo="https://api.firecrawl.dev/v2/search",Ipo="https://api.perplexity.ai/chat/completions",rvr="https://api.supadata.ai/v1/transcript",Apo=2e3,tvr=6e4;function nvr(){let t=te();switch(t.selfHostSearchProvider){case"perplexity":return!!t.perplexityApiKey;case"firecrawl":default:return!!t.firecrawlApiKey}}async function Npo(t,e){let r=Date.now(),n=await fetch(Rpo,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({query:t,limit:5})});if(!n.ok){let c=await n.text();throw new Error(`Firecrawl search failed (${n.status}): ${c}`)}let i=(await n.json())?.data,a=Array.isArray(i)?i:Array.isArray(i?.web)?i.web:[],s=[],u=[];for(let c of a){let d=c.title||"Untitled",f=c.description||"",p=c.url||"";s.push(`### ${d}
${f}
Source: ${p}`),p&&u.push(p)}let l=Date.now()-r;return F(`[selfHostWebSearch] Firecrawl: ${a.length} results in ${l}ms`),{content:s.join(`
`),citations:u}}async function Dpo(t,e){let r=await fetch(Ipo,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({model:"sonar",messages:[{role:"user",content:t}]})});if(!r.ok){let a=await r.text();throw new Error(`Perplexity Sonar search failed (${r.status}): ${a}`)}let n=await r.json(),o=n?.choices?.[0]?.message?.content??"",i=Array.isArray(n?.citations)?n.citations:[];return{content:o,citations:i}}async function ovr(t){let e=te();switch(e.selfHostSearchProvider){case"perplexity":return Dpo(t,await oo(e.perplexityApiKey));case"firecrawl":default:return Npo(t,await oo(e.firecrawlApiKey))}}async function JEe(t){let e=Date.now(),r=await oo(te().supadataApiKey),n=`${rvr}?url=${encodeURIComponent(t)}&mode=auto&text=true`,o=await fetch(n,{method:"GET",headers:{"x-api-key":r,Accept:"application/json"}});if(o.status===200){let a=await o.json(),s=Date.now()-e;return F(`[selfHostYoutube4llm] transcript received in ${s}ms`),{response:{transcript:a.content||""},elapsed_time_ms:s}}if(o.status===201||o.status===202){let s=(await o.json()).job_id;if(!s)throw new Error("Supadata returned async status but no job_id");return await jpo(s,r,e)}let i=await o.text();throw new Error(`Supadata transcript request failed (${o.status}): ${i}`)}async function jpo(t,e,r){let n=Date.now()+tvr,o=`${rvr}/${t}`;for(;Date.now()<n;){await new Promise(s=>setTimeout(s,Apo));let i=await fetch(o,{method:"GET",headers:{"x-api-key":e,Accept:"application/json"}});if(i.status===200){let s=await i.json(),u=Date.now()-r;return F(`[selfHostYoutube4llm] async transcript completed in ${u}ms`),{response:{transcript:s.content||""},elapsed_time_ms:u}}if(i.status===202)continue;let a=await i.text();throw ne(`[selfHostYoutube4llm] poll failed (${i.status}): ${a}`),new Error(`Supadata poll failed (${i.status}): ${a}`)}throw new Error(`Supadata transcript timed out after ${tvr}ms`)}Bt();Xe();Fc();Ye();var s9=class t{constructor(){this.mentions=new Map,this.brevilabsClient=Ql.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}extractAllUrls(e){let r=/https?:\/\/[^\s"'<>]+/g;return(e.match(r)||[]).map(n=>n.replace(/,+$/,"")).filter((n,o,i)=>i.indexOf(n)===o)}extractUrls(e){let r=/https?:\/\/[^\s"'<>]+/g;return(e.match(r)||[]).map(n=>n.replace(/,+$/,"")).filter((n,o,i)=>i.indexOf(n)===o)}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(r){let n=zr(r);return ne(`Error processing URL ${e}: ${n}`),{response:e,elapsed_time_ms:0,error:n}}}async processYoutubeUrl(e){try{return{transcript:(o_()&&te().supadataApiKey?await JEe(e):await this.brevilabsClient.youtube4llm(e)).response.transcript}}catch(r){let n=zr(r);return ne(`Error processing YouTube URL ${e}: ${n}`),{transcript:"",error:n}}}async processTwitterUrl(e){try{return await this.brevilabsClient.twitter4llm(e)}catch(r){let n=zr(r);return ne(`Error processing Twitter URL ${e}: ${n}`),{response:e,elapsed_time_ms:0,error:n}}}async processUrlList(e){let r="",n=[],o={};if(e.length===0)return{urlContext:r,imageUrls:n,processedErrorUrls:o};let i=e.map(async s=>{if(await bA.isImageUrl(s,app.vault))return n.push(s),{type:"image",url:s};if(E1t(s)){let l=this.mentions.get(s);if(!l||l.error){let c=await this.processYoutubeUrl(s);this.mentions.set(s,{type:"youtube",original:s,processed:c.transcript,error:c.error})}return{type:"youtube",data:this.mentions.get(s)}}if(P1t(s)){let l=this.mentions.get(s);if(!l||l.error){let c=await this.processTwitterUrl(s);this.mentions.set(s,{type:"twitter",original:s,processed:c.response,error:c.error})}return{type:"twitter",data:this.mentions.get(s)}}let u=this.mentions.get(s);if(!u||u.error){let l=await this.processUrl(s);this.mentions.set(s,{type:"url",original:s,processed:l.response,error:l.error})}return{type:"url",data:this.mentions.get(s)}});return(await Promise.all(i)).forEach(s=>{if(s.type==="image")return;let u=s.data;u&&(u.processed&&(s.type==="youtube"?r+=`
<youtube_video_context>
<url>${u.original}</url>
<content>
${u.processed}
</content>
</youtube_video_context>`:s.type==="twitter"?r+=`
<twitter_content>
<url>${u.original}</url>
<content>
${u.processed}
</content>
</twitter_content>`:r+=`
<url_content>
<url>${u.original}</url>
<content>
${u.processed}
</content>
</url_content>`),u.error&&(o[u.original]=u.error))}),{urlContext:r,imageUrls:n,processedErrorUrls:o}}async processUrls(e){let r=this.extractUrls(e);return this.processUrlList(r)}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};ob();Ye();Xe();var ivr=$(gH()),KEe=class t{constructor(){this.cacheDir=".copilot/pdf-cache"}static getInstance(){return t.instance||(t.instance=new t),t.instance}async ensureCacheDir(){await app.vault.adapter.exists(this.cacheDir)||(F("Creating PDF cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){let r=`${e.path}:${e.stat.size}:${e.stat.mtime}`,n=(0,ivr.MD5)(r).toString();return F("Generated cache key for PDF:",{path:e.path,key:n}),n}getCachePath(e){return`${this.cacheDir}/${e}.json`}async get(e){try{let r=this.getCacheKey(e),n=this.getCachePath(r);if(await app.vault.adapter.exists(n)){F("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return F("Cache miss for PDF:",e.path),null}catch(r){return ne("Error reading from PDF cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCacheKey(e),o=this.getCachePath(n);F("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(r))}catch(n){ne("Error writing to PDF cache:",n)}}async clear(){try{if(await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);F("Clearing PDF cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){ne("Error clearing PDF cache:",e)}}};Xe();BG();Fc();Ye();function DD(t){if(!t||typeof t!="object")return!1;let e=t.message||t.toString();return e.includes("Request rate limit exceeded")||e.includes("RATE_LIMIT_EXCEEDED")||e.includes("429")||t.status===429}function avr(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var YEe=require("obsidian");var svr=require("obsidian");var XEe,uvr,GEe=class{constructor(e){this.vault=e;cBe(this,XEe)}async load(e){let r=await this.vault.read(e),{nodes:n=[],edges:o=[]}=JSON.parse(r),i=await Promise.all(n.map(async u=>{if(u.type==="file"&&u.file){let l=this.vault.getAbstractFileByPath(u.file),c=l instanceof svr.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];dCt(this,XEe,uvr).call(this,i,a);let s=Object.fromEntries(i.map(u=>[u.id,u]));return{nodes:i,edges:a,byId:s}}buildPrompt(e){let r=new Map,n=e.nodes.filter(s=>s.type==="group");for(let s of n){let u=e.nodes.filter(l=>{if(l.id===s.id)return!1;let c=l.x+l.width/2,d=l.y+l.height/2;return c>=s.x&&d>=s.y&&c<=s.x+s.width&&d<=s.y+s.height});r.set(s.label||s.id,u)}let o=`This canvas contains the following elements:
`,i=s=>{switch(s.type){case"file":return`- File: ${s.file}
Content:
${s.content}
`;case"text":return`- Text: "${s.text}"
`;case"link":return`- Link: ${s.url}
`;default:return""}};n.forEach(s=>{let u=s.label||s.id,l=r.get(u)||[];o+=`Group "${u}" contains:
`,l.forEach(c=>{o+=i(c)}),o+=`
`});let a=e.nodes.filter(s=>s.type==="group"?!1:!Array.from(r.values()).flat().some(u=>u.id===s.id));return a.length>0&&(o+=`Elements outside of groups:
`,a.forEach(s=>{o+=i(s)})),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}};XEe=new WeakSet,uvr=function(e,r){let n=e.filter(o=>o.type==="group");for(let o of n)for(let i of e){if(i.id===o.id)continue;let a=i.x+i.width/2,s=i.y+i.height/2;a>=o.x&&s>=o.y&&a<=o.x+o.width&&s<=o.y+o.height&&r.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}};function $po(t,e){let r=e.adapter;if(r instanceof YEe.FileSystemAdapter)return r.getFullPath(t.path);let n=r;return typeof n.getFullPath=="function"?n.getFullPath(t.path):null}var ost=class{constructor(){this.miyoClient=new S0}async parsePdf(e,r){let n=te();if(!n.enableMiyo||e.extension.toLowerCase()!=="pdf")return null;let o=$po(e,r);if(!o)return Te(`[SelfHostPdfParser] Could not resolve absolute path for ${e.path}; cannot call Miyo parse-doc`),null;try{let i=await this.miyoClient.resolveBaseUrl(n.selfHostUrl),a=await this.miyoClient.parseDoc(i,o);if(typeof a.text!="string"||a.text.trim().length===0)throw new Error("Miyo parse-doc returned empty text");return F(`[SelfHostPdfParser] Parsed PDF via Miyo: ${e.path}`),a.text}catch(i){return Te(`[SelfHostPdfParser] Failed to parse ${e.path} via Miyo parse-doc: ${i instanceof Error?i.message:String(i)}`),null}}},ist=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},ZEe=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=KEe.getInstance(),this.selfHostPdfParser=new ost}async parseFile(e,r){try{F("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return F("Using cached PDF content for:",e.path),n.response;let o=te();if(o_()&&o.enableMiyo&&e.extension.toLowerCase()==="pdf"){let s=await this.selfHostPdfParser.parsePdf(e,r);return s!==null?(await this.pdfCache.set(e,{response:s,elapsed_time_ms:0}),s):(ne(`[PDFParser] Miyo enabled but parse-doc failed for ${e.path}`),`[Error: Could not extract content from PDF ${e.basename}]`)}let i=await r.readBinary(e);F("Calling pdf4llm API for:",e.path);let a=await this.brevilabsClient.pdf4llm(i);return await this.pdfCache.set(e,a),a.response}catch(n){return ne(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){F("Clearing PDF cache"),await this.pdfCache.clear()}},ast=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{F("Parsing Canvas file:",e.path);let n=new GEe(r),o=await n.load(e);return n.buildPrompt(o)}catch(n){return ne(`Error parsing Canvas file ${e.path}:`,n),`[Error: Could not parse Canvas file ${e.basename}]`}}},u9=class u9{constructor(e,r=null){this.supportedExtensions=["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"];this.brevilabsClient=e,this.projectContextCache=Fw.getInstance(),this.currentProject=r}static resetRateLimitNoticeTimer(){u9.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(F(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throw ne("[Docs4LLMParser] No project context for parsing file: ",e.path),new Error("No project context provided for file parsing");let n=await this.projectContextCache.getOrReuseFileContext(this.currentProject,e.path);if(n)return F(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;F(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);let o=await r.readBinary(e);F(`[Docs4LLMParser] Project ${this.currentProject.name}: Calling docs4llm API for: ${e.path}`);let i=await this.brevilabsClient.docs4llm(
`)}else typeof i.response=="object"?i.response.md?a=i.response.md:i.response.text?a=i.response.text:i.response.content?a=i.response.content:a=JSON.stringify(i.response,null,2):a=String(i.response);return await this.projectContextCache.setFileContext(this.currentProject,e.path,a),F(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),a}catch(n){throw ne(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,n),DD(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-u9.lastRateLimitNoticeTime<6e4)return;u9.lastRateLimitNoticeTime=r;let n=avr(e);new YEe.Notice(`\u26A0\uFE0F Rate limit exceeded for document processing. Please try again in ${n}. Having fewer non-markdown files in the project will help.`,1e4)}async clearCache(){F("Cache clearing is now handled at the project level")}};u9.lastRateLimitNoticeTime=0;var Iae=u9,Tq=class{constructor(e,r,n=!1,o=null){this.parsers=new Map;this.isProjectMode=n,this.currentProject=o,this.registerParser(new ist),this.registerParser(new Iae(e,o)),n||this.registerParser(new ZEe(e)),this.registerParser(new ast)}registerParser(e){for(let r of e.supportedExtensions)this.parsers.set(r,e)}async parseFile(e,r){let n=this.parsers.get(e.extension);if(!n)throw new Error(`No parser found for file type: ${e.extension}`);return await n.parseFile(e,r)}supportsExtension(e){return this.parsers.has(e)}async clearPDFCache(){let e=this.parsers.get("pdf");e instanceof ZEe&&await e.clearCache()}};Bt();l1();var dW=require("obsidian");mA();ra();sd();mr();mr();Xe();Bt();var jD=class{constructor(e){this.chainManager=e}async handleResponse(e,r,n,o,i,a,s,u){if((e||u?.wasTruncated)&&!(n.signal.aborted&&n.signal.reason==="new-chat")){let p=r.contextEnvelope?.layers.find(g=>g.id==="L5_USER")?.text||r.originalMessage||r.message,m=s||e||"[Response truncated - no content generated]";await this.chainManager.memoryManager.saveContext({input:p},{output:m});let y={message:e||(u?.wasTruncated?"_[The response was truncated before any content could be generated. Try increasing the max tokens limit.]_":""),sender:cw,isVisible:!0,timestamp:Mg(new Date),sources:a,responseMetadata:u};o(y),i("")}else n.signal.reason==="new-chat"&&i("");let c=this.chainManager.memoryManager.getMemory().chatHistory.messages;F(`Chat memory updated:
`,{turns:Array.isArray(c)?c.length:0});let d=2e3;try{let{parseToolCallMarkers:f}=await Promise.resolve().then(()=>(dst(),lvr)),m=f(e).segments.map(y=>y.type==="text"?y.content:"").join("").trim();m||(m=e||"");let h=m.length>d?m.slice(0,d)+"... (truncated)":m;F(`Final AI response (truncated):
`,h)}catch{let f=typeof e=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;F(`Final AI response (truncated):
`,p)}return e}async handleError(e,r){let n=zr(e);ne("Error during LLM invocation:",n);let o=e?.response?.data?.error||n,i=o?.code||n,a="";e?.message?.includes("Invalid license key")?a="Invalid Copilot Plus license key. Please check your license key in settings.":i==="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=`${i}`,ne(o),r(this.enhancedErrorMsg(a,n,e))}enhancedErrorMsg(e,r,n){let o=e.search("Troubleshooting URL");return e=o!==-1?e.slice(0,o):e,this.isAuthenticationError(n,r)&&(e=`Something went wrong. Please check if you have set your API key.
Path: Settings > copilot plugin > Basic Tab > Set Keys.
Or check model config
Error Details: `+e),e}isAuthenticationError(e,r){let n=e?.response,o=n?.data?.error??e?.error,i=n?.status??o?.status,a=typeof i=="string"?Number.parseInt(i,10):i,s=typeof o=="object"&&o!==null?o:void 0,u=(typeof s?.message=="string"?s.message:r).toLowerCase(),l=typeof s?.code=="string"?s.code.toLowerCase():"",c=typeof s?.type=="string"?s.type.toLowerCase():"";return a===401?!0:["api key","apikey","unauthorized","authentication","invalid authentication"].some(f=>u.includes(f)||l.includes(f)||c.includes(f))}};mr();Xe();var _A=class{static convert(e,r={}){let{includeSystemMessage:n=!0,mergeUserContent:o=!0,debug:i=!1}=r,a=[],s=e.layers.find(f=>f.id==="L1_SYSTEM"),u=e.layers.find(f=>f.id==="L2_PREVIOUS"),l=e.layers.find(f=>f.id==="L3_TURN"),c=e.layers.find(f=>f.id==="L4_STRIP"),d=e.layers.find(f=>f.id==="L5_USER");if(n&&s&&s.text){let f=[s.text];u&&u.text&&(f.push(`
## Context Library
The following notes are available for reference:
`+u.text),i&&F("[LayerToMessagesConverter] Added L2 (cumulative context) to system")),a.push({role:"system",content:f.join(`
`)}),i&&F("[LayerToMessagesConverter] Added L1 (System) + L2 (Cumulative) as stable prefix")}if(c&&c.text&&i&&F("[LayerToMessagesConverter] L4 (Strip) found but skipped (using LangChain memory)"),o){let f=[];if(l&&l.segments.length>0&&u){let p=new Set(u.segments.map(y=>y.id)),m=[],h=[];for(let y of l.segments)p.has(y.id)?m.push(y.id):h.push(y);if(m.length>0||h.length>0){let y=[];m.length>0&&y.push(`Context attached to this message:
`+m.map(g=>`- ${g}`).join(`
`)+`
Find them in the Context Library in the system prompt above.`),h.length>0&&y.push(h.map(g=>g.content).join(`
`)),f.push(y.join(`
`)),i&&F(`[LayerToMessagesConverter] Added L3: ${m.length} references, ${h.length} new items`)}}else l&&l.text&&(f.push(l.text),i&&F("[LayerToMessagesConverter] Added L3 (all new context)"));f.length>0&&d&&d.text&&f.push(`---
[User query]:`),d&&d.text&&(f.push(d.text),i&&F("[LayerToMessagesConverter] Added L5 (user message)")),f.length>0&&a.push({role:"user",content:f.join(`
`)})}else l&&l.text&&a.push({role:"user",content:l.text}),d&&d.text&&a.push({role:"user",content:d.text});return i&&(F(`[LayerToMessagesConverter] Converted envelope to ${a.length} messages`),a.forEach((f,p)=>{let m=f.content.substring(0,100);F(` Message ${p+1} [${f.role}]: ${m}...`)})),a}static extractUserContent(e){let r=e.layers.find(i=>i.id==="L3_TURN"),n=e.layers.find(i=>i.id==="L5_USER"),o=[];return r&&r.text&&o.push(r.text),n&&n.text&&o.push(n.text),o.join(`
`)}static extractFullContext(e){let r=e.layers.find(a=>a.id==="L2_PREVIOUS"),n=e.layers.find(a=>a.id==="L3_TURN"),o=e.layers.find(a=>a.id==="L5_USER"),i=[];return r&&r.text&&i.push(r.text),n&&n.text&&i.push(n.text),o&&o.text&&i.push(o.text),i.join(`
`)}static extractSystemMessage(e){return e.layers.find(n=>n.id==="L1_SYSTEM")?.text||""}static getLayerHashes(e){return e.layerHashes}};Xe();Ye();Bt();Xe();function fst(t){let e=[];for(let r of t)if(r){if(typeof r._getType=="function"){let n=r._getType();n==="human"?e.push({role:"user",content:r.content}):n==="ai"&&e.push({role:"assistant",content:r.content})}else if(r.content!==void 0){let n=zpo(r);n&&e.push({role:n,content:r.content})}}return e}function zpo(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}function Vpo(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(r=>r.type==="text").map(r=>r.text||"").join(" ")||"[Image content]":String(t||"")}function cvr(t){return t.map(e=>({role:e.role,content:Vpo(e.content)}))}async function Oq(t,e){let n=(await t.loadMemoryVariables({})).history||[],o=n.length?fst(n):[];for(let u of o)e.push({role:u.role,content:u.content});let i=0;for(let u of e)typeof u.content=="string"&&u.role==="system"&&(i+=u.content.length);let a=0;for(let u of o)typeof u.content=="string"&&(a+=u.content.length);let s=i+a;return s>2e6&&F("[Token Budget] Large payload detected (excluding user message):",{"L1+L2 (system)":`${Math.round(i/4e3)}k tokens`,"L4 (history)":`${Math.round(a/4e3)}k tokens (${o.length} msgs)`,total:`${Math.round(s/4e3)}k tokens`}),o}Xe();var yd=class t{constructor(){this.tools=new Map}static getInstance(){return t.instance||(t.instance=new t),t.instance}register(e){this.tools.set(e.metadata.id,e)}registerAll(e){e.forEach(r=>this.register(r))}getAllTools(){return Array.from(this.tools.values())}getEnabledTools(e,r){let n=[];for(let[o,i]of this.tools){let{metadata:a,tool:s}=i;if(a.isAlwaysEnabled){(!a.requiresVault||r)&&n.push(s);continue}e.has(o)&&(!a.requiresVault||r)&&n.push(s)}return n}getToolsByCategory(){let e=new Map;for(let r of this.tools.values()){let n=r.metadata.category;e.has(n)||e.set(n,[]),e.get(n).push(r)}return e}getConfigurableTools(){return Array.from(this.tools.values()).filter(e=>!e.metadata.isAlwaysEnabled)}getCopilotCommandMappings(){let e=new Map;for(let r of this.tools.values()){let n=r.metadata.copilotCommands;if(n)for(let o of n){let i=o.toLowerCase();e.has(i)||e.set(i,r)}}return e}getToolMetadata(e){return this.tools.get(e)?.metadata}getToolDefinition(e){return this.tools.get(e)}clear(){this.tools.clear()}};var l9=null;function Hpo(t){let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return typeof n=="bigint"?n.toString():n},2)}function Wpo(t,e){let r=[];e&&(r.push(`msg:${e.messageId??"N/A"} | conv:${e.conversationId??"N/A"} | v${e.version}`),r.push(""));let n=yd.getInstance(),o=new Set(n.getAllTools().map(c=>c.tool.name)),i=c=>{let d=[],f=/<(\w+)>([\s\S]*?)<\/\1>/g,p;for(;(p=f.exec(c))!==null;){let m=p[1],h=p[2];if(o.has(m)){let y=h.length>200?h.substring(0,200).trim()+"...[truncated]":h.trim();d.push({tool:m,preview:y})}}return d},a=c=>typeof c.content=="string"?c.content:Array.isArray(c.content)?c.content.filter(f=>f.type==="text").map(f=>f.text).join(`
`):"",s=Array.isArray(t)?t:[],u=0;for(let c=0;c<s.length;c++){let d=s[c],f=a(d);if(d.role==="system"){r.push("\u2501\u2501\u2501 SYSTEM MESSAGE \u2501\u2501\u2501"),r.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);r.push(`\u{1F512} L1_SYSTEM (${h}) [CACHEABLE]`);let y=f.indexOf(p.text)+p.text.length,g=p.text.length>300?p.text.substring(0,300)+"...[truncated]":p.text;if(r.push(g),r.push(""),m&&m.text){let w=m.hash.substring(0,8);r.push(`\u{1F512} L2_PREVIOUS (${w}) [CACHEABLE]`);let T=m.text.length>300?m.text.substring(0,300)+"...[truncated]":m.text;r.push(T),r.push("")}let b=f.substring(y),_=i(b);if(_.length>0){r.push("--- PER-TURN ADDITIONS (not cached) ---"),r.push("");for(let w of _)r.push(`\u{1F4E6} TOOL: ${w.tool} (turn-specific RAG)`),r.push(w.preview),r.push("")}}else{let h=i(f);if(h.length>0){let y=f.match(/<(\w+)>/);if(y){let g=f.substring(0,y.index);if(g.trim()){let b=g.length>300?g.substring(0,300)+"...[truncated]":g;r.push(b),r.push("")}}r.push("--- PER-TURN ADDITIONS (not cached) ---"),r.push("");for(let g of h)r.push(`\u{1F4E6} TOOL: ${g.tool}`),r.push(g.preview),r.push("")}else{let y=f.length>300?f.substring(0,300)+"...[truncated]":f;r.push(y),r.push("")}}}else(d.role==="user"||d.role==="assistant")&&c<s.length-1&&u++}u>0&&(r.push("\u2501\u2501\u2501 CHAT HISTORY (L4) \u2501\u2501\u2501"),r.push(""),r.push(`${u} message(s)`),r.push(""));let l=s[s.length-1];if(l&&l.role==="user"){r.push("\u2501\u2501\u2501 USER MESSAGE \u2501\u2501\u2501"),r.push("");let c=a(l),d=i(c);if(d.length>0){r.push("--- PER-TURN TOOL RESULTS ---"),r.push("");for(let m of d)r.push(`\u{1F4E6} TOOL: ${m.tool}`),r.push(m.preview),r.push("")}let f=e?.layers.find(m=>m.id==="L3_TURN"),p=e?.layers.find(m=>m.id==="L5_USER");if(f&&f.text&&c.includes(f.text)){let m=f.hash.substring(0,8);r.push(`\u26A1 L3_TURN (${m})`);let h=f.text.length>300?f.text.substring(0,300)+"...[truncated]":f.text;r.push(h),r.push("")}if(p&&p.text&&c.includes(p.text)){let m=p.hash.substring(0,8);r.push(`\u26A1 L5_USER (${m})`),r.push(p.text),r.push("")}}return r.join(`
`)}function Eq(t){let{messages:e,modelName:r,contextEnvelope:n}=t;try{l9={timestamp:new Date().toISOString(),modelName:r,serializedMessages:Hpo(e),messagesArray:e,contextEnvelope:n}}catch{l9={timestamp:new Date().toISOString(),modelName:r,serializedMessages:String(e),messagesArray:e,contextEnvelope:n}}}function c9(){l9=null}async function QEe(){if(!l9)return;let{timestamp:t,modelName:e,serializedMessages:r,messagesArray:n,contextEnvelope:o}=l9,i=[`### Prompt \u2014 ${t}${e?` \u2014 ${e}`:""}`,"","**Actual Messages Sent to LLM:**","","```json",r,"```",""],a=Wpo(n,o);i.push("**Layered Context Metadata:**"),i.push(""),i.push("```"),i.push(a),i.push("```"),i.push(""),fye(i),l9=null}function dvr(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 fvr(t){let e=t.response_metadata||{};return e.tokenUsage?{inputTokens:e.tokenUsage.promptTokens,outputTokens:e.tokenUsage.completionTokens,totalTokens:e.tokenUsage.totalTokens}:e.usage?{inputTokens:e.usage.input_tokens||e.usage.inputTokens||e.usage.inputTokenCount||e.usage.prompt_tokens,outputTokens:e.usage.output_tokens||e.usage.outputTokens||e.usage.outputTokenCount||e.usage.completion_tokens,totalTokens:e.usage.total_tokens||e.usage.totalTokens||(e.usage.input_tokens||e.usage.inputTokenCount||0)+(e.usage.output_tokens||e.usage.outputTokenCount||0)}:t.usage_metadata?{inputTokens:t.usage_metadata.input_tokens,outputTokens:t.usage_metadata.output_tokens,totalTokens:t.usage_metadata.total_tokens}:null}function Jpo(t){return`<errorChunk>${t}</errorChunk>`}function ePe(t,e){let r=Jpo(t);return e?`${e}
${r}`:`
${r}`}ta();Xe();function pst(t,e,r){return new Mh({content:r,tool_call_id:t,name:e})}function tPe(){let t=Date.now(),e=Math.random().toString(36).substring(2,11);return`call_${t}_${e}`}function rPe(t){let e=[];for(let r of t.values()){if(!r.name)continue;let n={};if(r.args)try{n=JSON.parse(r.args)}catch{ne(`[ToolCall] Failed to parse args for tool "${r.name}": ${r.args}`),n={}}e.push({id:r.id||tPe(),name:r.name,args:n})}return e}function pvr(t,e){return new Pn({content:t,tool_calls:e.map(r=>({id:r.id,name:r.name,args:r.args,type:"tool_call"}))})}Xe();var dv=class{constructor(e,r=!1){this.updateCurrentAiMessage=e;this.excludeThinking=r;this.hasOpenThinkBlock=!1;this.fullResponse="";this.errorResponse="";this.wasTruncated=!1;this.tokenUsage=null;this.hasHandledTextLevelThinkTag=!1;this.toolCallChunks=new Map;this.accumulatedToolCalls=[];F(`[ThinkBlockStreamer] Created with excludeThinking=${r}`)}handleTextLevelThinkTags(){let e=this.fullResponse.includes("</think>"),r=this.fullResponse.includes("<think>");if(e){if(this.excludeThinking){if(r)this.fullResponse=this.fullResponse.replace(/<think>[\s\S]*?<\/think>/g,"").trim();else{let n=this.fullResponse.indexOf("</think>");this.fullResponse=this.fullResponse.substring(n+8).trim()}return}!r&&!this.hasHandledTextLevelThinkTag&&(this.hasHandledTextLevelThinkTag=!0,Te("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)}}handleClaudeChunk(e){let r="",n=!1;for(let o of e)switch(o.type){case"text":r+=o.text;break;case"thinking":if(n=!0,this.excludeThinking)break;this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),o.thinking!==void 0&&(this.fullResponse+=o.thinking),this.updateCurrentAiMessage(this.fullResponse);break}return r&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),r&&(this.fullResponse+=r),n}handleDeepseekChunk(e){return typeof e.content=="string"&&(this.fullResponse+=e.content),e.additional_kwargs?.reasoning_content?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),e.additional_kwargs.reasoning_content!==void 0&&(this.fullResponse+=e.additional_kwargs.reasoning_content)),!0):!1}handleOpenRouterChunk(e){return e.additional_kwargs?.delta?.reasoning?(this.excludeThinking||(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 r=e.tool_call_chunks;if(!(!r||!Array.isArray(r)))for(let n of r){let o=n.index??0,i=this.toolCallChunks.get(o)||{name:"",args:""};n.id&&(i.id=n.id),n.name&&(i.name+=n.name),n.args&&(i.args+=n.args),this.toolCallChunks.set(o,i)}}processChunk(e){dvr(e).wasTruncated&&(this.wasTruncated=!0);let n=fvr(e);n&&(this.tokenUsage=n),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=ePe(e)}getToolCalls(){return this.accumulatedToolCalls.length>0?this.accumulatedToolCalls:rPe(this.toolCallChunks)}hasToolCalls(){return this.toolCallChunks.size>0||this.accumulatedToolCalls.length>0}setToolCalls(e){this.accumulatedToolCalls=e}buildAIMessage(){let e=this.getToolCalls();return pvr(this.fullResponse,e)}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}}};ra();var Aae=class extends jD{async constructMessages(e){if(!e.contextEnvelope)throw new Error("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");F("[LLMChainRunner] Using envelope-based context");let r=_A.convert(e.contextEnvelope,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),n=[],o=r.find(s=>s.role==="system");o&&n.push(o);let i=this.chainManager.memoryManager.getMemory();await Oq(i,n);let a=r.find(s=>s.role==="user");if(a)if(e.content&&Array.isArray(e.content)){let s=e.content.map(u=>u.type==="text"?{...u,text:a.content}:u);n.push({role:"user",content:s})}else n.push(a);return n}async run(e,r,n,o,i){let a=te(),s=B_(),u=!1;try{u=!qS(s,a.activeModels).capabilities?.includes("reasoning")}catch(f){F("Could not determine model capabilities, defaulting to include thinking blocks",f)}let l=new dv(n,u);try{let f=await this.constructMessages(e),m=this.chainManager.chatModelManager.getChatModel()?.modelName;Eq({messages:f,modelName:m,contextEnvelope:e.contextEnvelope}),F(`Final Request to AI:
`,f);let h=await Vb(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:r.signal}));for await(let y of h){if(r.signal.aborted){F("Stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(y)}}catch(f){f.name==="AbortError"||r.signal.aborted?F("Stream aborted by user",{reason:r.signal.reason}):await this.handleError(f,l.processErrorChunk.bind(l))}let c=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(await this.handleResponse(c.content,e,r,o,n,void 0,void 0,d),c.content)}};mr();Bt();async function nPe(t,e){let r=`Given the following conversation and a follow up question,
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.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`,n=e.map(({role:o,content:i})=>`${o}: ${i}`).join(`
`);return await Vb(async()=>{let i=await(await ry.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0)).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]),a=Rte(i.content);return _ye(a)})}Xe();Xe();Fc();Ye();Xe();Bt();ND();f9();var oPe=class extends Ux{constructor(r,n,o){super();this.lc_namespace=["self_host_retriever"];this.app=r,this.backend=n,this.options={...o,minSimilarityScore:o.minSimilarityScore??.01,salientTerms:o.salientTerms??[],returnAll:o.returnAll??!1}}async getRelevantDocuments(r,n){try{if(!await this.backend.isAvailable())return Te("SelfHostRetriever: Backend is not available"),[];let a=kS(r,this.app.vault).map(f=>f.basename),s=[...new Set([...this.options.salientTerms||[],...a])],u=this.buildFilter(),l=this.options.returnAll?100:this.options.maxK,c=await this.backend.search(r,{limit:l,minScore:this.options.minSimilarityScore,filter:u});F(`SelfHostRetriever: Found ${c.length} results for query "${r.substring(0,50)}..."`);let d=this.convertToDocuments(c);return s.length>0?this.boostBySalientTerms(d,s):d}catch(o){return Te(`SelfHostRetriever: Search failed: ${o}`),[]}}buildFilter(){let r={};return this.options.timeRange&&(r.mtime={gte:this.options.timeRange.startTime,lte:this.options.timeRange.endTime}),this.options.tagTerms&&this.options.tagTerms.length>0&&(r.tags={containsAny:this.options.tagTerms}),Object.keys(r).length>0?r:void 0}convertToDocuments(r){return r.map(n=>new tl({pageContent:n.content,metadata:{...n.metadata,score:n.score,rerank_score:n.score,id:n.id,source:"self_host"}}))}boostBySalientTerms(r,n){return r.map(a=>{let s=a.pageContent.toLowerCase(),u=(a.metadata?.title||"").toLowerCase();if(n.some(c=>s.includes(c.toLowerCase())||u.includes(c.toLowerCase()))){let c=(a.metadata?.score||0)*1.1;return new tl({pageContent:a.pageContent,metadata:{...a.metadata,score:c,rerank_score:c,salientBoost:!0}})}return a}).sort((a,s)=>(s.metadata?.score||0)-(a.metadata?.score||0))}getBackend(){return this.backend}};ND();f9();Xe();BG();NOe();Ye();wH();var bPe=class extends Ux{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["miyo_semantic_retriever"];this.client=new S0,this.returnAll=!!n.returnAll,this.maxK=Math.max(1,n.maxK),this.minSimilarityScore=n.minSimilarityScore??.1}async getRelevantDocuments(r,n){let o=await this.searchMiyo(r),i=this.deduplicateResults(o);return te().debug&&this.logDebugInfo(r,o,i),i}async searchMiyo(r){try{let n=await this.client.resolveBaseUrl(te().selfHostUrl),o=this.returnAll?ec:this.maxK,i=this.buildSearchFilters();te().debug&&F("MiyoSemanticRetriever: search params:",{baseUrl:n,limit:o,maxK:this.maxK,minSimilarityScore:this.minSimilarityScore,returnAll:this.returnAll,filters:i});let s=(await this.client.search(n,zG(this.app),r,o,i)).results||[],u=s.filter(l=>this.isScoreAboveThreshold(l));return te().debug&&F(`MiyoSemanticRetriever: received ${s.length} results, ${u.length} after threshold`),u.map(l=>this.toDocument(l))}catch(n){return Te(`MiyoSemanticRetriever: search failed: ${n}`),[]}}buildSearchFilters(){if(!this.options.timeRange)return;let{startTime:r,endTime:n}=this.options.timeRange;return[{field:"mtime",gte:r,lte:n}]}toDocument(r){let n=r.metadata??{},o=n.chunkId||(r.chunk_index!==void 0?`${r.path}#${r.chunk_index}`:void 0),i=typeof r.score=="number"?r.score.toFixed(2):"?";return new tl({pageContent:r.chunk_text??"",metadata:{...n,score:r.score,explanation:`miyo ${i}`,path:r.path,mtime:r.mtime,ctime:r.ctime,title:r.title??"",id:r.id,embeddingModel:r.embedding_model,tags:r.tags??[],extension:r.extension,created_at:r.created_at,nchars:r.nchars,chunkId:o}})}isScoreAboveThreshold(r){let n=r.score;return typeof n!="number"||Number.isNaN(n)?!0:n>=this.minSimilarityScore}deduplicateResults(r){let n=new Map,o=i=>{let a=this.getDocumentKey(i);n.has(a)||n.set(a,i)};return r.forEach(o),te().debug&&n.size!==r.length&&F(`MiyoSemanticRetriever: deduplicated semantic results from ${r.length} to ${n.size}`),Array.from(n.values())}logDebugInfo(r,n,o){F("*** MIYO SEMANTIC RETRIEVER DEBUG INFO: ***"),F("
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)`,xti=`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)
- DO NOT write long descriptions - keep titles concise`;function H4r(t,e=!0){return e?`
<guidance>
${V4r}
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) 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 ![alt](image.png) 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 W4r(t,e=!0){return e?`
${V4r}
Source Catalog (for reference only):
${t}`:""}var Tti=20;function QDe(t,e,r=!0){if(!r||!e?.length||!t)return t||"";if(Oti(t))return t;let n=e.slice(0,Tti).map((o,i)=>{let a=(o.title||o.path||"Untitled").replace(/^\[\[|\]\]$/g,"");return`[^${i+1}]: [[${a}]]`}).join(`
`);return`${t}
#### Sources:
${n}`}function eje(t){if(!t)return"";let e=t.replace(/\[\^\d+\]/g,"");return e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,""),e=e.replace(/^\s*\[\^\d+\]:.*$/gm,""),e}function Oti(t){let e=t||"",r=/(^|\n)\s*#{1,6}\s*Sources\b/i.test(e),n=/(^|\n)\s*Sources\s*(?:[:-]\s*)?(\n|$)/i.test(e),o=/<summary[^>]*>\s*Sources\s*<\/summary>/i.test(e),i=/(^|\n)\s*\[\^\d+\]:\s*/.test(e);return r||n||o||i}function J4r(t){let e=t||"";return/\[\^\d+\]/.test(e)}function K4r(t=!0){return t?`
${xti}`:""}function Eti(t){let e=/([\s\S]*?)\n+(?:####\s*)?Sources\s*:?\s*\n+([\s\S]*)$/i,r=t.match(e);return r?{mainContent:r[1],sourcesBlock:(r[2]||"").trim()}:null}function Pti(t){return t.includes(`
`)||(t=t.replace(/\s*\[(\d+)\]\s*/g,`
[$1] `),t=t.replace(/\s+(\d+)\.\s/g,`
$1. `),t=t.trim()),t}function Mti(t){return t.split(`
`).map(e=>e.trim()).filter(e=>/^\[\^\d+\]:/.test(e))}function Rti(t,e){let r=new Map,n=new Set,o=[],i=/\[\^(\d+)\]/g,a;for(;(a=i.exec(t))!==null;){let s=parseInt(a[1],10);n.has(s)||(n.add(s),o.push(s))}if(o.length>0)o.forEach((s,u)=>r.set(s,u+1));else{let s=1;for(let u of e){let l=u.match(/^\[\^(\d+)\]:/);if(l){let c=parseInt(l[1],10);r.has(c)||r.set(c,s++)}}}return r}function Iti(t,e){let r=t,n;do n=!1,r=r.replace(/\[\^(\d+)\]/g,(o,i)=>{let a=parseInt(i,10),u=`[${e.get(a)??a}]`;return u!==o&&(n=!0),u}),r=r.replace(/\[\^(\d+(?:\s*,\s*\^?\d+)*)\]/g,(o,i)=>{let s=`[${i.split(",").map(u=>{let l=u.trim().replace(/^\^/,""),c=parseInt(l,10);return e.get(c)??c}).sort((u,l)=>u-l).map(u=>u.toString()).join(", ")}]`;return s!==o&&(n=!0),s});while(n);return r=r.replace(/\[(\d+)\]\./g,"[$1]"),r}function Ati(t,e){let r=[];return t.split(`
`).forEach(n=>{let o=n.match(/^\[\^(\d+)\]:\s*(.*)$/);if(!o)return;let i=parseInt(o[1],10),a=e.get(i)??i,s=o[2].match(/\[([^\]]+)\]\(([^)]+)\)/),u=o[2].match(/\[\[(.*?)\]\]/),l;if(s)l=`<a href="${s[2]}">${s[1]}</a>`;else if(u)l=`[[${u[1]}]]`;else{let c=o[2].match(/^(.*?)\]\s*\(([^)]+)\)\s*$/);if(c){let d=c[1].trim();l=`<a href="${c[2].trim()}">${d}</a>`}else l=o[2].replace(/\s*\([^)]*\)\s*$/,"")}r[a-1]=l}),r}function Nti(t){let e=[],r=new Set,n=new Map;return t.forEach((o,i)=>{if(!o)return;let a=o.match(/\[\[(.*?)\]\]/),s=a?a[1].toLowerCase():o.toLowerCase();if(!r.has(s))r.add(s),e.push(o),n.set(i+1,e.length);else{let u=e.findIndex(l=>{let c=l.match(/\[\[(.*?)\]\]/);return(c?c[1].toLowerCase():l.toLowerCase())===s});u>=0&&n.set(i+1,u+1)}}),{uniqueItems:e,consolidationMap:n}}function Dti(t,e){return e.size===0?t:t.replace(/\[(\d+(?:\s*,\s*\d+)*)\]/g,(r,n)=>`[${n.split(/\s*,\s*/).map(a=>{let s=parseInt(a,10);return String(e.get(s)||s)}).join(", ")}]`)}function jti(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function $ti(t){return t!=null}function Lti(t){let e=t.split(`
`),r=[];return e.forEach(n=>{let o=n.trim();if(!o)return;let i=o.replace(/^<li>/i,"").replace(/<\/li>$/i,"").replace(/^[-*]\s*/,"").trim();if(!i)return;let a=i.match(/\[([^\]]+)\]\(([^)]+)\)/),s=i.match(/\[\[(.*?)\]\]/),u;a?u=`<a href="${a[2]}">${a[1]}</a>`:s?u=`[[${s[1]}]]`:u=jti(i),r.push({index:r.length+1,html:u})}),r}function z4r(t,e){let r=e.filter(o=>o.html.trim().length>0);if(r.length===0)return t;let n=r.map(({index:o,html:i})=>`<li class="copilot-sources__item"><span class="copilot-sources__index">[${o}]</span><span class="copilot-sources__text">${i}</span></li>`).join(`
`);return`${t}
<br/>
<details class="copilot-sources"><summary class="copilot-sources__summary">Sources</summary>
<ul class="copilot-sources__list">
${n}
</ul>
</details>`}function G4r(t,e=!0){if(!e)return t;let r=Eti(t);if(!r)return t;let{mainContent:n,sourcesBlock:o}=r;o=Pti(o);let i=Mti(o);if(i.length===0){let d=Lti(o);return z4r(n,d)}let a=Rti(n,i);n=Iti(n,a);let s=Ati(o,a),{uniqueItems:u,consolidationMap:l}=Nti(s);l.size>0&&(n=Dti(n,l),s=u);let c=s.map((d,f)=>d?{index:f+1,html:d}:null).filter($ti);return z4r(n,c)}function tje(t){return t.map(e=>{let r=e.title||e.path||"Untitled",n=e.path||r;return`- [[${r}]] (${n})`})}ra();var Cle=class extends jD{async run(e,r,n,o,i){let a=te(),s=B_(),u=!1;try{u=!qS(s,a.activeModels).capabilities?.includes("reasoning")}catch(p){F("Could not determine model capabilities, defaulting to include thinking blocks",p)}let l=new dv(n,u);try{let p=e.contextEnvelope;if(!p)throw new Error("[VaultQA] Context envelope is required but not available. Cannot proceed with VaultQA chain.");let h=p.layers.find(re=>re.id==="L5_USER")?.text||e.message,y=this.extractTagTerms(h);F("[VaultQA] Extracted tags before condensing:",y);let g=this.chainManager.memoryManager.getMemory(),b=await g.loadMemoryVariables({}),_=gye(b),w=h;_.length>0&&(F("[VaultQA] Condensing query with chat history for better retrieval"),w=await nPe(h,_),F("[VaultQA] Standalone question:",w));let T=te(),O=y.length>0,P=await new VU(app,{salientTerms:O?[...y]:[],maxK:Ly,returnAll:O}).getRelevantDocuments(w),R=lT.isMiyoActive(),I=await lT.createRetriever(app,{minSimilarityScore:.01,maxK:Ly,salientTerms:O?[...y]:[],tagTerms:y,returnAll:O},R?{enableMiyo:!1,enableSemanticSearchV3:!1}:{}),N=I.retriever;F(`VaultQA: Using ${I.type} retriever - ${I.reason}`);let z=await N.getRelevantDocuments(w),{filterResults:V,searchResults:k}=TX(P,z),X=[...V,...k],B=X.length>Ly,Q=X.slice(0,Ly);this.chainManager.storeRetrieverDocuments(Q);let Y=Q.map(re=>{let Z=re.metadata?.title||"Untitled",le=re.metadata?.path||Z;return`<${CWe}>
<title>${Z}</title>
<path>${le}</path>
<content>
${eje(re.pageContent)}
</content>
</${CWe}>`}).join(`
`),K=[],oe=this.chainManager.chatModelManager.getChatModel(),ue=Q.slice(0,Math.max(5,Math.min(20,Q.length))).map(re=>({title:re.metadata?.title||re.metadata?.path||"Untitled",path:re.metadata?.path||re.metadata?.title||""})),de=tje(ue).join(`
`),L=B?`
IMPORTANT: The retrieval limit of ${Ly} documents was reached. ${X.length-Ly} additional matching documents were omitted. Inform the user: "Note: The retrieval cap was reached \u2014 some matching documents were not included. Upgrade to Copilot Plus for more complete answers."`:"",W=`
Answer the question based only on the following context:
`+Y+W4r(de,T.enableInlineCitations)+L;F("[VaultQA] Using envelope-based context construction with LayerToMessagesConverter");let ie=_A.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),j=ie.find(re=>re.role==="system");j&&K.push({role:Mte(oe),content:j.content}),await Oq(g,K);let A=ie.find(re=>re.role==="user");if(A){let re=W+`
`+A.content;if(e.content&&Array.isArray(e.content)){let Z=e.content.map(le=>le.type==="text"?{...le,text:re}:le);K.push({role:"user",content:Z})}else K.push({role:"user",content:re})}let U=oe?.modelName;Eq({messages:K,modelName:U,contextEnvelope:e.contextEnvelope}),F(`Final Request to AI:
`,K);let H=await Vb(()=>this.chainManager.chatModelManager.getChatModel().stream(K,{signal:r.signal}));for await(let re of H){if(r.signal.aborted){F("VaultQA stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(re)}}catch(p){p.name==="AbortError"||r.signal.aborted?F("VaultQA stream aborted by user",{reason:r.signal.reason}):await this.handleError(p,l.processErrorChunk.bind(l))}let c=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};if(r.signal.aborted&&r.signal.reason==="new-chat")return n(""),"";let f=this.addSourcestoResponse(c.content);return await this.handleResponse(f,e,r,o,n,void 0,void 0,d),f}addSourcestoResponse(e){let r=te();if(!J4r(e))return e;let n=this.chainManager.getRetrievedDocuments(),o=T1t(n).map(i=>({title:i}));return QDe(e,o,r.enableInlineCitations)}extractTagTerms(e){return h9(e)}};var OX=["@vault","@websearch","@composer","@memory"];mr();Xe();Fc();Ye();Ye();mr();Xe();XC();XC();Ye();var Qw=pF(),HU=bc([]),$mt=bc(""),X4r=bc(!1);function rje(){return L_(HU,{store:Qw})}function Z4r(){return u1($mt,{store:Qw})}function EX(){return Qw.get(HU)}function G3(){return Qw.get($mt)}function nje(t){Qw.set(HU,t)}function X3(t){let e=Qw.get(HU),r=e.findIndex(n=>n.title===t.title);if(r!==-1){let n=[...e];n[r]=t,Qw.set(HU,n)}else Qw.set(HU,[...e,t])}function PX(t){let e=Qw.get(HU);Qw.set(HU,e.filter(r=>r.title!==t))}function WU(t){Qw.set($mt,t)}function xle(t){Qw.set(X4r,t)}function Tle(){return Qw.get(X4r)}var Lmt=new Set;function JU(t){Lmt.add(t)}function KU(t){Lmt.delete(t)}function C$(t){return Lmt.has(t)}function oje(){return te().defaultSystemPromptTitle}function Y4r(){let t=EX(),e=G3();if(e){let n=t.find(o=>o.title===e);if(n)return n.content}let r=oje();if(r){let n=t.find(o=>o.title===r);if(n)return n.content}return""}function Q4r(){let t=oje();WU(t)}function Fmt(){xle(!1),WU("")}function ije(){return Y4r()||te()?.userSystemPrompt||""}function x$(){let t=ije();if(Tle())return t;let r=L1t;return t?`${r}
<user_custom_instructions>
${t}
</user_custom_instructions>`:r}async function T$(t){let e=x$();if(!t)return F("No UserMemoryManager provided to getSystemPromptWithMemory"),e;let r=await t.getUserMemoryPrompt();return r?`${r}
${e}`:e}var MX=require("obsidian");$r();Xe();Ye();function cT(){}cT.prototype={diff:function(e,r){var n,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=o.callback;typeof o=="function"&&(i=o,o={});var a=this;function s(w){return w=a.postProcess(w,o),i?(setTimeout(function(){i(w)},0),!0):w}e=this.castInput(e,o),r=this.castInput(r,o),e=this.removeEmpty(this.tokenize(e,o)),r=this.removeEmpty(this.tokenize(r,o));var u=r.length,l=e.length,c=1,d=u+l;o.maxEditLength!=null&&(d=Math.min(d,o.maxEditLength));var f=(n=o.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+f,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],r,e,0,o);if(m[0].oldPos+1>=l&&h+1>=u)return s(e2r(a,m[0].lastComponent,r,e,a.useLongestToken));var y=-1/0,g=1/0;function b(){for(var w=Math.max(y,-c);w<=Math.min(g,c);w+=2){var T=void 0,O=m[w-1],E=m[w+1];O&&(m[w-1]=void 0);var P=!1;if(E){var R=E.oldPos-w;P=E&&0<=R&&R<u}var I=O&&O.oldPos+1<l;if(!P&&!I){m[w]=void 0;continue}if(!I||P&&O.oldPos<E.oldPos?T=a.addToPath(E,!0,!1,0,o):T=a.addToPath(O,!1,!0,1,o),h=a.extractCommon(T,r,e,w,o),T.oldPos+1>=l&&h+1>=u)return s(e2r(a,T.lastComponent,r,e,a.useLongestToken));m[w]=T,T.oldPos+1>=l&&(g=Math.min(g,w-1)),h+1>=u&&(y=Math.max(y,w+1))}c++}if(i)(function w(){setTimeout(function(){if(c>d||Date.now()>p)return i();b()||w()},0)})();else for(;c<=d&&Date.now()<=p;){var _=b();if(_)return _}},addToPath:function(e,r,n,o,i){var a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===r&&a.removed===n?{oldPos:e.oldPos+o,lastComponent:{count:a.count+1,added:r,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:r,removed:n,previousComponent:a}}},extractCommon:function(e,r,n,o,i){for(var a=r.length,s=n.length,u=e.oldPos,l=u-o,c=0;l+1<a&&u+1<s&&this.equals(n[u+1],r[l+1],i);)l++,u++,c++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return c&&!i.oneChangePerToken&&(e.lastComponent={count:c,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=u,l},equals:function(e,r,n){return n.comparator?n.comparator(e,r):e===r||n.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join("")},postProcess:function(e){return e}};function e2r(t,e,r,n,o){for(var i=[],a;e;)i.push(e),a=e.previousComponent,delete e.previousComponent,e=a;i.reverse();for(var s=0,u=i.length,l=0,c=0;s<u;s++){var d=i[s];if(d.removed)d.value=t.join(n.slice(c,c+d.count)),c+=d.count;else{if(!d.added&&o){var f=r.slice(l,l+d.count);f=f.map(function(p,m){var h=n[c+m];return h.length>p.length?h:p}),d.value=t.join(f)}else d.value=t.join(r.slice(l,l+d.count));l+=d.count,d.added||(c+=d.count)}}return i}var Jps=new cT;function t2r(t,e){var r;for(r=0;r<t.length&&r<e.length;r++)if(t[r]!=e[r])return t.slice(0,r);return t.slice(0,r)}function r2r(t,e){var r;if(!t||!e||t[t.length-1]!=e[e.length-1])return"";for(r=0;r<t.length&&r<e.length;r++)if(t[t.length-(r+1)]!=e[e.length-(r+1)])return t.slice(-r);return t.slice(-r)}function kmt(t,e,r){if(t.slice(0,e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't start with prefix ").concat(JSON.stringify(e),"; this is a bug"));return r+t.slice(e.length)}function qmt(t,e,r){if(!e)return t+r;if(t.slice(-e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't end with suffix ").concat(JSON.stringify(e),"; this is a bug"));return t.slice(0,-e.length)+r}function Ole(t,e){return kmt(t,e,"")}function aje(t,e){return qmt(t,e,"")}function n2r(t,e){return e.slice(0,Fti(t,e))}function Fti(t,e){var r=0;t.length>e.length&&(r=t.length-e.length);var n=e.length;t.length<e.length&&(n=t.length);var o=Array(n),i=0;o[0]=0;for(var a=1;a<n;a++){for(e[a]==e[i]?o[a]=o[i]:o[a]=i;i>0&&e[a]!=e[i];)i=o[i];e[a]==e[i]&&i++}i=0;for(var s=r;s<t.length;s++){for(;i>0&&t[s]!=e[i];)i=o[i];t[s]==e[i]&&i++}return i}var sje="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\
`));var r=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var o=0;o<n.length;o++){var i=n[o];o%2&&!e.newlineIsToken?r[r.length-1]+=i:r.push(i)}return r};cje.equals=function(t,e,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
`))&&(t=t.trim()),(!r.newlineIsToken||!e.includes(`
`))&&(e=e.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
`)&&(t=t.slice(0,-1)),e.endsWith(`
`)&&(e=e.slice(0,-1))),cT.prototype.equals.call(this,t,e,r)};function i2r(t,e,r){var n=Uti(r,{ignoreWhitespace:!0});return cje.diff(t,e,n)}var Bti=new cT;Bti.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var zti=new cT;zti.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Umt(t){"@babel/helpers - typeof";return Umt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Umt(t)}var Ele=new cT;Ele.useLongestToken=!0;Ele.tokenize=cje.tokenize;Ele.castInput=function(t,e){var r=e.undefinedReplacement,n=e.stringifyReplacer,o=n===void 0?function(i,a){return typeof a>"u"?r:a}:n;return typeof t=="string"?t:JSON.stringify(Bmt(t,null,null,o),o," ")};Ele.equals=function(t,e,r){return cT.prototype.equals.call(Ele,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function Bmt(t,e,r,n,o){e=e||[],r=r||[],n&&(t=n(o,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var a;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),a=new Array(t.length),r.push(a),i=0;i<t.length;i+=1)a[i]=Bmt(t[i],e,r,n,o);return e.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),Umt(t)==="object"&&t!==null){e.push(t),a={},r.push(a);var s=[],u;for(u in t)Object.prototype.hasOwnProperty.call(t,u)&&s.push(u);for(s.sort(),i=0;i<s.length;i+=1)u=s[i],a[u]=Bmt(t[u],e,r,n,u);e.pop(),r.pop()}else a=t;return a}var uje=new cT;uje.tokenize=function(t){return t.slice()};uje.join=uje.removeEmpty=function(t){return t};function a2r(t,e,r){return uje.diff(t,e,r)}Or();var O$=require("obsidian"),Ft=$(J()),u2r=$(jm());Cn();var Ple=$(J());$r();var dT=Ple.forwardRef(({checked:t=!1,onCheckedChange:e,disabled:r=!1,className:n,...o},i)=>{let a=()=>{r||e?.(!t)},s=u=>{r||(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),e?.(!t))};return Ple.createElement("div",{role:"switch","aria-checked":t,"aria-disabled":r,"data-state":t?"checked":"unchecked","data-disabled":r?"":void 0,ref:i,tabIndex:r?-1:0,className:we("tw-relative tw-inline-flex tw-h-5.5 tw-w-10 tw-shrink-0 tw-cursor-pointer tw-items-center tw-rounded-full tw-transition-colors","focus-visible:tw-outline-none focus-visible:tw-ring-2 focus-visible:tw-ring-ring focus-visible:tw-ring-offset-2",t?"tw-bg-interactive-accent":"tw-bg-[--background-modifier-border-hover]",r&&"tw-cursor-not-allowed tw-opacity-50",n),onClick:a,onKeyDown:s,...o},Ple.createElement("div",{className:we("tw-pointer-events-none tw-block tw-size-4 tw-rounded-full tw-bg-toggle-thumb tw-shadow-lg tw-ring-0 tw-transition-transform",t?"tw-translate-x-5.5":"tw-translate-x-0.5")}))});dT.displayName="SettingSwitch";function s2r(t){let e=[],r=[];return t.forEach(n=>{n.added||n.removed?r.push(n):(r.length>0&&(e.push(r),r=[]),e.push([n]))}),r.length>0&&e.push(r),e}Bt();function Vti(t,e){let r=o=>o.split(/(\s+)/).filter(Boolean);return a2r(r(t),r(e)).map(o=>({value:o.value.join(""),added:o.added,removed:o.removed}))}function Mle(t){let e=t.split(`
`);return e.length>0&&e[e.length-1]===""&&e.pop(),e}function l2r(t){let e=[],r=0;for(;r<t.length;){let n=t[r];if(!n.added&&!n.removed)Mle(n.value).forEach(o=>{e.push({original:o,modified:o,isUnchanged:!0})}),r++;else if(n.removed){let o=t[r+1];if(o?.added){let i=Mle(n.value),a=Mle(o.value),s=Math.max(i.length,a.length);for(let u=0;u<s;u++)e.push({original:i[u]??null,modified:a[u]??null,isUnchanged:!1});r+=2}else Mle(n.value).forEach(i=>{e.push({original:i,modified:null,isUnchanged:!1})}),r++}else n.added&&Mle(n.value).forEach(o=>{e.push({original:null,modified:o,isUnchanged:!1})}),r++}return e}var c2r=(0,Ft.memo)(({original:t,modified:e,side:r})=>{let n=Vti(t,e);return Ft.default.createElement("span",null,n.map((o,i)=>{if(r==="original"){if(o.removed)return Ft.default.createElement("span",{key:i,className:"tw-bg-error tw-text-error"},o.value);if(o.added)return null}else{if(o.added)return Ft.default.createElement("span",{key:i,className:"tw-bg-success tw-text-success"},o.value);if(o.removed)return null}return Ft.default.createElement("span",{key:i},o.value)}))});c2r.displayName="WordDiffSpan";var Rle=(0,Ft.memo)(({row:t,side:e})=>{let r=e==="original"?t.original:t.modified,n=e==="original"?t.modified:t.original;return r===null?Ft.default.createElement("span",{className:"tw-text-muted"},"\xA0"):t.isUnchanged?Ft.default.createElement("span",{className:"tw-text-normal"},r||"\xA0"):n!==null?Ft.default.createElement(c2r,{original:t.original,modified:t.modified,side:e}):Ft.default.createElement("span",{className:e==="original"?"tw-bg-error tw-text-error":"tw-bg-success tw-text-success"},r||"\xA0")});Rle.displayName="DiffCell";var Ile="obsidian-copilot-apply-view",dje=class extends O$.ItemView{constructor(r){super(r);this.root=null;this.state=null;this.result=null}getViewType(){return Ile}getDisplayText(){return"Preview Changes"}async setState(r){this.state=r,this.render()}async onOpen(){this.render()}async onClose(){this.root&&(this.root.unmount(),this.root=null),this.state?.resultCallback?.(this.result?this.result:"aborted")}render(){if(!this.state)return;let r=this.containerEl.children[1];r.empty();let n=r.createDiv();this.root||(this.root=(0,u2r.createRoot)(n)),this.root.render(Ft.default.createElement(Hti,{app:this.app,state:this.state,close:o=>{this.result=o,this.leaf.detach()}}))}},d2r=(0,Ft.memo)(({block:t})=>{let e=(0,Ft.useMemo)(()=>l2r(t),[t]);return Ft.default.createElement("div",{className:"tw-grid tw-grid-cols-2 tw-gap-2"},Ft.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((r,n)=>Ft.default.createElement("div",{key:n,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Ft.default.createElement(Rle,{row:r,side:"original"})))),Ft.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((r,n)=>Ft.default.createElement("div",{key:n,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Ft.default.createElement(Rle,{row:r,side:"modified"})))))});d2r.displayName="SideBySideBlock";var f2r=(0,Ft.memo)(({block:t})=>{let e=t.some(n=>n.added||n.removed),r=(0,Ft.useMemo)(()=>l2r(t),[t]);return e?Ft.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ft.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Ft.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Original"),Ft.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},r.map((n,o)=>n.original!==null?Ft.default.createElement("div",{key:o},Ft.default.createElement(Rle,{row:n,side:"original"})):null))),Ft.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Ft.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Modified"),Ft.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},r.map((n,o)=>n.modified!==null?Ft.default.cr
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:wt.union([wt.string(),wt.object({}).passthrough()]).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
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
Required edge fields: id, fromNode, toNode
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
All IDs must be unique. Edge nodes must reference existing node IDs.
Example:
{
"nodes": [
{"id": "1", "type": "text", "text": "Hello", "x": 0, "y": 0, "width": 200, "height": 50},
{"id": "2", "type": "file", "file": "note.md", "subpath": "#heading", "x": 250, "y": 0, "width": 200, "height": 100, "color": "2"},
{"id": "3", "type": "group", "label": "Group", "x": 0, "y": 100, "width": 300, "height": 150}
],
"edges": [
{"id": "e1-2", "fromNode": "1", "toNode": "2", "fromSide": "right", "toSide": "left", "color": "3", "label": "links to"}
]
}`),confirmation:wt.preprocess(t=>{if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t},wt.boolean()).optional().default(!0).describe("(Optional) Whether to ask for change confirmation with preview UI before writing changes. Default: true. Set to false to skip preview and apply changes immediately.")}),fje=cc({name:"writeToFile",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:Wti,func:async({path:t,content:e,confirmation:r=!0})=>{let n=D1t(t);n!==t&&(Te(`Filename too long, truncated for filesystem compatibility: "${t}" \u2192 "${n}"`),t=n);let o=typeof e=="string"?e:JSON.stringify(e,null,2);if(te().autoAcceptEdits||r===!1)try{let u=await p2r(t);return await app.vault.modify(u,o),{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(u){return{result:"failed",message:`Error writing to file without preview: ${u?.message||u}`}}let s=await m2r(t,o);return{result:s,message:`File change result: ${s}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}}),Jti=wt.object({path:wt.string().describe("(Required) The path of the file to modify (relative to the root of the vault and include the file extension)."),diff:wt.string().describe(`(Required) One or more SEARCH/REPLACE blocks. Each block MUST follow this exact format with these exact markers:
------- SEARCH
[exact content to find, including all whitespace and indentation]
=======
[new content to replace with]
+++++++ REPLACE
WHEN TO USE THIS TOOL vs writeToFile:
- Use replaceInFile for: small edits, fixing typos, updating specific sections, targeted changes
- Use writeToFile for: creating new files, major rewrites, when you can't identify specific text to replace
CRITICAL RULES:
1. SEARCH content must match EXACTLY - every character, space, and line break
2. Use the exact markers: "------- SEARCH", "=======", "+++++++ REPLACE"
3. For multiple changes, include multiple SEARCH/REPLACE blocks in order
4. Keep blocks concise - include only the lines being changed plus minimal context
COMMON MISTAKES TO AVOID:
- Wrong: Using different markers like "---- SEARCH" or "SEARCH -------"
- Wrong: Including too many unchanged lines
- Wrong: Not matching whitespace/indentation exactly`)});function Ale(t){return t.replace(/\r\n/g,`
`).replace(/\r/g,`
`)}function Kti(t,e,r){let n=(t.match(/\r\n/g)||[]).length,o=(t.match(/(?<!\r)\n/g)||[]).length,i=n>o,a=Ale(t),s=Ale(e),u=Ale(r),l=a.replaceAll(s,u);return i?l.replace(/\n/g,`\r
`):l}var h2r=cc({name:"replaceInFile",description:"Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a LARGE file.",schema:Jti,func:async({path:t,diff:e})=>{let r=app.vault.getAbstractFileByPath(t);if(!r||!(r instanceof MX.TFile))return`File not found at path: ${t}. Please check the file path and try again.`;try{let n=await app.vault.read(r),o=n;if(n.length<3e3)return"File is too small to use this tool. Please use writeToFile instead.";let a=Gti(e);if(a.length===0)return`No valid SEARCH/REPLACE blocks found in diff. Please use the correct format with ------- SEARCH, =======, and +++++++ REPLACE markers.
diff: ${e}`;let s=0;for(let c of a){let{searchText:d,replaceText:f}=c,p=Ale(o),m=Ale(d);if(!p.includes(m))if(p.includes(m.trimEnd()))d=d.trimEnd(),f=f.trimEnd();else return`Search text not found in file ${t} : "${d}".`;let h=o;o=Kti(o,d,f),o!==h&&s++}if(n===o)return`No changes made to ${t}. The search text was not found or replacement resulted in identical content. Call writeToFile instead`;if(te().autoAcceptEdits)try{return await app.vault.modify(r,o),{result:"accepted",blocksApplied:s,message:`Applied ${s} SEARCH/REPLACE block(s) without preview. Do not call this tool again to modify this file in response to the current user request.`}}catch(c){return{result:"failed",blocksApplied:s,message:`Error applying changes without preview: ${c?.message||c}`}}let l=await m2r(t,o);return{result:l,blocksApplied:s,message:`Applied ${s} SEARCH/REPLACE block(s) (replacing all occurrences). Result: ${l}. Do not call this tool again to modify this file in response to the current user request.`}}catch(n){return`Error performing SEARCH/REPLACE on ${t}: ${n}. Please check the file path and diff format and try again.`}}});function Gti(t){let e=[],r=/-{3,}\s*SEARCH\s*(?:\r?\n)?/,n=/(?:\r?\n)?={3,}\s*(?:\r?\n)?/,o=/(?:\r?\n)?\+{3,}\s*REPLACE/,i=new RegExp(r.source+"([\\s\\S]*?)"+n.source+"([\\s\\S]*?)"+o.source,"g"),a;for(;(a=i.exec(t))!==null;){let s=a[1].trim(),u=a[2].trim();e.push({searchText:s,replaceText:u})}return e}Xe();var zmt=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@composer":return"Edit existing notes or create new notes.";case"@memory":return"Save information to user memory";default:return""}},E$=class{static async callTool(e,r){if(!e)throw new Error("Tool is undefined");let n=await e.call(r);return n??(Te(`[ToolCall] Tool "${e.name}" returned null/undefined`),null)}};function g2r(t){let e=t.trim();if(!e)return"note";let r=e.match(/^\[\[([\s\S]+?)\]\]$/),n=r?r[1]:e,[o="",i=""]=n.split("|"),a=i.trim();if(a.length>0)return a;let s=o.trim(),[u]=s.split("#"),l=(u||s).trim()||e,c=l.split("/").filter(Boolean),d=c.length>0?c[c.length-1]:l;return d.replace(/\.[^/.]+$/,"")||d||"note"}var y2r=180;function Xti(t){let e=t.trim();return e.length<=y2r?e:`${e.slice(0,y2r)}\u2026`}function Zti(t){if(!t||typeof t!="object")return null;let e=typeof t.status=="string"?t.status:null,r=typeof t.message=="string"&&t.message.trim().length>0?Xti(t.message):null,n=typeof t.notePath=="string"?t.notePath:"",i=(typeof t.noteTitle=="string"&&t.noteTitle.trim().length>0?t.noteTitle.trim():g2r(n))||g2r(n);if(e==="invalid_path")return r??`\u26A0\uFE0F Invalid note path "${i}"`;if(e==="not_found")return r??`\u26A0\uFE0F Note "${i}" not found`;if(e==="not_unique"){let c=Array.isArray(t.candidates)?t.candidates.length:0;return r||(c>0?`\u26A0\uFE0F Multiple matches for "${i}" (${c} candidates)`:`\u26A0\uFE0F Multiple matches for "${i}"`)}if(e==="empty")return r??`\u26A0\uFE0F "${i}" contains no readable content`;if(e==="out_of_range"){if(r)return r;let c=typeof t.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,d=typeof t.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:null;if(d!==null&&c!==null){let f=Math.max(c-1,0);return`\u26A0\uFE0F Chunk ${d} exceeds available range (max index ${f})`}return"\u26A0\uFE0F Requested chunk is out of range"}let a=typeof t.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:0,s=typeof t.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,u=!!t.hasMore,l=[`\u2705 Read "${i||"note"}"`];return s&&s>0?l.push(`chunk ${a+1} of ${s}`):l.push(`chunk ${a+1}`),u&&l.push("more available"),l.join(" \xB7 ")}var P$=class{static format(e,r){try{let n=r;if(typeof n=="string"&&n.startsWith("ENC:"))try{n=decodeURIComponent(n.slice(4))}catch{}let o;try{o=JSON.parse(n)}catch{o=n}switch(e){case"localSearch":return this.formatLocalSearch(o);case"webSearch":return this.formatWebSearch(o);case"youtubeTranscription":return this.formatYoutubeTranscription(o);case"writeToFile":
No matching notes found.`;let r=e.length,n=e.slice(0,10),o=n.some(s=>typeof s?.rerank_score=="number"||typeof s?.score=="number"||s?.source),i=n.map((s,u)=>o?this.formatSearchItem(s,u):this.formatBasicSearchItem(s,u)).join(`
`),a=r>10?`
... and ${r-10} more results`:"";return`\u{1F4DA} Found ${r} relevant notes
Top results:
${i}${a}`}static formatLocalSearch(e){if(typeof e=="string"){let n=e.match(/<localSearch[^>]*>([\s\S]*)<\/localSearch>/);if(n){let o=n[1].trim(),i=o.match(/<document>/g);if((i?i.length:0)===0)return`\u{1F4DA} Found 0 relevant notes
No matching notes found.`;let s=[],u=/<document>([\s\S]*?)<\/document>/g,l;for(;(l=u.exec(o))!==null;){let c=l[1],d=c.match(/<title>([\s\S]*?)<\/title>/),f=c.match(/<path>([\s\S]*?)<\/path>/),p=c.match(/<modified>([\s\S]*?)<\/modified>/),m=(d?.[1]||"Untitled").trim(),h=(f?.[1]||"").trim(),y=(p?.[1]||"").trim();s.push({title:m,path:h,mtime:y||null})}return this.formatLocalSearchDocuments(s)}}let r=this.parseSearchResults(e);return Array.isArray(r)?r.length===0?typeof e=="string"&&!e.includes("<localSearch")&&!e.includes('"type":"local_search"')?e:`\u{1F4DA} Found 0 relevant notes
No matching notes found.`:this.formatLocalSearchDocuments(r):typeof e=="string"?e:JSON.stringify(e,null,2)}static parseSearchResults(e){if(typeof e=="object"&&e!==null)return e.type==="local_search"&&Array.isArray(e.documents)?e.documents:[];if(typeof e=="string"){try{let r=JSON.parse(e);if(r&&r.type==="local_search"&&Array.isArray(r.documents))return r.documents}catch{}return[]}return[]}static formatSearchItem(e,r){let n=e.path?.split("/").pop()?.replace(/\.md$/,"")||e.title||"Untitled",o=e.rerank_score||e.score||0,i=typeof o=="number"?o.toFixed(4):o,a=e.source==="time-filtered"?"Recency":"Relevance",s=[`${r+1}. ${n}`];if(e.source==="time-filtered"){if(e.mtime)try{let l=new Date(e.mtime),c=isNaN(l.getTime())?String(e.mtime):l.toISOString();s.push(` \u{1F552} Modified: ${c}${e.includeInContext?" \u2713":""}`)}catch{s.push(` \u{1F552} Modified: ${String(e.mtime)}${e.includeInContext?" \u2713":""}`)}}else e.source==="title-match"?s.push(` \u{1F516} Title match${e.includeInContext?" \u2713":""}`):s.push(` \u{1F4CA} ${a}: ${i}${e.includeInContext?" \u2713":""}`);let u=this.extractContentSnippet(e.content);return u&&s.push(` \u{1F4AC} "${u}${e.content?.length>150?"...":""}"`),e.path&&!e.path.endsWith(`/${n}.md`)&&s.push(` \u{1F4C1} ${e.path}`),s.join(`
`)}static formatBasicSearchItem(e,r){let n=e.title||e.path||`Result ${r+1}`,o=[`${r+1}. ${n}`],i=e.mtime||e.modified||e.modified_at||e.updated_at;return i&&o.push(` \u{1F552} Modified: ${String(i)}`),e.path&&e.path!==n&&o.push(` \u{1F4C1} ${e.path}`),o.join(`
`)}static extractContentSnippet(e,r=150){return e?(e.match(/NOTE BLOCK CONTENT:\s*([\s\S]*)/)?.[1]||e).substring(0,r).replace(/\s+/g," ").trim():""}static formatWebSearch(e){if(Array.isArray(e)&&e.length>0&&e[0].type==="web_search"){let r=["\u{1F310} Web Search Results"],n=e[0];return n.content&&(r.push(""),r.push(n.content)),n.citations&&n.citations.length>0&&(r.push(""),r.push("Sources:"),n.citations.forEach((o,i)=>{r.push(`[${i+1}] ${o}`)})),n.instruction&&(r.push(""),r.push(`Note: ${n.instruction}`)),r.join(`
`)}if(typeof e=="string"){let r=e.split(`
`),n=["\u{1F310} Web Search Results"],o=!1,i=[],a=[];for(let s of r){if(s.includes("Sources:")){o=!0;continue}o?a.push(s):s.includes("Here are the web search results")||i.push(s)}return i.length>0&&(n.push(""),n.push(...i.filter(s=>s.trim()))),a.length>0&&(n.push(""),n.push("Sources:"),a.forEach(s=>{s.trim()&&n.push(s)})),n.join(`
`)}return e}static formatYoutubeTranscription(e){let r;if(typeof e=="string")try{r=JSON.parse(e)}catch{return e}else if(typeof e=="object")r=e;else return String(e);if(r.success===!1)return`\u{1F4FA} YouTube Transcription Failed
${r.message}`;if(r.results&&Array.isArray(r.results)){let n=[`\u{1F4FA} YouTube Transcripts (${r.total_urls} video${r.total_urls>1?"s":""})`];n.push("");for(let o of r.results){if(o.success){n.push(`\u{1F4F9} Video: ${o.url}`),n.push("");let i=o.transcript.split(`
`),a=0;for(let s of i)if(s.trim()&&(s.match(/^\[(\d+:\d+)\]/)?(a>0&&n.push(""),n.push(`\u23F0 ${s}`)):n.push(` ${s.trim()}`),a++,a>30)){n.push(""),n.push("... (transcript truncated for display)");break}o.elapsed_time_ms&&(n.push(""),n.push(`Processing time: ${(o.elapsed_time_ms/1e3).toFixed(1)}s`))}else n.push(`\u274C Failed to transcribe: ${o.url}`),n.push(` ${o.message}`);n.push(""),n.push("---"),n.push("")}return n.join(`
`).trimEnd()}if(r.transcript){let n=["\u{1F4FA} YouTube Transcript"];n.push("");let o=r.transcript.split(`
`),i=0;for(let a of o)if(a.trim()&&(a.match(/^\[(\d+:\d+)\]/)?(i>0&&n.push(""),n.push(`\u23F0 ${a}`)):n.push(` ${a.trim()}`),i++,i>50)){n.push(""),n.push("... (transcript truncated for display)");break}return r.elapsed_time_ms&&(n.push(""),n.push(`Processing time: ${(r.elapsed_time_ms/1e3).toFixed(1)}s`)),n.join(`
`)}return typeof e=="object"?JSON.stringify(e,null,2):String(e)}static formatWriteToFile(e){let r=typeof e=="object"?e.result:e,n=String(r).toLowerCase();return n.includes("accepted")?"\u2705 File change: accepted":n.includes("rejected")?"\u274C File change: rejected":typeof e=="object"&&e.message?e.message:String(r)}static formatReplaceInFile(e){let r=0,n="";if(typeof e=="object")r=e.blocksApplied||0,n=e.result||"";else if(typeof e=="string"){let i=e.match(/Applied (\d+) SEARCH\/REPLACE block/);i&&(r=parseInt(i[1])),n=e}let o=String(n).toLowerCase();if(o.includes("accepted")){let i=r===1?"replacement":"replacements";return r>0?`\u2705 ${r} ${i} accepted`:"\u2705 File replacements: accepted"}else if(o.includes("rejected"))return r===0?"\u274C No replacements made":"\u274C File replacements: rejected";return typeof e=="object"&&e.message?e.message:String(n)}static formatReadNote(e){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{r=null}let n=Zti(r);return n||(typeof e=="string"?e:JSON.stringify(e,null,2))}};Ye();ob();function Yti(t){return"children"in t&&"path"in t}function Qti(t){return"path"in t&&!("children"in t)}function eri(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function Vmt(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=el();for(let u of t.children)if(Qti(u)){if(Hs(u,i,a)){e&&r.push(u.name);let l=eri(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(Yti(u)){let l=Vmt(u,e);if(Object.keys(l).length>0&&(o[u.name]=l[u.name],l[u.name].extensionCounts))for(let[c,d]of Object.entries(l[u.name].extensionCounts))n[c]=(n[c]||0)+d}let s={};return Object.keys(n).length>0&&(s.extensionCounts=n),e&&r.length>0&&(s.files=r),Object.keys(o).length>0&&(s.subFolders=o),Object.keys(s).length===0?{}:t.name?{[t.name]:s}:{vault:s}}var b2r=t=>cc({name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:wt.object({}),func:async()=>{let e=Vmt(t,!0),r=`A JSON represents the file tree as a nested structure:
* 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
`,n=JSON.stringify(e);if(n.length>5e5){let o=Vmt(t,!1);return r+JSON.stringify(o)}return r+n}});var RX=require("obsidian");Xe();Ye();Bt();ta();var GU=class{constructor(e){this.recentConversationsContent="";this.savedMemoriesContent="";this.isUpdatingMemory=!1;this.app=e}async loadMemory(){try{let e=this.app.vault.getAbstractFileByPath(this.getRecentConversationFilePath());e instanceof RX.TFile?this.recentConversationsContent=await this.app.vault.read(e):(this.recentConversationsContent="",F("[UserMemoryManager] Recent Conversations file not found, skipping memory load"));let r=this.app.vault.getAbstractFileByPath(this.getSavedMemoriesFilePath());r instanceof RX.TFile?this.savedMemoriesContent=await this.app.vault.read(r):(this.savedMemoriesContent="",F("[UserMemoryManager] Saved Memories file not found, skipping saved memory load"))}catch(e){ne("[UserMemoryManager] Error reading memory files:",e),this.recentConversationsContent="",this.savedMemoriesContent=""}}addRecentConversation(e,r){if(!te().enableRecentConversations){Te("[UserMemoryManager] Recent history referencing is disabled, skipping analysis");return}if(e.length===0){Te("[UserMemoryManager] No messages to analyze for user memory");return}this.updateMemory(e,r).catch(o=>{ne("[UserMemoryManager] Background user memory operation failed:",o)})}async updateSavedMemory(e,r){if(!te().enableSavedMemory)return{error:"Saved memory is disabled, skipping save"};if(!e||e.trim()==="")return{error:"No content provided for saved memory"};if(!r)return{error:"No chat model available, skipping save"};try{return await this.ensureMemoryFolderExists(),await this.updateSavedMemoryFile(this.getSavedMemoriesFilePath(),e,r)}catch(o){return{error:"Error saving memory: "+o.message}}}async getUserMemoryPrompt(){await this.loadMemory();try{let e=te(),r="";return e.enableRecentConversations&&this.recentConversationsContent&&(r+=`<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&&(r+=`<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.`),r.length>0?r:null}catch(e){return ne("[UserMemoryManager] Error reading user memory content:",e),null}}getTimestamp(){let e=new Date,r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0");return`${r}-${n}-${o} ${i}:${a}`}async createConversationSection(e,r){let{title:n,summary:o}=await this.extractTitleAndSummary(e,r),i=this.getTimestamp(),a=`## ${n}
`;return a+=`**Time:** ${i}
`,a+=`**Summary:** ${o}
`,a}async updateMemory(e,r){if(this.isUpdatingMemory){F("[UserMemoryManager] Memory update already in progress, skipping.");return}this.isUpdatingMemory=!0;try{if(await this.ensureMemoryFolderExists(),!r){ne("[UserMemoryManager] No chat model available, skipping memory update");return}if(e.length===0){F("[UserMemoryManager] No messages available, skipping memory update");return}let n=await this.createConversationSection(e,r);await this.addToRecentConversationsFile(this.getRecentConversationFilePath(),n)}catch(n){ne("[UserMemoryManager] Error analyzing chat messages for user memory:",n)}finally{this.isUpdatingMemory=!1}}async ensureMemoryFolderExists(){let r=te().memoryFolderName;await $c(r)}getRecentConversationFilePath(){return`${te().memoryFolderName}/Recent Conversations.md`}getSavedMemoriesFilePath(){return`${te().memoryFolderName}/Saved Memories.md`}async updateSavedMemoryFile(e,r,n){let o=this.app.vault.getAbstractFileByPath(e),i=o instanceof RX.TFile?await this.app.vault.read(o):"";if(!n)return{error:"No chat model available, skipping memory update"};let a=`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
...
`,s=`<current_memories>
${i.trim()}
</current_memories>
<new_statement>
${r.trim()}
</new_statement>
`,u=[new Od(a),new qs(s)],l=null;try{l=(await n.invoke(u)).text??""}catch(c){return{error:"LLM call failed while updating saved memories: "+c.message}}return l==null||l.trim()===""?{error:"Empty content returned from LLM"}:(o instanceof RX.TFile?await this.app.vault.modify(o,l):await this.app.vault.create(e,l),{content:l})}async addToRecentConversationsFile(e,r){let n=this.app.vault.getAbstractFileByPath(e);if(n instanceof RX.TFile){let o=await this.app.vault.read(n),i;if(o.trim()==="")i=`${r.trim()}
`;else{let a=this.parseExistingConversations(o);a.push(r);let u=te().maxRecentConversations;a.length>u&&a.splice(0,a.length-u),i=`${a.map(c=>c.trim()).join(`
`)}
`}await this.app.vault.modify(n,i)}else{let o=`${r.trim()}
`;await this.app.vault.create(e,o)}}parseExistingConversations(e){let r=e.split(`
`),n=[],o=[];for(let i of r)i.trim().startsWith("## ")?(o.length>0&&n.push(o.join(`
`).trim()),o=[i]):o.length>0&&o.push(i);return o.length>0&&n.push(o.join(`
`).trim()),n}extractJsonFromResponse(e){let r=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);if(r)return r[1].trim();let n=e.match(/\{[\s\S]*\}/);return n?n[0]:e}async extractTitleAndSummary(e,r){let n=e.map(s=>`${s.sender}: ${s.message}`).join(`
`),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>
${n}
</conversation_text>
Generate a title and summary for this conversation:`,a=[new Od(o),new qs(i)];try{let u=(await r.invoke(a)).text,l=this.extractJsonFromResponse(u);try{let c=JSON.parse(l);return{title:c.title||"Untitled Conversation",summary:c.summary||"No summary available"}}catch(c){return ne("[UserMemoryManager] Failed to parse LLM response as JSON:",c),{title:"Untitled Conversation",summary:"Summary generation failed"}}}catch(s){return ne("[UserMemoryManager] Failed to extract title and summary:",s),{title:"Untitled Conversation",summary:"Summary generation failed"}}}};Xe();CX();var tri=wt.object({statement:wt.string().min(1).describe("The user statement for explicitly updating saved memories")}),pje=cc({name:"updateMemory",description:"Update the user memory when the user explicitly asks to update the memory",schema:tri,func:async({statement:t})=>{try{let e=new GU(app),r=tC.getInstance().getChatModel(),n=await e.updateSavedMemory(t,r);return n.error?{success:!1,message:n.error}:{success:!0,message:`Memory updated successfully into ${e.getSavedMemoriesFilePath()}: ${n.content}`}}catch(e){return ne("[updateMemoryTool] Error updating memory:",e),{success:!1,message:`Failed to save memory: ${e.message}`}}}});var Nle=require("obsidian");Xe();var Hmt=200;function mje(t){return t.replace(/\\/g,"/").toLowerCase()}function rri(t){return t.replace(/\.[^/.]+$/,"")}function nri(t,e){if(e.length===0)return!1;let n=mje(t).split("/").filter(Boolean);if(n.length<e.length)return!1;let o=n.slice(-e.length);for(let i=0;i<e.length;i+=1){let a=e[i];if(!a)return!1;let s=o[i];if(i===o.length-1){let u=rri(s);if(!s.includes(a)&&!u.includes(a))return!1}else if(!s.includes(a))return!1}return!0}function Wmt(t){return/\.[^/]+$/.test(t)}async function ori(t){let e=b=>{let _=app.vault.getAbstractFileByPath(b);return _ instanceof Nle.TFile?_:null},r=t.trim(),n=r.match(/^\s*\[\[([\s\S]+?)\]\]\s*$/),i=(n?n[1]:r).trim(),[a]=i.split("|"),[s]=a.split("#"),u=s.trim(),l=Array.from(new Set([r,i,u].map(b=>b.trim()).filter(Boolean)));for(let b of l){let _=e(b);if(_)return{type:"resolved",file:_};if(!Wmt(b))for(let w of[".md",".canvas"]){let T=e(`${b}${w}`);if(T)return{type:"resolved",file:T}}}let c=app.metadataCache,d=u.trim();if(c&&d){let b=new Set([d]);if(!Wmt(d))for(let _ of[".md",".canvas"])b.add(`${d}${_}`);for(let _ of b){let w=c.getFirstLinkpathDest?.(_,"");if(w instanceof Nle.TFile)return{type:"resolved",file:w}}}if(!d)return{type:"not_found"};let f=app.vault.getMarkdownFiles?.()??[];if(f.length===0)return{type:"not_found"};let p=mje(d),m=new Set([p]);if(!Wmt(d))for(let b of[".md",".canvas"])m.add(mje(`${d}${b}`));for(let b of f){let _=mje(b.path);if(m.has(_))return{type:"resolved",file:b}}let h=d.split("/").pop();if(h){let b=h.toLowerCase(),_=f.filter(w=>w.basename.toLowerCase()===b);if(_.length===1)return{type:"resolved",file:_[0]};if(_.length>1)return{type:"not_unique",matches:_}}let y=p.split("/").filter(Boolean);if(y.length===0)return{type:"not_found"};let g=f.filter(b=>nri(b.path,y));return g.length===1?{type:"resolved",file:g[0]}:g.length>1?{type:"not_unique",matches:g}:{type:"not_found"}}async function iri(t){try{return await app.vault.cachedRead(t)}catch(e){return Te(`readNote: failed to read ${t.path}`,e),""}}function ari(){let t=new Map,e=app.vault.getMarkdownFiles?.()??[];for(let r of e)if(r instanceof Nle.TFile){let n=t.get(r.basename)??[];n.push(r),t.set(r.basename,n)}return t}function sri(t,e,r){let n=t.trim();if(!n)return[];let o=new Map,i=app.metadataCache.getFirstLinkpathDest?.(n,e);if(i instanceof Nle.TFile&&o.set(i.path,i),!/\.[^./]+$/.test(n)){let a=n.split("/").pop()??n,s=r.get(a)??[];for(let u of s)o.set(u.path,u)}return Array.from(o.values())}function uri(t,e){if(!t)return[];let r=/\[\[([^\]]+)\]\]/g,n=new Map,o=null,i;for(;(i=r.exec(t))!==null;){if(i.index>0&&t[i.index-1]==="!")continue;let a=i[1]?.trim();if(!a)continue;let[s,u]=a.split("|"),[l,c]=s.split("#"),d=l?.trim();if(!d)continue;let f=`${d}|${u??""}|${c??""}`;if(n.has(f))continue;o||(o=ari());let p=sri(d,e.path,o);n.set(f,{linkText:d,displayText:u?.trim()||d,section:c?.trim()||void 0
`).trimEnd(),heading:d})}return i}var cri=wt.object({notePath:wt.string().min(1).describe("Full path to the note (relative to the vault root) that needs to be read, such as 'Projects/plan.md'."),chunkIndex:wt.preprocess(t=>{if(typeof t=="string"){let e=t.trim();if(e.length===0)return;let r=Number(e);return Number.isFinite(r)?r:t}return t},wt.number().int().min(0)).optional().describe("0-based chunk index to read. Omit to read the first chunk.")}),_2r=cc({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:cri,func:async({notePath:t,chunkIndex:e=0})=>{let r=t.trim();if(r.startsWith("/"))return{notePath:r,status:"invalid_path",message:"Provide the note path relative to the vault root without a leading slash."};let n=await ori(r);if(n.type==="not_found")return Te(`readNote: note not found or not a file (${r})`),{notePath:r,status:"not_found",message:`Note "${r}" was not found or is not a readable file.`};if(n.type==="not_unique")return Te(`readNote: ambiguous note path "${r}" matched multiple files`,n.matches.map(f=>f.path)),{notePath:r,status:"not_unique",message:`Multiple notes match "${r}". Provide a more specific path.`,candidates:n.matches.map(f=>({path:f.path,title:f.basename}))};let o=n.file,i=o.path,a=await iri(o),s=lri(o,a),u=s.length;if(u===0)return{notePath:i,status:"empty",message:`No readable content was found in "${i}".`};if(e>=u)return{notePath:i,status:"out_of_range",message:`Chunk index ${e} exceeds available chunks (last index ${u-1}).`,totalChunks:u};let l=s[e];F(`readNote: returning chunk ${l.chunkIndex} of ${u} for ${i}`);let c=l.chunkIndex<u-1,d=uri(l.content,o);return{notePath:i,noteTitle:o.basename,heading:l.heading,chunkId:l.id,chunkIndex:l.chunkIndex,totalChunks:u,hasMore:c,nextChunkIndex:c?l.chunkIndex+1:null,content:l.content,mtime:o.stat.mtime,linkedNotes:d.length>0?d:void 0}}});mr();mA();Xe();Fc();Ye();Xe();Fc();Ye();Bt();async function Jmt(t,e,r){try{if(!t||!t.name)return{toolName:t?.name||"unknown",result:"Error: Invalid tool call - missing tool name",success:!1};let o=e.find(c=>c.name===t.name);if(!o){let c=e.map(d=>d.name).join(", ");return{toolName:t.name,result:`Error: Tool '${t.name}' not found. Available tools: ${c}. Make sure you have the tool enabled in the Agent settings.`,success:!1}}let a=yd.getInstance().getToolMetadata(t.name);if(a?.isPlusOnly&&!await E0()&&!o_())return{toolName:t.name,result:`Error: ${hje(t.name)} requires a Copilot Plus subscription`,success:!1};let s={...t.args};a?.requiresUserMessageContent&&r&&(s._userMessageContent=r);let u=12e4;typeof a?.timeoutMs=="number"&&(u=a.timeoutMs);let l;return!u||u===1/0?l=await E$.callTool(o,s):l=await Promise.race([E$.callTool(o,s),new Promise((c,d)=>setTimeout(()=>d(new Error(`Tool execution timed out after ${u}ms`)),u))]),l==null?(Te(`Tool ${t.name} returned null/undefined result`),{toolName:t.name,result:JSON.stringify({message:"Tool executed but returned no result",status:"empty"}),success:!0}):{toolName:t.name,result:typeof l=="string"?l:JSON.stringify(l),success:!0}}catch(o){let i=zr(o);return i.includes("schema")?ne(`[ToolCall] Schema validation failed for "${t.name}". Args: ${JSON.stringify(t.args,null,2)}`):ne(`[ToolCall] Error executing "${t.name}": ${i}`),{toolName:t.name,result:`Error: ${i}`,success:!1}}}function hje(t){return t==="localSearch"?te().enableSemanticSearchV3?"vault search (semantic)":"vault search (index-free)":{webSearch:"web search",getFileTree:"file tree",getCurrentTime:"current time",getTimeRangeMs:"time range",getTimeInfoByEpoch:"time info",convertTimeBetweenTimezones:"timezone converter",startPomodoro:"pomodoro timer",pomodoroTool:"pomodoro timer",youtubeTranscription:"YouTube transcription",indexVault:"vault indexing",indexTool:"index",writeToFile:"file editor",replaceInFile:"file editor"}[t]||t}function Kmt(t){return{localSearch:"\u{1F50D}",webSearch:"\u{1F310}",getFileTree:"\u{1F4C1}",getCurrentTime:"\u{1F552}",getTimeRangeMs:"\u{1F4C5}",getTimeInfoByEpoch:"\u{1F570}\uFE0F",convertTimeBetw
`+`Semantic search index has been refreshed with ${r} documents.`,documentCount:r}}catch(e){return{success:!1,message:`Failed to index with semantic search: ${e.message}`}}else return{success:!0,message:"Tiered lexical retriever uses on-demand indexing. No manual indexing required."}}}),pri=wt.object({query:wt.string().min(1).describe("The search query to search the internet"),chatHistory:wt.array(wt.object({role:wt.enum(["user","assistant"]),content:wt.string()})).describe("Previous conversation turns for context (usually empty array)")}),yje=cc({name:"webSearch",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",schema:pri,func:async({query:t,chatHistory:e})=>{try{let r=await nPe(t,e),n,o;if(o_()&&nvr()){let a=await ovr(r);n=a.content,o=a.citations}else{let a=await Ql.getInstance().webSearch(r);n=a.response.choices[0].message.content,o=a.response.citations||[]}return[{type:"web_search",content:n,citations:o,instruction:K4r()}]}catch(r){return console.error(`Error processing web search query ${t}:`,r),{error:`Web search failed: ${r}`}}}});var eht=5e5,mri=500,v2r=50,hri=wt.object({includeInline:wt.boolean().optional().describe("Include inline tags in addition to frontmatter tags. Defaults to true."),maxEntries:wt.number().int().min(1).max(5e3).optional().describe("Maximum number of tag entries to return, sorted by occurrences. Responses are capped at ~500KB.")}).describe("Parameters for retrieving the tag list.");function gri(){return typeof app>"u"||!app?.metadataCache?null:app.metadataCache}function w2r(t){let e={};if(!t)return e;for(let[r,n]of Object.entries(t)){let o=r?.trim();if(!o)continue;let i=o.replace(/^#+/,"").trim().toLowerCase();if(!i)continue;let a=`#${i}`;if(a==="#")continue;let s=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;e[a]=(e[a]||0)+s}return e}function yri(t,e,r){let n=t,o=w2r(n.getFrontmatterTags?.()),i=e?w2r(n.getTags?.()):{},a=new Set([...Object.keys(o),...e?Object.keys(i):[]]),s=[],u=0;for(let c of a){let d=o[c]??0,f=e?Math.max(0,i[c]??0):0,p=0,m=d;e&&(f>=d?(p=f-d,m=f):f>0&&(p=f,m=d+p)),m!==0&&(u+=m,s.push({tag:c,occurrences:m,frontmatterOccurrences:d,inlineOccurrences:p}))}s.sort((c,d)=>d.occurrences===c.occurrences?c.tag.localeCompare(d.tag):d.occurrences-c.occurrences);let l=s.slice(0,r);return{totalUniqueTags:s.length,returnedTagCount:l.length,totalOccurrences:u,includedSources:e?["frontmatter","inline"]:["frontmatter"],truncated:l.length<s.length,tags:l}}function bri(t){let e=t,r=JSON.stringify(e);if(r.length<=eht)return e;let n=e.tags.length;for(;r.length>eht&&n>v2r;)n=Math.max(v2r,Math.floor(n/2)),e={...e,tags:t.tags.slice(0,n),returnedTagCount:n,truncated:!0},r=JSON.stringify(e);return r.length>eht?{totalUniqueTags:t.totalUniqueTags,returnedTagCount:0,totalOccurrences:t.totalOccurrences,includedSources:t.includedSources,truncated:!0,tags:[],note:"Tag list exceeded the size limit. Request a narrower scope or specify a smaller maxEntries value."}:e}function S2r(t){return`A JSON object lists the vault tags and their occurrence counts:
* 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 C2r=()=>cc({name:"getTagList",description:"Get the list of tags in the vault with occurrence statistics.",schema:hri,func:async t=>{let e=gri(),r=t?.includeInline??!0,n=t?.maxEntries??mri;if(!e)return S2r({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 o=yri(e,r,n),i=bri(o);return S2r(i)}});var E2r=$(x2r(),1),Dle=$(ZU(),1);var ts;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(ts||(ts={}));var Cm;(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"})(Cm||(Cm={}));var eS;(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"})(eS||(eS={}));function T2r(t,e){e=e.add(1,"day"),Z3(t,e),IX(t,e)}function fT(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function bje(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",ts.AM):t.assign("meridiem",ts.PM)}function Z3(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function IX(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var iht=$(ZU(),1);var _ri={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=>O2r(t,eS.MARCH,Cm.SUNDAY,2),dstEnd:t=>O2r(t,eS.OCTOBER,Cm.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=>YU(t,eS.MARCH,Cm.SUNDAY,2,2),dstEnd:t=>YU(t,eS.NOVEMBER,Cm.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=>YU(t,eS.MARCH,Cm.SUNDAY,2,2),dstEnd:t=>YU(t,eS.NOVEMBER,Cm.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=>YU(t,eS.MARCH,Cm.SUNDAY,2,2),dstEnd:t=>YU(t,eS.NOVEMBER,Cm.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=>YU(t,eS.MARCH,Cm.SUNDAY,2,2),dstEnd:t=>YU(t,eS.NOVEMBER,Cm.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
tags: ${JSON.stringify(Array.from(this._tags).sort())},
knownValues: ${JSON.stringify(this.knownValues)},
impliedValues: ${JSON.stringify(this.impliedValues)}},
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,Dle.default)(this.date())}date(){let e=this.dateWithoutTimezoneAdjustment(),r=this.reference.getSystemTimezoneAdjustmentMinute(e,this.get("timezoneOffset"));return new Date(e.getTime()+r*6e4)}addTag(e){return this._tags.add(e),this}addTags(e){for(let r of e)this._tags.add(r);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let e=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return e.setFullYear(this.get("year")),e}static createRelativeFromReference(e,r){let n=(0,Dle.default)(e.instant);for(let i in r)n=n.add(r[i],i);let o=new t(e);return r.hour||r.minute||r.second?(bje(o,n),fT(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(IX(o,n),e.timezoneOffset!==null&&o.imply("timezoneOffset",-e.instant.getTimezoneOffset()),r.d?(o.assign("day",n.date()),o.assign("month",n.month()+1),o.assign("year",n.year())):r.week?(o.assign("day",n.date()),o.assign("month",n.month()+1),o.assign("year",n.year()),o.imply("weekday",n.day())):(o.imply("day",n.date()),r.month?(o.assign("month",n.month()+1),o.assign("year",n.year())):(o.imply("month",n.month()+1),r.year?o.assign("year",n.year()):o.imply("year",n.year())))),o}},M$=class t{constructor(e,r,n,o,i){this.reference=e,this.refDate=e.instant,this.index=r,this.text=n,this.start=o||new rs(e),this.end=i}clone(){let e=new t(this.reference,this.index,this.text);return e.start=this.start?this.start.clone():null,e.end=this.end?this.end.clone():null,e}date(){return this.start.date()}tags(){let e=new Set(this.start.tags());if(this.end)for(let r of this.end.tags())e.add(r);return e}toString(){let e=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(e)} ...}]`}};function aht(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function vri(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function py(t){return`(?:${vri(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var P2r=$(ZU(),1);function vje(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function eB(t,e,r){let n=(0,P2r.default)(t),o=n;o=o.month(r-1),o=o.date(e),o=o.year(n.year());let i=o.add(1,"y"),a=o.add(-1,"y");return Math.abs(i.diff(n))<Math.abs(o.diff(n))?o=i:Math.abs(a.diff(n))<Math.abs(o.diff(n))&&(o=a),o.year()}var lht={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},cht={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},rC={...cht,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},sht={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},uht={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},R2r={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},jle={s:"second",sec:"second",second:"second",seconds:"second",m:"mi
EXAMPLES OF CORRECT USAGE:
- "what time is it" \u2192 No parameter (uses local time)
- "what time is it in Tokyo" \u2192 timezoneOffset: "+9"
- "what time is it in Beijing" \u2192 timezoneOffset: "+8"
- "what time is it in New York" \u2192 timezoneOffset: "-5" (or "-4" during DST)
- "what time is it in Mumbai" \u2192 timezoneOffset: "+5:30"
SUPPORTED FORMATS:
- Simple: "+8", "-5", "+5:30"
- With prefix: "UTC+8", "GMT-5", "UTC+5:30"
COMMON TIMEZONE OFFSETS:
- Tokyo: UTC+9
- Beijing/Singapore: UTC+8
- Mumbai: UTC+5:30
- Dubai: UTC+4
- London: UTC+0 (UTC+1 during BST)
- New York: UTC-5 (UTC-4 during DST)
- Los Angeles: UTC-8 (UTC-7 during DST)`)}),func:async({timezoneOffset:t})=>eii(t)}),RHr={jan:1,january:1,feb:2,february:2,mar:3,march:3,apr:4,april:4,may:5,jun:6,june:6,jul:7,july:7,aug:8,august:8,sep:9,sept:9,september:9,oct:10,october:10,nov:11,november:11,dec:12,december:12};function tii(t,e){let r=t.match(/^(last|past|previous|prior)\s+(\d+)\s+(days?|weeks?|months?|years?)$/i);if(!r)return;let[,,n,o]=r,i=parseInt(n);if(i<=0)return;let a=o.replace(/s$/,""),s=e.startOf("day");return{start:s.minus({[a+"s"]:i}),end:s}}function rii(t,e){switch(t){case"yesterday":return{start:e.minus({days:1}).startOf("day"),end:e.minus({days:1}).endOf("day")};case"last week":return{start:e.minus({weeks:1}).startOf("week"),end:e.minus({weeks:1}).endOf("week")};case"this week":return{start:e.startOf("week"),end:e.endOf("week")};case"next week":return{start:e.plus({weeks:1}).startOf("week"),end:e.plus({weeks:1}).endOf("week")};case"last month":return{start:e.minus({months:1}).startOf("month"),end:e.minus({months:1}).endOf("month")};case"this month":return{start:e.startOf("month"),end:e.endOf("month")};case"next month":return{start:e.plus({months:1}).startOf("month"),end:e.plus({months:1}).endOf("month")};case"last year":return{start:e.minus({years:1}).startOf("year"),end:e.minus({years:1}).endOf("year")};case"this year":return{start:e.startOf("year"),end:e.endOf("year")};case"next year":return{start:e.plus({years:1}).startOf("year"),end:e.plus({years:1}).endOf("year")};case"last quarter":return{start:e.minus({quarters:1}).startOf("quarter"),end:e.minus({quarters:1}).endOf("quarter")};case"this quarter":return{start:e.startOf("quarter"),end:e.endOf("quarter")};case"next quarter":return{start:e.plus({quarters:1}).startOf("quarter"),end:e.plus({quarters:1}).endOf("quarter")}}}function nii(t,e){let r=t.match(/(?:the\s+)?week\s+of\s+(.+)/i);if(!r)return;let n=r[1],o=yht(n,e.toJSDate(),{forwardDate:!1});if(o.length===0)return;let i=$n.fromJSDate(o[0].start.date()).startOf("week"),a=i.endOf("week");return i>e&&(i=i.minus({years:1}),a=a.minus({years:1})),{start:i,end:a}}function oii(t,e){let r=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)$/i);if(!r)return;let n=RHr[r[1]],o=e.year;n>e.month&&o--;let i=$n.fromObject({year:o,month:n,day:1}),a=i.endOf("month");return i>e&&(i=i.minus({years:1}),a=a.minus({years:1})),{start:i,end:a}}function iii(t,e){let r=t.match(/^(?:(?:the\s+)?(?:year|yr)(?:\s+(?:of|in))?\s+)?(\d{4})$/i);if(!r)return;let n=parseInt(r[1]),o=$n.fromObject({year:n,month:1,day:1}),i=$n.fromObject({year:n,month:12,day:31});return o>e&&(o=o.minus({years:1}),i=i.minus({years:1})),{start:o,end:i}}function aii(t,e){let r=t.match(/^(?:(?:q|Q)(\d{1})\s+(\d{4})|(\d{4})\s+(?:q|Q)(\d{1}))$/),n=t.match(/^(?:q|Q)(\d{1})$/),o,i;if(r)o=parseInt(r[1]||r[4]),i=parseInt(r[2]||r[3]);else if(n){o=parseInt(n[1]),i=e.year;let l=Math.floor((e.month-1)/3)+1;o>l&&i--}else return;if(o<1||o>4)return;let a=(o-1)*3+1,s=$n.fromObject({year:i,month:a,day:1}).startOf("day"),u=s.plus({months:3}).minus({days:1}).endOf("day");return s>e&&(s=s.minus({years:1}),u=u.minus({years:1})),{start:s,end:u}}function sii(t,e){let r=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\s+(\d{4})$/i);if(!r)return;let n=RHr[r[1].toLowerCase()],o=parseInt(r[2]),i=$n.fromObject({year:o,month:n,day:1}).startOf("day"),a=i.endOf("month");return i>e&&(i=i.minus({years:1}),a=a.minus({years:1})),{start:i,end:a}}function uii(t){let e=$n.now(),r=t.toLowerCase().replace("@vault","").trim(),n=tii(r,e)||rii(r,e)||nii(r,e)||oii(r,e)||sii(r,e)||aii(r,e)||iii(r,e);if(n)return{startTime:n.start.toMillis(),endTime:n.end.toMillis()};let o=yht(t,e.toJSDate(),{forwardDate:!1});if(o.length>0){let i=$n.fromJSDate(o[0].start.date()).startOf("day"),a=o[0].end?$n.fromJSDate(o[0].end.date()).endOf("day"):i.endOf("day");return i>e&&(i.minus({years:1}),a.minus({years:1})),{startTime:i.toMillis(),endTime:a.toMillis()}}consol
COMMON EXPRESSIONS:
- Relative past: "yesterday", "last week", "last month", "last year"
- Relative ranges: "this week", "this month", "this year"
- Specific dates: "July 1", "July 1 2023", "2023-07-01"
- Date ranges: "from July 1 to July 15", "between May and June"
- Time periods: "last 7 days", "past 30 days", "previous 3 months"
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=uii(t);return e||{error:`Unable to parse time expression: ${t}`}}});function cii(t){let e=t.toString().length===10?t*1e3:t,r=$n.fromMillis(e);return lii(r)}var AHr=cc({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:wt.object({epoch:wt.number().describe("Unix timestamp in seconds or milliseconds")}),func:async({epoch:t})=>cii(t)});async function dii(t,e,r){let n=rgt(e),o=rgt(r);try{let i=$n.now().setZone(n),a=bVr(t,i.toJSDate());if(!a)throw new Error(`Could not parse time: ${t}`);let s=$n.fromJSDate(a,{zone:n}),u=s.setZone(o);if(!u.isValid)throw new Error("Invalid timezone conversion");let l=u.toJSDate(),c=u.offset;return{epoch:Math.floor(l.getTime()),isoString:l.toISOString(),userLocaleString:u.toLocaleString($n.DATETIME_FULL),localDateString:u.toISODate()||"",timezoneOffset:c,timezone:u.offsetNameShort||o,originalTime:s.toLocaleString($n.TIME_SIMPLE)+" "+s.offsetNameShort,convertedTime:u.toLocaleString($n.TIME_SIMPLE)+" "+u.offsetNameShort}}catch(i){throw new Error(`Failed to convert time: ${i.message}`)}}var NHr=cc({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:wt.object({time:wt.string().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:wt.string().describe(`Source UTC offset. Must be numeric, not timezone name.
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:wt.string().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" \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"
- "convert 3:30 PM EST to London time" \u2192 time: "3:30 PM", fromOffset: "-5", toOffset: "+0"
- "what is 9am Beijing time in New York" \u2192 time: "9am", fromOffset: "+8", toOffset: "-5"`)}),func:async({time:t,fromOffset:e,toOffset:r})=>dii(t,e,r)});mA();Fc();Ye();Bt();var DHr=5e4,jHr=cc({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:wt.object({_userMessageContent:wt.string().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>DHr)return{success:!1,message:`Input too long: Maximum allowed length is ${DHr} characters`};let r=M1t(e);if(r.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 n=await Promise.all(r.map(async i=>{try{let a=o_()&&te().supadataApiKey?await JEe(i):await Ql.getInstance().youtube4llm(i);return a.response.transcript?{url:i,success:!0,transcript:a.response.transcript,elapsed_time_ms:a.elapsed_time_ms}:{url:i,success:!1,message:"Transcript not available. Only English videos with auto transcript enabled are supported"}}catch(a){return console.error(`Error transcribing YouTube video ${i}:`,a),{url:i,success:!1,message:"An error occurred while transcribing the YouTube video"}}}));return{success:n.some(i=>i.success),results:n,total_urls:r.length}}});var fii=[{tool:gje,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 \u22650.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 \u2192 try "ML models", "neural networks", or "AI techniques"
Examples:
- Query "piano learning practice" \u2192 query: "piano learning practice", salientTerms: ["piano", "learning", "practice"]
- Query "#projectx status update" \u2192 query: "#projectx status update", salientTerms: ["#projectx", "status", "update"]
- Query "\u94A2\u7434\u5B66\u4E60" (Chinese) \u2192 query: "\u94A2\u7434\u5B66\u4E60", salientTerms: ["\u94A2\u7434", "\u5B66\u4E60"] (preserve original language)
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 exhaustive "find all" searches:
- Set returnAll: true when the user wants ALL matching notes (e.g., "find all my X", "list every Y", "show me all Z", "how many notes about W")
- Keep returnAll: false (or omit) for normal questions seeking specific information
- When setting returnAll: true, also call getFileTree to get all note titles as reference. This helps verify search completeness and identify notes the search may have missed.`}},{tool:yje,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:
* "web search", "internet search", "online search"
* "Google", "search online", "look up online", "search the web"
- Always provide an empty chatHistory array
Example: "search the web for python tutorials" \u2192 query: "python tutorials", chatHistory: []`}},{tool:MHr,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) \u2192 call with no parameters
- "what time is it in Tokyo" (UTC+9) \u2192 timezoneOffset: "+9"
- "what time is it in New York" (UTC-5 or UTC-4 depending on DST) \u2192 timezoneOffset: "-5"`}},{tool:AHr,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:IHr,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" \u2192 timeExpression: "last week"`}},{tool:NHr,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) \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"`}},{tool:_2r,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\u2014do 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:fje,metadata:{id:"writeToFile",displayName:"Write to File",description:"Create or modify files in your vault",category:"file",requiresVault:!0,timeoutMs:0,copilotCommands:["@composer"],customPromptInstructions:`For writeToFile:
- 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 writeToFile for any intent of updating or creating files
- Do not call writeToFile tool again if the result is not accepted
- Do not call writeToFile 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:h2r,metadata:{id:"replaceInFile",displayName:"Replace in File",description:"Make targeted changes to existing files using SEARCH/REPLACE blocks",category:"file",requiresVault:!0,timeoutMs:0,customPromptInstructions:`For replaceInFile:
- Remember: Small edits \u2192 replaceInFile, Major rewrites \u2192 writeToFile
- SEARCH text must match EXACTLY including all whitespace
- The diff parameter uses SEARCH/REPLACE block format
Example: To add "Bob Johnson" to attendees list in notes/meeting.md:
path: "notes/meeting.md"
diff: "------- SEARCH\\n## Attendees\\n- John Smith\\n- Jane Doe\\n=======\\n## Attendees\\n- John Smith\\n- Jane Doe\\n- Bob Johnson\\n+++++++ REPLACE"`}},{tool:jHr,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 pii(t){yd.getInstance().register({tool:b2r(t.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" \u2192 call getFileTree to get the exact folder path
- "Create a new note using the quick note template" \u2192 call getFileTree to look up the template path
- "How many files are in the projects folder" \u2192 call getFileTree to list all files`}})}function mii(){yd.getInstance().register({tool:C2r(),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 hii(){yd.getInstance().register({tool:pje,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 eZ(t){let e=yd.getInstance(),r=te(),n=e.getToolMetadata("getFileTree")!==void 0,o=t!==void 0,i=e.getToolMetadata("updateMemory")!==void 0,a=r.enableSavedMemory;(e.getAllTools().length===0||n!==o||i!==a)&&(e.clear(),e.registerAll(fii),t&&(pii(t),mii()),r.enableSavedMemory&&hii())}Bt();Bt();var Hje=class{constructor(e,r){this.toolManager=e;this.writeToFileTool=r;this.buffer=""}findCompleteBlock(e){let r=/<writeToFile>[\s\S]*?<\/writeToFile>/,n=e.match(r);return!n||n.index===void 0?null:{block:n[0],endIdx:n.index+n[0].length}}async*processChunk(e){let r="";if(Array.isArray(e.content))for(let o of e.content)o.type==="text"&&o.text!=null&&(r+=o.text);else e.content!=null&&(r=e.content);r&&(this.buffer+=r),yield e;let n=this.findCompleteBlock(this.buffer);for(;n;){let{block:o,endIdx:i}=n,a=o.match(/<path>([\s\S]*?)<\/path>/),s=o.match(/<content>([\s\S]*?)<\/content>/),u=a?a[1].trim():void 0,l=s?s[1].trim():void 0;try{let c=await this.toolManager.callTool(this.writeToFileTool,{path:u,content:l}),d=P$.format("writeToFile",c);yield{...e,content:`
${d}
`}}catch(c){yield{...e,content:`
Error: ${c?.message||c}
`}}this.buffer=this.buffer.substring(i),n=this.findCompleteBlock(this.buffer)}}};Xe();function $Hr(t){if(!Array.isArray(t)||t.length===0)return{high:0,medium:0,low:0,total:0,averageScore:0};let e=0,r=0,n=0,o=0;for(let i of t){let a=i.rerank_score??i.score??0;o+=a,a>=.7?e++:a>=.3?r++:n++}return{high:e,medium:r,low:n,total:t.length,averageScore:o/t.length}}function LHr(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 ogt(t){if(!Array.isArray(t))return"";let e=t.filter(n=>n.includeInContext!==!1);return e.length===0?"No relevant documents found.":e.map((n,o)=>{let i=n.title||"Untitled",a=n.path||"",s=n.__sourceId||n.collection_name||n.source_id||o+1,u=null;if(n.mtime){let l=new Date(n.mtime);isNaN(l.getTime())||(u=l.toISOString())}return`<document>
<id>${s}</id>
<title>${i}</title>${a&&a!==i?`
<path>${a}</path>`:""}${u?`
<modified>${u}</modified>`:""}
<content>
${n.content||""}
</content>
</document>`}).filter(n=>n.length>0).join(`
`)}function FHr(t){try{let e=JSON.parse(t);return Array.isArray(e)?ogt(e):"Invalid search results format."}catch(e){return Te("Failed to format localSearch result string:",e),"Error processing search results."}}function kHr(t){return Array.isArray(t)?t.map(e=>({title:e.title||e.path||"Untitled",path:e.path||e.title||"",score:e.rerank_score||e.score||0,explanation:e.explanation||null})):[]}function ngt(t){if(typeof t=="number"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}if(typeof t=="string"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}return""}function gii(t){if(!t)return"";let e=[];try{if(Array.isArray(t.lexicalMatches)&&t.lexicalMatches.length>0){let r=new Set,n=new Set;for(let a of t.lexicalMatches)a?.field&&r.add(String(a.field)),a?.query&&n.add(String(a.query));let o=Array.from(r).join("/"),i=Array.from(n).slice(0,3).join(", ");e.push(`Lexical(${o}): ${i}${n.size>3?", ...":""}`)}if(typeof t.semanticScore=="number"&&t.semanticScore>0&&e.push(`Semantic: ${(t.semanticScore*100).toFixed(1)}%`),t.folderBoost&&typeof t.folderBoost.boostFactor=="number"){let r=t.folderBoost,n=r.folder||"root";e.push(`Folder +${r.boostFactor.toFixed(2)} (${n})`)}if(t.graphConnections&&typeof t.graphConnections=="object"){let r=t.graphConnections,n=[];r.backlinks>0&&n.push(`${r.backlinks} backlinks`),r.coCitations>0&&n.push(`${r.coCitations} co-cites`),r.sharedTags>0&&n.push(`${r.sharedTags} tags`),typeof r.score=="number"?e.push(`Graph ${r.score.toFixed(1)}${n.length?` (${n.join(", ")})`:""}`):n.length&&e.push(`Graph (${n.join(", ")})`)}if(t.graphBoost&&typeof t.graphBoost.boostFactor=="number"&&!t.graphConnections){let r=t.graphBoost;e.push(`Graph +${r.boostFactor.toFixed(2)} (${r.connections} connections)`)}typeof t.baseScore=="number"&&typeof t.finalScore=="number"&&t.baseScore!==t.finalScore&&e.push(`Score: ${t.baseScore.toFixed(4)}\u2192${t.finalScore.toFixed(4)}`)}catch{}return e.join(" | ")}function qHr(t,e,r=1){let n=r,o=[];if(t.length>0){let i=t.map(a=>{let s=a.__sourceId||n++,u=a.title||"Untitled",l=a.path||"",c=a.matchType||a.source||"filter",d=ngt(a.mtime);return`<document>
<id>${s}</id>
<title>${u}</title>
<path>${l}</path>
<matchType>${c}</matchType>${d?`
<modified>${d}</modified>`:""}
<content>
${a.content||""}
</content>
</document>`}).join(`
`);o.push(`<filterResults>
${i}
</filterResults>`)}if(e.length>0){let i=e.map(a=>{let s=a.__sourceId||n++,u=a.title||"Untitled",l=a.path||"",c=ngt(a.mtime);return`<document>
<id>${s}</id>
<title>${u}</title>${l&&l!==u?`
<path>${l}</path>`:""}${c?`
<modified>${c}</modified>`:""}
<content>
${a.content||""}
</content>
</document>`}).join(`
`);o.push(`<searchResults>
${i}
</searchResults>`)}return o.length===0?"No relevant documents found.":o.join(`
`)}function UHr(t){if(!Array.isArray(t)||t.length===0){F("Search Results: (none)");return}let e=0,r=t.map((u,l)=>{let c=ngt(u.mtime),d=typeof u.rerank_score=="number"?u.rerank_score:u.score||0,f=(Number.isFinite(d)?d:0).toFixed(4),p=u.chunkId||u.path||"",m=gii(u.explanation),h=u.includeInContext!==!1;return h&&e++,{idx:String(l+1),in:h?"Y":"",path:p,mtime:c,score:f,explanation:m}}),n=r.length;F(`Search Results (debug table): ${n} rows; in-context ${e}/${n}`),p1t(r,["idx","in","path","mtime","score","explanation"]);let o=u=>String(u||"").replace(/\|/g,"\\|"),i="| # | IN | PATH | MTIME | SCORE | EXPLANATION |",a="| ---: | :-: | --- | --- | ---: | --- |",s=r.map(u=>`| ${u.idx} | ${u.in} | ${o(u.path)} | ${u.mtime||""} | ${u.score} | ${o(u.explanation)} |`);fye(["",`Results: ${n} rows; in-context ${e}/${n}`,"",i,a,...s,""])}function BHr(t,e){return[t,e].map(n=>n?.trim()).filter(n=>!!n).join(`
`)}function zHr(t,e){let r=t?`
${t}
`:"";return`<localSearch${e?` timeRange="${e}"`:""}>${r}</localSearch>`}function igt(t,e){let r=t.trim();return r?`${r}
${e}`:e}function VHr(t,e){let r=e.trim();return!r||t.includes(r)?t:igt(t,`[User query]:
${r}`)}function HHr(t){let e=[],r=0;for(;r<t.length;){let n=t.indexOf("![",r);if(n===-1)break;let o=_ii(t,n+2);if(o===null){r=n+2;continue}let i=o+1;for(;i<t.length&&Wje(t[i]);)i++;if(t[i]!=="("){r=i;continue}let a=vii(t,i);if(a===null){r=i+1;continue}let s=yii(t.slice(i+1,a));s&&e.push(s),r=a+1}return e}function yii(t){let e=t.trim();if(e.length===0)return null;if(e.startsWith("<")){let n=wii(e,0);if(n===null)return null;let o=e.slice(1,n).trim();return o.length>0?o:null}let r=bii(e).trim();return r.length>0?r:null}function bii(t){let e=t.trimEnd();if(e.length===0)return"";let r=e[e.length-1];if(r==='"'||r==="'"){let o=Sii(e,r,e.length-1);if(o!==null){let i=e.slice(0,o);if(i.length>0&&Wje(i[i.length-1]))return i.trimEnd()}}if(r===")"){let n=Cii(e);if(n!==null){let o=e.slice(0,n);if(o.length>0&&Wje(o[o.length-1]))return o.trimEnd()}}return e}function _ii(t,e){let r=e,n=0;for(;r<t.length;){let o=t[r];if(o==="\\"){r+=2;continue}if(o==="["){n++,r++;continue}if(o==="]"){if(n===0)return r;n--,r++;continue}r++}return null}function vii(t,e){let r=e+1,n=1,o=!0,i=!1;for(;r<t.length;){let a=t[r];if(i){if(a==="\\"){r+=2;continue}if(a===">"){i=!1,o=!1,r++;continue}r++;continue}if(o){if(Wje(a)){r++;continue}if(a==="<"){i=!0,r++;continue}o=!1}if(a==="\\"){r+=2;continue}if(a==="("){n++,r++;continue}if(a===")"){if(n--,n===0)return r;r++;continue}r++}return null}function wii(t,e){for(let r=e+1;r<t.length;r++){let n=t[r];if(n==="\\"){r++;continue}if(n===">")return r}return null}function Sii(t,e,r){for(let n=r-1;n>=0;n--)if(t[n]===e&&!WHr(t,n))return n;return null}function Cii(t){if(t.length===0||t[t.length-1]!==")")return null;let e=0;for(let r=t.length-1;r>=0;r--){let n=t[r];if(!((n===")"||n==="(")&&WHr(t,r))){if(n===")"){e++;continue}if(n==="("&&(e--,e===0))return r}}return null}function WHr(t,e){let r=0;for(let n=e-1;n>=0&&t[n]==="\\";n--)r++;return r%2===1}function Wje(t){return t===" "||t===" "||t===`
`||t==="\r"}function Rc(t){return typeof t!="string"?"":t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function JHr(t){return typeof t!="string"?"":t.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&")}ra();var aN=class extends jD{constructor(){super(...arguments);this.lastCitationSources=null}getAvailableToolsForPlanning(){let r=yd.getInstance();return r.getAllTools().length===0&&eZ(this.chainManager.app?.vault),r.getAllTools().map(o=>o.tool).filter(o=>o.name==="getCurrentTime"||o.name==="convertTimeBetweenTimezones"||o.name==="getTimeInfoByEpoch"||o.name==="getTimeRangeMs"||o.name==="getFileTree")}async planToolCalls(r,n){let o=this.getAvailableToolsForPlanning();if(typeof n.bindTools!="function")return Te("[CopilotPlus] Model does not support native tool calling, skipping tool planning"),{toolCalls:[],salientTerms:this.extractSalientTermsFromQuery(r),returnAll:!1};let i=n.bindTools(o),s=[{role:Mte(n),content:`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
- For file structure queries, use getFileTree to explore the vault
- 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]
If the user wants ALL matching notes (e.g., "find all my X", "list every Y", "show me all Z", "how many notes about W"), output: [RETURN_ALL: true]
Otherwise omit RETURN_ALL or output: [RETURN_ALL: false]`},{role:"user",content:r}];F("[CopilotPlus] Requesting tool planning with native tool calling...");let u=await Vb(()=>i.invoke(s)),l=u.tool_calls||[],c=typeof u.content=="string"?u.content:String(u.content);F("[CopilotPlus] Native tool calls:",l.length);let{salientTerms:d,returnAll:f}=this.extractPlanningFieldsFromResponse(c,r),p=[];for(let m of l){let h=o.find(y=>y.name===m.name);h?(p.push({tool:h,args:m.args}),F(`[CopilotPlus] Tool call: ${m.name}`,m.args)):Te(`[CopilotPlus] Tool '${m.name}' not found in available tools`)}return{toolCalls:p,salientTerms:d,returnAll:f}}extractPlanningFieldsFromResponse(r,n){let o,i=r.match(/\[SALIENT_TERMS:\s*([^\]]+?)\s*\]/i);if(i){let u=i[1].split(",").map(l=>l.trim()).filter(l=>l.length>0);o=u.length>0?u:this.extractSalientTermsFromQuery(n)}else o=this.extractSalientTermsFromQuery(n);let a=r.match(/\[RETURN_ALL:\s*(true|false)\s*\]/i),s=a?a[1].toLowerCase()==="true":!1;return{salientTerms:o,returnAll:s}}extractSalientTermsFromQuery(r){return r.split(/[\s\p{P}]+/u).filter(n=>n.length>=3).slice(0,10)}async processAtCommands(r,n,o){let i=r.toLowerCase(),a=this.removeAtCommands(r),s=[...n];if(i.includes("@vault")&&(s.some(l=>l.tool.name==="localSearch")||s.push({tool:gje,args:{query:a,salientTerms:o.salientTerms,timeRange:o.timeRange,returnAll:o.returnAll===!0?!0:void 0}})),(i.includes("@websearch")||i.includes("@web"))&&!s.some(l=>l.tool.name==="webSearch")){let c=await ry.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=gye(c);s.push({tool:yje,args:{query:a,chatHistory:d}})}return i.includes("@memory")&&(s.some(l=>l.tool.name==="updateMemory")||s.push({tool:pje,args:{statement:a}})),s}removeAtCommands(r){return r.split(" ").filter(n=>!OX.includes(n.toLowerCase())).join(" ").trim()}async processImageUrls(r){let n=[],o=await _H.processUrlBatch(r,n,this.chainManager.app.vault);return _H.showFailedImagesNotice(n),o}async processChatInputImages(r){let n=[],o=await _H.processChatImageBatch(r,n,this.chainManager.app.vault);return _H.showFailedImagesNotice(n),o}async extractImagesFromContextBlock(r,n){let i=new RegExp(`<${n.tagName}>([\\s\\S]*?)<\\/${n.tagName}>`).exec(r);if(!i)return[];let a=i[1],u=/<content>([\s\S]*?)<\/content>/.exec(a),l=u?JHr(u[1]):"";if(!l)return[];let d=new RegExp(`<${n.identifierTag}>(.*?)<\\/${n.identifierTag}>`).exec(a),f=d?d[1]:void 0;F(`[CopilotPlus] Extracting images from ${n.displayName}:`,f||`no ${n.identifierTag}`);let p=n.useForResolution?f:void 0;return this.extractEmbeddedImages(l,p)}async extractEmbeddedImages(r,n){let o=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,i=[],a=[...r.matchAll(o)];for(let u of a){let l=u[1];if(n){let c=app.metadataCache.getFirstLinkpathDest(l,n);c?i.push(c.path):(Te(`Could not resolve embedded image: ${l} from source: ${n}`),i.push(l))}else i.push(l)}let s=HHr(r);for(let u of s){if(!u)continue;if(u.match(/^https?:\/\//)){i.push(u);continue}let l=u.replace(/^\.\//,"").replace(/^\//,"");if(n){let c=app.metadataCache.getFirstLinkpathDest(l,n);c?i.push(c.path):i.push(l)}else i.push(l)}return i}async buildMessageContent(r,n){let o=[],i=[],a=te(),s=[];if(a.passMarkdownImages){let d=n.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&&s.push({urls:h,type:"embedded"})}}}for(let d of s){let f=await this.processImageUrls(d.urls);i.push(...f.successfulImages),o.push(...f.failureDescriptions)}let u=n.content;if(u&&u.length>0){let d=await this.processChatInputImages(u);i.push(...d.successfulImages),o.push(...d.failureDescriptions)}let l=r;o.length>0&&(l=`${r}
Note:
${o.join(`
`)}
`);let c=[{type:"text",text:l}];return i.length>0&&c.push(...i),c}hasCapability(r,n){let o=r.modelName||r.model||"";return this.chainManager.chatModelManager.findModelByName(o)?.capabilities?.includes(n)??!1}isMultimodalModel(r){return this.hasCapability(r,"vision")}appendComposerInstructionsIfNeeded(r,n){if(!n.message||!n.message.includes("@composer"))return r;let o=`<OUTPUT_FORMAT>
${F1t}
</OUTPUT_FORMAT>`;return`${r}
${o}`}async streamMultimodalResponse(r,n,o,i,a,s,u){let l=this.chainManager.memoryManager.getMemory(),c=this.chainManager.chatModelManager.getChatModel(),d=this.isMultimodalModel(c),f=[],p=n.contextEnvelope;if(!p)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");F("[CopilotPlus] Using envelope-based context construction");let m=_A.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),h=m.find(w=>w.role==="system");h&&f.push({role:Mte(c),content:h.content}),await Oq(l,f);let y=m.find(w=>w.role==="user");if(y){let w,T=o.length>0,O=P=>{let R="[User query]:";if(P.includes(R))return P;let I=P.trimEnd(),N=[];I.length>0&&N.push(I);let z=s.trim()||n.originalMessage?.trim()||"";return z.length>0?N.push(`${R}
${z}`):N.push(R),N.join(`
`)};if(T){let P=this.formatAllToolOutputs(o),R=O(y.content);w=igt(P,R)}else w=O(y.content);if(r.includes("<OUTPUT_FORMAT>")&&!w.includes("<OUTPUT_FORMAT>")){let P=r.match(/<OUTPUT_FORMAT>[\s\S]*?<\/OUTPUT_FORMAT>/);P&&(w+=`
`+P[0])}let E=d?await this.buildMessageContent(w,n):w;f.push({role:"user",content:E})}F("Final request to AI",{messages:f.length});let g=c?.modelName;Eq({messages:f,modelName:g,contextEnvelope:n.contextEnvelope});let b=new Hje(E$,fje),_=await Vb(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:i.signal}));for await(let w of _){if(i.signal.aborted){F("CopilotPlus multimodal stream iteration aborted",{reason:i.signal.reason});break}for await(let T of b.processChunk(w))a.processChunk(T)}}async run(r,n,o,i,a){let{updateLoadingMessage:s}=a,u=this.chainManager.chatModelManager.getChatModel(),c=!this.hasCapability(u,"reasoning"),d=new dv(o,c),f=[];if(!await E0({isCopilotPlus:!0})){await this.handleError(new Error("Invalid license key"),d.processErrorChunk.bind(d));let _=d.close().content;return this.handleResponse(_,r,n,i,o,void 0)}try{F("==== Step 1: Planning tools ====");let _,w=r.contextEnvelope;if(!w)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");let O=w.layers.find(V=>V.id==="L5_USER")?.text||r.originalMessage||"";try{let V=this.chainManager.chatModelManager.getChatModel(),k=await this.planToolCalls(O,V),X,B=k.toolCalls.find(Y=>Y.tool.name==="getTimeRangeMs");if(B){let Y=await E$.callTool(B.tool,B.args),K=oe=>oe?.startTime?.epoch!==void 0&&oe?.endTime?.epoch!==void 0?{startTime:oe.startTime.epoch,endTime:oe.endTime.epoch}:oe;if(typeof Y=="string")try{let oe=JSON.parse(Y);oe.error||(X=K(oe))}catch{Te("[CopilotPlus] Failed to parse getTimeRangeMs result:",Y)}else Y&&!Y.error&&(X=K(Y));F("[CopilotPlus] Executed getTimeRangeMs, result:",X)}let Q=k.toolCalls.filter(Y=>Y.tool.name==="getFileTree"&&a5()?(F("Skipping getFileTree in project mode"),!1):Y.tool.name==="getTimeRangeMs"&&X?(F("Skipping getTimeRangeMs - already executed during planning"),!1):!0);_=await this.processAtCommands(O,Q,{salientTerms:k.salientTerms,timeRange:X,returnAll:k.returnAll})}catch(V){return this.handleResponse(_1t(V),r,n,i,o)}let E=r.contextEnvelope?.layers.find(V=>V.id==="L5_USER")?.text,P=this.removeAtCommands(E||r.originalMessage||r.message),{toolOutputs:R,sources:I}=await this.executeToolCalls(_,s);f=I;let N=R.filter(V=>V.output!=null),z=this.appendComposerInstructionsIfNeeded(P,r);F("Invoking LLM with envelope-based context construction"),await this.streamMultimodalResponse(z,r,N,n,d,P,s)}catch(_){s?.(dw.DEFAULT),_.name==="AbortError"||n.signal.aborted?F("CopilotPlus stream aborted by user",{reason:n.signal.reason}):await this.handleError(_,d.processErrorChunk.bind(d))}if(n.signal.aborted&&n.signal.reason==="new-chat")return o(""),"";let m=d.close(),h=m.content,y={wasTruncated:m.wasTruncated,tokenUsage:m.tokenUsage??void 0},g=te(),b=this.lastCitationSources&&this.lastCitationSources.length>0?this.lastCitationSources:(f||[]).map(_=>({title:_.title,path:_.path}));return h=QDe(h,b,g.enableInlineCitations),await this.handleResponse(h,r,n,i,o,f,void 0,y),h}async executeToolCalls(r,n){let o=[],i=[],a=r.some(s=>s.tool.name==="localSearch");for(let s of r){if(s.tool.name==="getFileTree"&&a){F("Skipping getFileTree since localSearch is already active");continue}F(`Step 2: Calling tool: ${s.tool.name}`),s.tool.name==="localSearch"?n?.(dw.READING_FILES):s.tool.name==="webSearch"?n?.(dw.SEARCHING_WEB):s.tool.name==="getFileTree"&&n?.(dw.READING_FILE_TREE);let u=await E$.callTool(s.tool,s.args);if(s.tool.name==="localSearch"){let c={result:typeof u=="string"?u:JSON.stringify(u),success:u!=null},d=this.getTimeExpression(r),f=this.processLocalSearchResult(c,d);i.push(...f.sources),o.push({tool:s.tool.name,output:f.formattedForLLM})}else o.push({tool:s.tool.name,output:u})}return{toolOutputs:o,sources:XU(i)}}getTimeExpression(r){let n=r.find(o=>o.tool.name==="getTimeRangeMs");return n?n.args.timeExpression:""}prepareLocalSearchResult(r,n){let o=r.filter(T=>T.includeInContext!==!1),i=$Hr(o),a=LHr(i),s=o.reduce((T,O)=>T+(O.content?.length||0),0),u=o;if(s>OWe){let T=OWe/s;F("Truncating document contents to fit context length. Truncation ratio:",T),u=o.map(O=>({...O,conten
${_}
${g}`:`${a}
${_}`;return zHr(w,n)}processLocalSearchResult(r,n){let o=[],i,a;if(!r.success)return i=`<localSearch>
Search failed.
</localSearch>`,a=`Search failed: ${r.result}`,{formattedForLLM:i,formattedForDisplay:a,sources:o};try{let s=JSON.parse(r.result),u=s&&typeof s=="object"&&s.type==="local_search"&&Array.isArray(s.documents)?s.documents:null;if(!Array.isArray(u))return i=`<localSearch>
Invalid search results format.
</localSearch>`,a="Search results were in an unexpected format.",{formattedForLLM:i,formattedForDisplay:a,sources:o};UHr(u),o=kHr(u),i=this.prepareLocalSearchResult(u,n||""),a=P$.format("localSearch",i)}catch(s){Te("Failed to parse localSearch results:",s);let u=FHr(r.result);i=n?`<localSearch timeRange="${n}">
${u}
</localSearch>`:`<localSearch>
${u}
</localSearch>`,a=P$.format("localSearch",i)}return{formattedForLLM:i,formattedForDisplay:a,sources:o}}async getSystemPrompt(){return T$(this.chainManager.userMemoryManager)}formatAllToolOutputs(r){return r.length===0?"":`# Additional context:
`+r.map(o=>{let i=o.output;return typeof i!="string"&&(i=JSON.stringify(i)),`<${o.tool}>
${i}
</${o.tool}>`}).join(`
`)}};var qce=class extends aN{};mr();Xe();Fc();Ye();Bt();ta();Xe();function cgt(t){return t.map(e=>e.content).filter(e=>e&&e.trim().length>0).join(`
`)}var oW=class{constructor(e){this.modelName=e}buildToolSpecificInstructions(e){let r=[];for(let o of e)o.customPromptInstructions&&r.push(o.customPromptInstructions);let n=this.buildCopilotCommandInstructions(e);return n&&r.push(n),r.length>0?r.join(`
`):""}buildCopilotCommandInstructions(e){let r=[];for(let n of e)if(!(!n.copilotCommands||n.copilotCommands.length===0))for(let o of n.copilotCommands)r.push(`- ${o}: call the tool named ${n.id}`);return r.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):",...r,"If the referenced tool is unavailable, explain that the command cannot be fulfilled instead of ignoring it."].join(`
`)}enhanceSystemPrompt(e,r,n,o){let i=this.buildSystemPromptSections(e,r,n,o);return cgt(i)}buildSystemPromptSections(e,r,n,o){let i=o||[],a=this.buildToolSpecificInstructions(i).trim(),u=[{id:"base-system-prompt",label:"System prompt with memory",source:"src/system-prompts/systemPromptBuilder.ts#getSystemPromptWithMemory",content:e.trimEnd()},{id:"autonomous-agent-intro",label:"Autonomous agent introduction",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Autonomous Agent Mode
You are now in autonomous agent mode. You can use tools to gather information and complete tasks step by step.
Tools are provided via native function calling - use them when needed to complete tasks.
`}],l=r.trim();return l.length>0&&u.push({id:"tool-descriptions",label:"Tool descriptions (native tool calling via bindTools)",source:"Native tool calling - schemas provided via bindTools()",content:`Available tools:
${l}`}),u.push({id:"tool-usage-guidelines",label:"Tool usage guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Tool Usage Guidelines
## Time-based Queries
When users ask about temporal periods (e.g., "what did I do last month", "show me notes from last week"), you MUST:
1. First call getTimeRangeMs to convert the time expression to a proper time range
2. Then use localSearch with the timeRange parameter from step 1
3. For salientTerms, ONLY use words that exist in the user's original query (excluding time expressions)
Example for "what did I do last month":
1. Call getTimeRangeMs with timeExpression: "last month"
2. Use localSearch with query matching the user's question
3. salientTerms: [] - empty because "what", "I", "do" are not meaningful search terms
Example for "meetings about project X last week":
1. Call getTimeRangeMs with timeExpression: "last week"
2. Use localSearch with query "meetings about project X"
3. salientTerms: ["meetings", "project", "X"] - these words exist in the original query
## File-related Queries
### Handle ambiguity in folder/note paths
When user mentions a folder name (e.g., "meetings folder") or a note name (e.g., "meeting note template") without providing an exact path,
you MUST first call getFileTree to find the folder or notes best matching the user's query.
If multiple results or no result, you should ask the user to provide a more specific path.
`}),a.length>0&&u.push({id:"tool-specific-instructions",label:"Tool-specific instructions",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildToolSpecificInstructions",content:a}),u.push({id:"general-guidelines",label:"General guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`## General Guidelines
- Think hard about whether a query could potentially be answered from personal knowledge or notes, if yes, call a vault search (localSearch) first
- 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`}),u}enhanceUserMessage(e,r){return e}needsSpecialHandling(){return!1}},agt=class extends oW{isGPT5Model(){return this.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o),a=n||[],s=a.includes("writeToFile")||a.includes("replaceInFile"),u=[];this.isGPT5Model()?u.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`):u.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."),s&&u.push(`\u{1F6A8} FILE EDITING WITH COMPOSER TOOLS \u{1F6A8}
When user asks you to edit or modify a file, you MUST:
1. Determine if it's a small edit (use replaceInFile) or major rewrite (use writeToFile)
2. Call the tool immediately - do not just describe what you plan to do
For replaceInFile, the diff parameter must use SEARCH/REPLACE format:
------- SEARCH
content to find
=======
replacement content
+++++++ REPLACE
\u274C WRONG: "I'll help you add item 4 to the list. Let me update that for you." [No tool call = FAILURE]
\u2705 CORRECT: Actually call replaceInFile or writeToFile with proper parameters`),u.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 l=u.join(`
`);return i.push({id:"gpt-specific-guidelines",label:"GPT-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GPTModelAdapter.buildSystemPromptSections",content:l}),i}enhanceUserMessage(e,r){return r?this.getBaseEnhancement(e,r):e}getBaseEnhancement(e,r){if(!r)return e;let n=e.toLowerCase(),o=n.includes("find")||n.includes("search")||n.includes("my notes"),i=n.includes("edit")||n.includes("modify")||n.includes("update")||n.includes("change")||n.includes("fix")||n.includes("add")||n.includes("typo");return o?`${e}
REMINDER: Call the localSearch tool now.`:i?`${e}
\u{1F6A8} GPT REMINDER: Use replaceInFile for small edits (with SEARCH/REPLACE blocks in diff parameter).`:e}needsSpecialHandling(){return!0}},sgt=class extends oW{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,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o);if(!this.isThinkingModel())return i;let a=[`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()&&a.push(`\u{1F6A8} CRITICAL INSTRUCTIONS FOR CLAUDE SONNET 4 - AUTONOMOUS AGENT MODE \u{1F6A8}
\u26A0\uFE0F WARNING: You have a specific tendency to write complete responses immediately after tool calls. This BREAKS the autonomous agent pattern!
\u{1F504} 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. \u270B 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
\u2705 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
\u{1F3AF} CORRECT PATTERN:
I'll search your vault for piano practice information.
[Call localSearch tool]
[RESPONSE ENDS HERE - NO MORE TEXT]
\u274C 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!]
\u{1F511} 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
\u26A1 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:a.join(`
`)}),i}needsSpecialHandling(){return this.isThinkingModel()}},ugt=class extends oW{buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o),u=[`\u{1F6A8} CRITICAL INSTRUCTIONS FOR GEMINI - AUTONOMOUS AGENT MODE \u{1F6A8}
You MUST use tools to complete tasks. DO NOT ask the user questions about how to proceed.
${(n||[]).includes("localSearch")?`
When the user mentions "my notes" or "my vault", use the localSearch tool.
\u274C WRONG:
"Let's start by searching your notes. What kind of information should I look for?"
\u2705 CORRECT: Call localSearch immediately with the user's topic as the query`:""}`.trim()];return u.push(`GEMINI SPECIFIC RULES:
1. When user mentions "my notes" about X \u2192 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
\u{1F6A8} CRITICAL: SEQUENTIAL vs PARALLEL TOOL CALLS \u{1F6A8}
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
\u274C 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!
\u2705 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:u.join(`
`)}),i}enhanceUserMessage(e,r){return r?`${e}
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},lgt=class extends oW{buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o);return i.push({id:"copilot-plus-guidelines",label:"Copilot Plus model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#CopilotPlusModelAdapter.buildSystemPromptSections",content:`\u{1F6A8} CRITICAL: NO HALLUCINATED TOOL CALLS OR SOURCES \u{1F6A8}
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}},Uce=class{static createAdapter(e){let r=(e.modelName||e.model||"").toLowerCase();if(F(`Creating model adapter for: ${r}`),r.includes("gpt")){let n=new agt(r);return n.isGPT5Model()?F("Using GPTModelAdapter with GPT-5 specific enhancements"):F("Using GPTModelAdapter"),n}return r.includes("claude")?(F("Using ClaudeModelAdapter"),new sgt(r)):r.includes("gemini")||r.includes("google/gemini")?(F("Using GeminiModelAdapter"),new ugt(r)):r.includes("copilot-plus")?(F("Using CopilotPlusModelAdapter"),new lgt(r)):(F("Using BaseModelAdapter (default)"),new oW(r))}};function KHr(t){let e=["find","search","look for","look up","my notes","in my vault","from my vault","check the web","search online","from the internet","current time","what time","timer","youtube","video","transcript"],r=t.toLowerCase();return e.some(n=>r.includes(n))}function xii(t){let{systemSections:e,rawHistory:r,adapterName:n,originalUserMessage:o,enhancedUserMessage:i}=t,a=[...e];if(r&&r.length>0){let u=fst(r);if(u.length>0){let c=cvr(u).map((d,f)=>`${f+1}. ${d.role.toUpperCase()}
${d.content}`);a.push({id:"chat-history",label:"Restored chat history from memory",source:"src/LLMProviders/chainRunner/utils/chatHistoryUtils.ts#processRawChatHistory",content:c.join(`
`)})}}a.push({id:"user-original-message",label:"Original user message",source:"Chat input",content:o});let s=i===o?" (unchanged)":"";return a.push({id:"user-enhanced-message",label:`User message after ${n}.enhanceUserMessage${s}`,source:`src/LLMProviders/chainRunner/utils/modelAdapter.ts#${n}.enhanceUserMessage`,content:i}),a}function Tii(t){return t.map(e=>`${`[Section: ${e.label} | Source: ${e.source}]`}
${e.content}`).join(`
`)}function GHr(t){let e=xii(t),r=Tii(e),n=cgt(t.systemSections);return{sections:e,annotatedPrompt:r,systemPrompt:n}}async function Oii(t){let{chainManager:e,adapter:r,basePrompt:n,toolDescriptions:o,toolNames:i,toolMetadata:a,userMessage:s}=t,u=r.buildSystemPromptSections(n,o,i,a),c=await e.memoryManager.getMemory().loadMemoryVariables({}),d=Array.isArray(c.history)?c.history:[],f=s.originalMessage||s.message,p=KHr(s.message),m=r.enhanceUserMessage(s.message,p);return GHr({systemSections:u,rawHistory:d,adapterName:r.constructor?.name||"ModelAdapter",originalUserMessage:f,enhancedUserMessage:m})}async function Eii(t){return T$(t.userMemoryManager)}async function XHr(t){let{chainManager:e,adapter:r,availableTools:n,toolDescriptions:o,userMessage:i}=t,a=yd.getInstance(),s=n.map(c=>c.name),u=n.map(c=>a.getToolMetadata(c.name)).filter(c=>c!==void 0),l=await Eii(e);return Oii({chainManager:e,adapter:r,basePrompt:l,toolDescriptions:o,toolNames:s,toolMetadata:u,userMessage:i})}function ZHr(){return{status:"idle",startTime:null,elapsedSeconds:0,steps:[]}}function dgt(t){if(t.status==="idle")return"";let e=JSON.stringify(t.steps.map(r=>r.summary));return`<!--AGENT_REASONING:${t.status}:${t.elapsedSeconds}:${e}-->`}function Bce(t){let e=t.match(/<!--AGENT_REASONING:(\w+):(\d+):(.+?)-->/);if(!e)return null;let[r,n,o,i]=e,a=[];try{a=JSON.parse(i)}catch{a=[]}return{hasReasoning:!0,status:n,elapsedSeconds:parseInt(o,10),steps:a,contentAfter:t.replace(r,"").trim()}}function YHr(t,e,r,n){if(!e.success)return`${fgt(t,n)} failed`;switch(t){case"localSearch":{if(r&&r.count>0){let o=r.titles.slice(0,3),i=r.count-o.length,a=`Found ${r.count} note${r.count!==1?"s":""}: ${o.join(", ")}`;return i>0&&(a+=` +${i} more`),a}return"No matching notes found"}case"webSearch":return"Retrieved web search results";case"getTimeRangeMs":return"Calculated time range";case"readFile":return"Read file content";case"readNote":{let o=n?.notePath;return o?`Read "${o.split("/").pop()?.replace(/\.md$/i,"")||o}"`:"Read note content"}case"createNote":return"Created new note";case"appendToNote":return"Appended to note";case"editNote":return"Edited note";case"deleteNote":return"Deleted note";case"youtubeTranscript":case"youtubeTranscription":return"Fetched video transcript";case"fetchUrl":return"Fetched URL content";case"getFileTree":return"Retrieved vault file tree";case"getTagList":return"Retrieved vault tags";case"getCurrentTime":return"Got current time";case"getTimeInfoByEpoch":return"Converted timestamp";case"convertTimeBetweenTimezones":return"Converted timezone";case"indexVault":return"Indexed vault";case"updateMemory":return"Updated memory";case"writeToFile":case"replaceInFile":{let o=n?.path,i=o?o.split("/").pop()||o:"file",a=e.result||"";return a.includes('"rejected"')||a.includes("rejected")?`Edit rejected for "${i}"`:a.includes('"failed"')||a.includes("Error")?`Edit failed for "${i}"`:t==="writeToFile"?`Wrote to "${i}"`:`Edited "${i}"`}default:return"Done"}}function fgt(t,e,r){switch(t){case"localSearch":{if(r&&r.recallTerms&&r.recallTerms.length>0){let o=r.recallTerms.filter(i=>typeof i=="string"&&i.trim().length>0&&!i.includes("[object ")&&i!=="[object Object]");if(o.length>0){let i=o.slice(0,6).map(u=>`"${u}"`).join(", "),a=o.length-6,s=a>0?` +${a} more`:"";return`Searching notes for ${i}${s}`}}let n=e?.query;return n?`Searching notes for "${n.length>50?n.slice(0,50)+"...":n}"`:"Searching notes"}case"webSearch":{let n=e?.query;return n?`Searching web for "${n.length>30?n.slice(0,30)+"...":n}"`:"Searching the web"}case"getTimeRangeMs":return"Calculating time range";case"readFile":{let n=e?.path;return n?`Reading "${n.split("/").pop()||n}"`:"Reading file"}case"readNote":{let n=e?.notePath;return n?`Reading "${n.split("/").pop()?.replace(/\.md$/i,"")||n}"`:"Reading note"}case"createNote":return"Creating new note";case"appendToNote":return"Appending to note";case"editNote":return"Editing note";case"deleteNote":return"Deleting note";case"youtubeTranscript":case"youtubeTranscription":return"Fetching video transcript";case"fetchUrl":return"Fetching URL content"
`)[0];return Pii(e,100)}xst();var zce=class extends aN{constructor(){super(...arguments);this.llmFormattedMessages=[];this.lastDisplayedContent="";this.reasoningState=ZHr();this.reasoningTimerInterval=null;this.accumulatedContent="";this.allReasoningSteps=[];this.abortHandledByTimer=!1}getAvailableTools(){let r=te(),n=yd.getInstance();n.getAllTools().length===0&&eZ(this.chainManager.app?.vault);let o=new Set(r.autonomousAgentEnabledToolIds||[]);return n.getEnabledTools(o,!!this.chainManager.app?.vault)}startReasoningTimer(r,n){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=setInterval(()=>{if(n?.signal.aborted&&this.reasoningState.status==="reasoning"){this.stopReasoningTimer(),this.reasoningState.status="complete",this.abortHandledByTimer=!0;let a=this.buildReasoningBlockMarkup(),s="The response was interrupted.",u=a?a+`
`+s:s;r(u);return}if(this.reasoningState.startTime&&this.reasoningState.status==="reasoning"){this.reasoningState.elapsedSeconds=Math.floor((Date.now()-this.reasoningState.startTime)/1e3);let a=this.buildReasoningBlockMarkup(),s=a?a+(this.accumulatedContent?`
`+this.accumulatedContent:""):this.accumulatedContent;r(s)}},100)}addReasoningStep(r,n,o=!1){let i={timestamp:Date.now(),summary:r,toolName:n};this.allReasoningSteps.push(i),!o&&(this.reasoningState.steps.push(i),this.reasoningState.steps.length>4&&this.reasoningState.steps.shift())}stopReasoningTimer(){this.reasoningTimerInterval&&(clearInterval(this.reasoningTimerInterval),this.reasoningTimerInterval=null),this.reasoningState.status="collapsed"}buildReasoningBlockMarkup(){if(this.reasoningState.status==="complete"||this.reasoningState.status==="collapsed"){let r={...this.reasoningState,steps:this.allReasoningSteps};return dgt(r)}return dgt(this.reasoningState)}static async generateSystemPrompt(r,n,o){let i=await T$(o),a=yd.getInstance(),u=r.map(l=>a.getToolMetadata(l.name)).filter(l=>l!==void 0).filter(l=>l.customPromptInstructions).map(l=>`For ${l.displayName}: ${l.customPromptInstructions}`).join(`
`);return u?`${i}
## Tool Guidelines
${u}`:i}async buildToolPromptDebugReport(r){let n=this.getAvailableTools(),o=Uce.createAdapter(this.chainManager.chatModelManager.getChatModel()),i=n.map(a=>`${a.name}: ${a.description}`).join(`
`);return XHr({chainManager:this.chainManager,adapter:o,availableTools:n,toolDescriptions:i,userMessage:r})}applyCiCOrderingToLocalSearchResult(r,n){return VHr(r,n)}async run(r,n,o,i,a){this.llmFormattedMessages=[],this.lastDisplayedContent="";let s=await E0({isAutonomousAgent:!0}),u=this.chainManager.chatModelManager.getChatModel(),l=Uce.createAdapter(u),c=new dv(o,!0);if(!s){await this.handleError(new Error("Invalid license key"),c.processErrorChunk.bind(c));let m=c.close().content;return this.handleResponse(m,r,n,i,o,void 0)}let d=u?.modelName;if(!r.contextEnvelope)throw new Error("[Agent] Context envelope is required but not available. Cannot proceed with autonomous agent.");F("[Agent] Using native tool calling with ReAct pattern");let p=await this.prepareAgentConversation(r,u,a.updateLoadingMessage);try{this.startReasoningTimer(o,n);let m=await this.runReActLoop({boundModel:p.loopDeps.boundModel,tools:p.loopDeps.availableTools,messages:p.messages,originalPrompt:p.originalUserPrompt,abortController:n,updateCurrentAiMessage:o,processLocalSearchResult:p.loopDeps.processLocalSearchResult,applyCiCOrderingToLocalSearchResult:p.loopDeps.applyCiCOrderingToLocalSearchResult,adapter:l});if(this.abortHandledByTimer)return this.lastDisplayedContent="","";let h=XU(m.sources);return p.messages.length>0&&Eq({messages:[...p.messages],modelName:d,contextEnvelope:r.contextEnvelope}),await this.handleResponse(m.finalResponse,r,n,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"||n.signal.aborted)return F("Autonomous agent stream aborted by user",{reason:n.signal.reason}),"";ne("Autonomous agent failed, falling back to regular Plus mode:",m);try{return await new aN(this.chainManager).run(r,n,o,i,a)}catch(h){ne("Fallback to regular Plus mode also failed:",h),this.lastDisplayedContent&&c.processChunk({content:this.lastDisplayedContent});let y=zr(m),g=`
Fallback to regular Plus mode also failed: `+zr(h);await this.handleError(new Error(y+g),c.processErrorChunk.bind(c));let b=c.close().content;return this.handleResponse(b,r,n,i,o,void 0,b)}}}async prepareAgentConversation(r,n,o){let i=[],a=this.getAvailableTools(),s=n.modelName||n.model||"unknown";if(typeof n.bindTools!="function")throw new Error(`Model ${s} does not support native tool calling (bindTools not available). Agent mode requires a model with tool calling support.`);let u=n.bindTools(a),l={availableTools:a,boundModel:u,processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},c=r.contextEnvelope,d=_A.convert(c,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),f=this.chainManager.memoryManager.getMemory(),p=d.find(E=>E.role==="system"),m=yd.getInstance(),y=a.map(E=>m.getToolMetadata(E.name)).filter(E=>E!==void 0).filter(E=>E.customPromptInstructions).map(E=>`For ${E.displayName}: ${E.customPromptInstructions}`).join(`
`),g=[p?.content||"",y?`
## Tool Guidelines
${y}`:""].filter(Boolean).join(`
`);g&&i.push(new Od({content:g}));let w=c.layers.find(E=>E.id==="L5_USER")?.text||""||r.originalMessage||r.message,T=[];await Oq(f,T);for(let E of T)E.role==="user"?i.push(new qs(E.content)):i.push(new Pn(E.content));let O=d.find(E=>E.role==="user");if(O){let P=this.isMultimodalModel(n)?await this.buildMessageContent(O.content,r):O.content;i.push(new qs(P))}return{messages:i,collectedSources:[],originalUserPrompt:w,loopDeps:l}}async runReActLoop(r){let{boundModel:n,tools:o,messages:i,originalPrompt:a,abortController:s,updateCurrentAiMessage:u,processLocalSearchResult:l,applyCiCOrderingToLocalSearchResult:c}=r,d=te().autonomousAgentMaxIterations,f=[],p=Date.now(),m=0,h;for(;m<d&&!s.signal.aborted;){let T=Date.now()-p;if(T>=EWe){Te(`Agent loop timed out after ${Math.round(T/1e3)}s`);break}m++;let{content:O,aiMessage:E,streamingResult:P}=await this.streamModelResponse(n,i,s,u);h={wasTruncated:P.wasTruncated,tokenUsage:P.tokenUsage??void 0};let R=E.tool_calls||[];if(R.length===0){this.stopReasoningTimer(),this.reasoningState.status="complete",i.push(E);let I=O,N=this.buildReasoningBlockMarkup(),z=20,V=5,k="";for(let B=0;B<I.length&&!s.signal.aborted;B+=z){k+=I.slice(B,B+z);let Q=N?N+`
`+k:k;u(Q),B+z<I.length&&await new Promise(Y=>setTimeout(Y,V))}let X=N?N+`
`+I:I;return u(X),{finalResponse:X,sources:f,responseMetadata:h}}if(i.push(E),m>1&&O&&O.trim().length>0){let I=QHr(O);I&&this.addReasoningStep(I)}for(let I of R){if(s.signal.aborted)break;let N={name:I.name,args:I.args},z;if(I.name==="localSearch"){let Y=N.args.query;if(Y)try{let oe=await new g9({getChatModel:async()=>this.chainManager.chatModelManager.getChatModel()}).expand(Y),ue=new Set,de=[],L=W=>{if(typeof W!="string")return;let ie=W.trim();if(!ie||ie==="[object Object]"||ie.startsWith("[object "))return;let j=ie.toLowerCase();ue.has(j)||(ue.add(j),de.push(ie))};oe.originalQuery&&L(oe.originalQuery),(oe.salientTerms||[]).forEach(L),(oe.expandedQueries||[]).forEach(L),z={originalQuery:oe.originalQuery,salientTerms:oe.salientTerms,expandedQueries:oe.expandedQueries,recallTerms:de}}catch{}}let V=fgt(I.name,N.args,z);this.addReasoningStep(V,I.name),z&&(N.args._preExpandedQuery=z),Gmt(N,m);let k=await Jmt(N,o,a),X;if(I.name==="localSearch"&&k.success){let Y=l(k);f.push(...Y.sources),X={titles:Y.sources.map(K=>K.title),count:Y.sources.length},k.result=c(Y.formattedForLLM,a||"")}Xmt(I.name,k);let B=YHr(I.name,k,X,N.args);this.addReasoningStep(B,I.name);let Q=pst(I.id||tPe(),I.name,k.result);i.push(Q)}}this.stopReasoningTimer(),this.reasoningState.status="complete";let y=this.buildReasoningBlockMarkup();if(s.signal.aborted){if(F("Agent reasoning interrupted by user"),this.abortHandledByTimer)return{finalResponse:"",sources:f,responseMetadata:h};let T="The response was interrupted.";return{finalResponse:y?y+`
`+T:T,sources:f,responseMetadata:h}}let g=Date.now()-p,b=g>=EWe;b?Te(`Agent loop timed out after ${Math.round(g/1e3)}s`):Te(`Agent reached max iterations (${d})`);let _=b?"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+`
`+_:_,sources:f,responseMetadata:h}}async streamModelResponse(r,n,o,i){let a=new Map,s=new dv(()=>{},!0);try{let u=await Vb(()=>r.stream(n,{signal:o.signal}));for await(let p of u){if(o.signal.aborted)break;if(p.response_metadata?.finish_reason==="MALFORMED_FUNCTION_CALL")throw Te("Backend returned MALFORMED_FUNCTION_CALL - falling back to non-agent mode"),new Error("MALFORMED_FUNCTION_CALL: Model does not support native tool calling");let h=p.tool_call_chunks;if(h&&Array.isArray(h))for(let y of h){let g=y.index??0,b=a.get(g)||{name:"",args:""};y.id&&(b.id=y.id),y.name&&(b.name+=y.name),y.args&&(b.args+=y.args),a.set(g,b)}s.processChunk(p)}let l=s.close(),c=l.content,d=rPe(a),f=new Pn({content:c,tool_calls:d.map(p=>({id:p.id,name:p.name,args:p.args,type:"tool_call"}))});return{content:c,aiMessage:f,streamingResult:l}}catch(u){if(ne(`Stream error: ${u.message}`),u.name==="AbortError"||o.signal.aborted){let l=s.close();return{content:l.content,aiMessage:new Pn({content:l.content}),streamingResult:l}}throw u}}};Xe();Ye();Bt();lw();FS();var Q3r=require("obsidian");CX();var Vce=[{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}],Jje=new Map;for(let t of Vce)Jje.set(t.tag,t);function iW(t){return Jje.get(t)?.sourceType??"unknown"}function Kje(t){return Jje.get(t)?.recoverable??!1}function tZ(t,e){let r=Jje.get(e);if(!r?.sourceExtractor)return"";let n=r.sourceExtractor;return new RegExp(`<${n}>([^<]+)</${n}>`).exec(t)?.[1]??""}function Hce(t){let e=/<content>([\s\S]*?)<\/content>/.exec(t);return e?e[1]:t}function pgt(t){return t.match(/^<(\w+)[\s>]/)?.[1]??null}var nS={previewCharsPerSection:500,maxSections:20,verbatimThreshold:5e3};function aW(t,e=500,r=20){let n=t.split(/(?=^#{1,6}\s+)/m).filter(s=>s.trim());if(n.length<=1)return mgt(t,e*4);let o=n.slice(0,r),i=n.length>r,a=o.map(s=>{let u=s.trim().split(`
`),l=u[0],c=u.slice(1).join(`
`).trim();return c.length<=e?s.trim():`${l}
${mgt(c,e)}`}).join(`
`);return i?`${a}
[... ${n.length-r} more sections omitted ...]`:a}function mgt(t,e){if(t.length<=e)return t;let r=t.slice(0,e),n=/[.!?]\s+/g,o=-1,i;for(;(i=n.exec(r))!==null;)i.index>e*.5&&(o=i.index+1);if(o>0)return r.slice(0,o)+" ...";let a=r.lastIndexOf(`
`);if(a>e*.5)return r.slice(0,a)+`
...`;let s=r.lastIndexOf(" ");return s>e*.8?r.slice(0,s)+" ...":r+"..."}function Gje(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Mii(){return["localSearch","note_context","active_note","retrieved_document","url_content","youtube_video_context"].map(e=>({pattern:new RegExp(`<${e}[^>]*>[\\s\\S]*?</${e}>`,"g"),tag:e}))}var Rii=Mii(),rZ="Tool 'readNote' result: ";function Iii(t,e){if(t[e]!=="{")return null;let r=0,n=!1,o=!1;for(let i=e;i<t.length;i++){let a=t[i];if(o){o=!1;continue}if(a==="\\"&&n){o=!0;continue}if(a==='"'){n=!n;continue}if(!n){if(a==="{")r++;else if(a==="}"&&(r--,r===0))return{json:t.slice(e,i+1),endPos:i+1}}}return null}function sW(t,e={}){return Array.isArray(t)?t.map(r=>r.type==="text"&&typeof r.text=="string"?{...r,text:e3r(r.text,e)}:r):typeof t=="string"?e3r(t,e):t}function e3r(t,e={}){let r=e.verbatimThreshold??nS.verbatimThreshold,n=t;for(let{pattern:o,tag:i}of Rii)o.lastIndex=0,n=n.replace(o,a=>a.length<r?a:Nii(a,i,e));return n=Aii(n,r,e),n}function Aii(t,e,r){let n="",o=0;for(;o<t.length;){let i=t.indexOf(rZ,o);if(i===-1){n+=t.slice(o);break}n+=t.slice(o,i);let a=i+rZ.length,s=Iii(t,a);if(!s){n+=rZ,o=a;continue}try{let u=JSON.parse(s.json);if(u.content&&u.content.length>e){let l=jii(u,r);n+=`${rZ}${JSON.stringify(l)}`}else n+=rZ+s.json}catch{n+=rZ+s.json}o=s.endPos}return n}function Nii(t,e,r={}){if(!Kje(e))return t;if(e==="localSearch")return Dii(t,r);let n=tZ(t,e),o=Hce(t),i=iW(e),a=r.previewCharsPerSection??nS.previewCharsPerSection,s=r.maxSections??nS.maxSections,u=aW(o,a,s);return`<prior_context source="${Gje(n)}" type="${i}">
${u}
</prior_context>`}function Dii(t,e={}){let r=e.previewCharsPerSection??nS.previewCharsPerSection,n=/<document>([\s\S]*?)<\/document>/g,o=[],i;for(;(i=n.exec(t))!==null;){let s=i[1],u=/<path>([^<]+)<\/path>/.exec(s),l=/<title>([^<]+)<\/title>/.exec(s),c=/<content>([\s\S]*?)<\/content>/.exec(s),d=u?.[1]??"",f=l?.[1]??d.split("/").pop()??"Untitled",p=c?.[1]??"",m=p.length>r?p.slice(0,r)+"...":p;o.push({path:d,title:f,preview:m.trim()})}if(o.length===0){let s=Hce(t);return`<prior_context source="localSearch" type="note">
${aW(s,r,e.maxSections??nS.maxSections)}
</prior_context>`}let a=o.map((s,u)=>`${u+1}. [[${s.title}]] (${s.path})
${s.preview}`).join(`
`);return`<prior_context source="localSearch" type="note">
[${o.length} search results - use localSearch to re-query]
${a}
</prior_context>`}function jii(t,e={}){let{content:r,notePath:n,noteTitle:o,...i}=t;if(!r||typeof r!="string")return t;let a=e.previewCharsPerSection??nS.previewCharsPerSection,s=e.maxSections??nS.maxSections,u=aW(r,a,s);return{...i,notePath:n,noteTitle:o,content:`[COMPACTED - use readNote to get full content]
${u}`,_wasCompacted:!0}}Ye();nye();FS();var $ii=`Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.
EXAMPLE
Current summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.
New lines of conversation:
Human: Why do you think artificial intelligence is a force for good?
AI: Because artificial intelligence will help humans reach their full potential.
New summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.
END OF EXAMPLE
Current summary:
{summary}
New lines of conversation:
{new_lines}
New summary:`,t3r=new mu({inputVariables:["summary","new_lines"],template:$ii}),Lii=`You are an assistant to a human, powered by a large language model trained by OpenAI.
You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
You are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.
Overall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.
Context:
{entities}
Current conversation:
{history}
Last line:
Human: {input}
You:`,r3r=new mu({inputVariables:["entities","history","input"],template:Lii}),Fii=`You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.
The conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.
Return the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).
EXAMPLE
Conversation history:
Person #1: my name is Jacob. how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.
Output: Jacob,Langchain
END OF EXAMPLE
EXAMPLE
Conversation history:
Person #1: how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.
Output: Langchain, Person #2
END OF EXAMPLE
Conversation history (for reference only):
{history}
Last line of conversation (for extraction):
Human: {input}
Output:`,n3r=new mu({inputVariables:["history","input"],template:Fii}),kii=`You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the "Entity" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.
The update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.
If there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string "UNCHANGED" below.
Full conversation history (for context):
{history}
Entity to summarize:
{entity}
Existing summary of {entity}:
{summary}
Last line of conversation:
Human: {input}
Updated summary (or the exact string "UNCHANGED" if there is no new information about {entity} above):`,o3r=new mu({inputVariables:["entity","summary","history","input"],template:kii});nye();Jo();kL();zL();vS();ta();var qii={};$t(qii,{BaseChatMessageHistory:()=>Uii,BaseListChatMessageHistory:()=>i3r,InMemoryChatMessageHistory:()=>Wce});var Uii=class extends Cg{async addMessages(t){for(let e of t)await this.addMessage(e)}},i3r=class extends Cg{addUserMessage(t){return this.addMessage(new qs(t))}addAIMessage(t){return this.addMessage(new Pn(t))}async addMessages(t){for(let e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},Wce=class extends i3r{constructor(e){super(...arguments);x(this,"lc_namespace",["langchain","stores","message","in_memory"]);x(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};Jo();var Bii={};$t(Bii,{BaseMemory:()=>uW,getInputValue:()=>lW,getOutputValue:()=>Jce,getPromptInputKey:()=>Xje});var uW=class{},a3r=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},lW=(t,e)=>{let r=a3r(t,e);if(!r){let n=Object.keys(t);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},Jce=(t,e)=>{let r=a3r(t,e);if(!r&&r!==""){let n=Object.keys(t);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r};function Xje(t,e){let r=Object.keys(t).filter(n=>!e.includes(n)&&n!=="stop");if(r.length!==1)throw new Error(`One input key expected, but got ${r.length}`);return r[0]}var zii={};$J(zii,{BaseChatMemory:()=>p_});var p_=class extends uW{constructor(e){super();x(this,"chatHistory");x(this,"returnMessages",!1);x(this,"inputKey");x(this,"outputKey");this.chatHistory=e?.chatHistory??new Wce,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}async saveContext(e,r){await this.chatHistory.addUserMessage(lW(e,this.inputKey)),await this.chatHistory.addAIMessage(Jce(r,this.outputKey))}async clear(){await this.chatHistory.clear()}};cW();ta();var Zce=class extends p_{constructor(e){let{returnMessages:r,inputKey:n,outputKey:o,chatHistory:i,humanPrefix:a,aiPrefix:s,llm:u,prompt:l,summaryChatMessageClass:c}=e;super({returnMessages:r,inputKey:n,outputKey:o,chatHistory:i});x(this,"memoryKey","history");x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"llm");x(this,"prompt",t3r);x(this,"summaryChatMessageClass",Od);this.memoryKey=e?.memoryKey??this.memoryKey,this.humanPrefix=a??this.humanPrefix,this.aiPrefix=s??this.aiPrefix,this.llm=u,this.prompt=l??this.prompt,this.summaryChatMessageClass=c??this.summaryChatMessageClass}async predictNewSummary(e,r){let n=fl(e,this.humanPrefix,this.aiPrefix);return await new ag({llm:this.llm,prompt:this.prompt}).predict({summary:r,new_lines:n})}},H3r=class extends Zce{constructor(e){super(e);x(this,"buffer","")}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){return this.returnMessages?{[this.memoryKey]:[new this.summaryChatMessageClass(this.buffer)]}:{[this.memoryKey]:this.buffer}}async saveContext(e,r){await super.saveContext(e,r);let n=await this.chatHistory.getMessages();this.buffer=await this.predictNewSummary(n.slice(-2),this.buffer)}async clear(){await super.clear(),this.buffer=""}};ta();var W3r=class extends Zce{constructor(e){super(e);x(this,"movingSummaryBuffer","");x(this,"maxTokenLimit",2e3);this.maxTokenLimit=e?.maxTokenLimit??this.maxTokenLimit}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();this.movingSummaryBuffer&&(r=[new this.summaryChatMessageClass(this.movingSummaryBuffer),...r]);let n;return this.returnMessages?n=r:n=fl(r,this.humanPrefix,this.aiPrefix),{[this.memoryKey]:n}}async saveContext(e,r){await super.saveContext(e,r),await this.prune()}async prune(){let e=await this.chatHistory.getMessages();this
`);await this.vectorStoreRetriever.addDocuments([new tl({pageContent:o,metadata:n})])}};cW();kL();var K3r=class extends Cg{};var G3r=class extends K3r{constructor(){super();x(this,"lc_namespace",["langchain","stores","entity","in_memory"]);x(this,"store");this.store=Object.create(null)}async get(e,r){return e in this.store?this.store[e]:r}async set(e,r){this.store[e]=r}async delete(e){delete this.store[e]}async exists(e){return e in this.store}async clear(){this.store=Object.create(null)}};ta();var X3r=class extends p_{constructor(e){super({chatHistory:e.chatHistory,returnMessages:e.returnMessages??!1,inputKey:e.inputKey,outputKey:e.outputKey});x(this,"entityExtractionChain");x(this,"entitySummarizationChain");x(this,"entityStore");x(this,"entityCache",[]);x(this,"k",3);x(this,"chatHistoryKey","history");x(this,"llm");x(this,"entitiesKey","entities");x(this,"humanPrefix");x(this,"aiPrefix");this.llm=e.llm,this.humanPrefix=e.humanPrefix,this.aiPrefix=e.aiPrefix,this.chatHistoryKey=e.chatHistoryKey??this.chatHistoryKey,this.entitiesKey=e.entitiesKey??this.entitiesKey,this.entityExtractionChain=new ag({llm:this.llm,prompt:e.entityExtractionPrompt??n3r}),this.entitySummarizationChain=new ag({llm:this.llm,prompt:e.entitySummarizationPrompt??o3r}),this.entityStore=e.entityStore??new G3r,this.entityCache=e.entityCache??this.entityCache,this.k=e.k??this.k}get memoryKeys(){return[this.chatHistoryKey]}get memoryVariables(){return[this.entitiesKey,this.chatHistoryKey]}async loadMemoryVariables(e){let r=this.inputKey??Xje(e,this.memoryVariables),n=await this.chatHistory.getMessages(),o=fl(n.slice(-this.k*2),this.humanPrefix,this.aiPrefix),i=await this.entityExtractionChain.predict({history:o,input:e[r]}),a=i.trim()==="NONE"?[]:i.split(",").map(l=>l.trim()),s={};for(let l of a)s[l]=await this.entityStore.get(l,"No current information known.");this.entityCache=[...a];let u=this.returnMessages?n.slice(-this.k*2):o;return{[this.chatHistoryKey]:u,[this.entitiesKey]:s}}async saveContext(e,r){await super.saveContext(e,r);let n=this.inputKey??Xje(e,this.memoryVariables),o=await this.chatHistory.getMessages(),i=fl(o.slice(-this.k*2),this.humanPrefix,this.aiPrefix),a=e[n];for(let s of this.entityCache){let u=await this.entityStore.get(s,"No current information known."),l=await this.entitySummarizationChain.predict({summary:u,entity:s,history:i,input:a});l.trim()!=="UNCHANGED"&&await this.entityStore.set(s,l.trim())}}async clear(){await super.clear(),await this.entityStore.clear()}};var Z3r=class extends p_{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"memoryKey","history");x(this,"memories",[]);this.memories=e?.memories??this.memories,this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.checkRepeatedMemoryVariable(),this.checkInputKey()}checkRepeatedMemoryVariable(){let e=[];for(let r of this.memories){let n=e.filter(o=>r.memoryKeys.includes(o));if(n.length>0)throw new Error(`The same variables ${[...n]} are found in multiple memory objects, which is not allowed by CombinedMemory.`);e.push(...r.memoryKeys)}}checkInputKey(){for(let e of this.memories)e.chatHistory!==void 0&&e.inputKey===void 0&&console.warn(`When using CombinedMemory, input keys should be set so the input is known. Was not set on ${e}.`)}async loadMemoryVariables(e){let r={};for(let n of this.memories){let o=await n.loadMemoryVariables(e);r={...r,...o}}return r}async saveContext(e,r){for(let n of this.memories)await n.saveContext(e,r)}async clear(){for(let e of this.memories)typeof e.clear=="function"&&await e.clear()}get memoryKeys(){let e=[];for(let r of this.memories)e.push(...r.memoryKeys);return e}};ta();var Y3r=class extends p_{constructor(e){super(e);x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"memoryKey","history");x(this,"maxTokenLimit",2e3);x(this,"llm");this.llm=e.llm,this.humanPrefix=e?.humanPrefix??this.humanPrefix,
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`;this.qaPrompt=Ah.fromMessages([LS.fromTemplate(e)])}escapeTemplateString(e){return e.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){return this.chatPrompt}async getQAPrompt({question:e,context:r,systemMessage:n}){return await this.qaPrompt.format({question:e,context:r,system_message:n})}};var ede=class{constructor(e){this.retrievedDocuments=[];this.pendingModelError=null;this.app=e,this.memoryManager=Yce.getInstance(),this.chatModelManager=tC.getInstance(),this.promptManager=Qce.getInstance(),this.userMemoryManager=new GU(e),this.initialize(),hl(async()=>{await this.createChainWithNewModel()})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}getChain(){return this.chain}getRetrievalChain(){return this.retrievalChain}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(this.pendingModelError)throw this.pendingModelError;if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new zJ(e)}}validateChainInitialization(){(!this.chain||!v1t(this.chain))&&(F("Reinitializing chat chain after detecting missing or unsupported instance."),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n,o=ex(),i=Gu();if(!(o==="project"&&!i))try{if(n=o==="project"?i?.projectModelKey:B_(),!n)throw new zJ("No model key found. Please select a model in settings.");if(r){let a=qS(n,te().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",n),a=hO[0],n=a.name+"|"+a.provider),o==="project"&&!a.projectEnabled){let u=te().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,n=u.name+"|"+u.provider,new Q3r.Notice(`Model ${a.name} is not available in project mode. Switching to ${u.name}.`);else throw new Error("No project-enabled models available. Please enable a model for project mode in settings.")}let s={...a,...i?.modelConfigs};await this.chatModelManager.setChatModel(s),this.pendingModelError=null}this.setChain(o,e),F(`Setting model to ${n}`)}catch(a){this.pendingModelError=a instanceof Error?a:new Error(String(a)),ne(`createChainWithNewModel failed: ${a}`),F(`modelKey: ${n||B_()}`)}}async setChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(e);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=Ate.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),N4("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let s=te().enableSemanticSearchV3?new(await Promise.resolve().then(()=>(_Pe(),Ost))).HybridRetriever({minSimilarityScore:.01,maxK:Ly,salientTerms:[]}):new(await Promise.resolve().then(()=>(xX(),Dmt))).TieredLexicalRetriever(app,{minSimilarityScore:.01,maxK:Ly,salientTerms:[],textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0});this.retrievalChain=Ate.createConversationalRetrievalChain({llm:n,retriever:s,systemMessage:x$()},this.storeRetrieverDocuments.bind(this),te().debug),N4("vault_qa"),te().debug&&(console.log("New Vault QA chain with hybrid retriever created for entire vault"),console.log("Set chain:","vault_qa"));break}case"copilot_plus":{await this.initializeQAChain(r),this.chain=Ate.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),N4("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=Ate.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),N4("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=ex(),r=te();switch(e){case"llm_chain":return new Aae(this);case"vault_qa":return new Cle(this);case"copilot_plus":return r.enableAutonomousAgent?ne
`,s||e.originalMessage||e.message),this.validateChatModel(),this.validateChainInitialization();let u=this.chatModelManager.getChatModel();if(a||Pte(u)){let c=Ah.fromMessages([new pO("history"),$_.fromTemplate("{input}")]);Pte(u)&&(c=Ah.fromMessages([[Zs,x$()||""],c])),this.createChainWithNewModel({prompt:c},!1)}return await this.getChainRunner().run(e,r,n,o,i)}};ra();Xe();Ye();Bt();var o$e=class t{constructor(e){this.app=e}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}clearAllLoadStates(){_Dt({success:[],failed:[],processingFiles:[],total:[]})}async executeWithProcessTracking(e,r,n){this.setFileOrUrlStartProcess(e);try{let o=await n();return this.setFileOrUrlProcessSuccessful(e),o}catch(o){let i=DD(o)?"Rate limit exceeded. (Rate limit: 50 files or 100MB per 3 hours, whichever is reached first)":zr(o);throw this.setFileOrUrlProcessFailed(e,r,i),o}}setFileOrUrlStartProcess(e){No.set(Ute,r=>{let n={...r};return n.failed.find(o=>o.path===e)&&(n.failed=n.failed.filter(o=>o.path!==e)),n.success.includes(e)&&(n.success=n.success.filter(o=>o!==e)),n.processingFiles.includes(e)||(n.processingFiles=[...n.processingFiles,e]),n.total.includes(e)||(n.total=[...n.total,e]),n})}setFileOrUrlProcessSuccessful(e){CO("processingFiles",r=>r.filter(n=>n!==e)),CO("success",r=>r.includes(e)?r:[...r,e])}setFileOrUrlProcessFailed(e,r,n){CO("processingFiles",o=>o.filter(i=>i!==e)),CO("failed",o=>{if(!o.find(a=>a.path===e)){let a={path:e,type:r,error:n,timestamp:Date.now()};return[...o,a]}return o})}preComputeAllItems(e,r){F(`[preComputeAllItems] Starting pre-computation for project: ${e.name}`);let n=[];n.push(...r.map(a=>a.path));let o=e.contextSource?.webUrls?.trim()||"";if(o){let a=o.split(`
`).filter(s=>s.trim());n.push(...a)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let a=i.split(`
`).filter(s=>s.trim());n.push(...a)}if(n.length>0){let a=[...new Set([...n])];CO("total",s=>a),F(`[preComputeAllItems] Project ${e.name}: Added ${n.length} items to tracking (${a.length} total unique items)`)}}markAllCachedItemsAsSuccess(e,r,n){F(`[markAllCachedItemsAsSuccess] Starting for project: ${e.name||"default"}`);let o=e.contextSource?.webUrls?.trim()||"";if(o){let s=o.split(`
`).filter(u=>u.trim()).filter(u=>r.webContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&F(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached Web URLs as successful`)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let s=i.split(`
`).filter(u=>u.trim()).filter(u=>r.youtubeContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&F(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached YouTube URLs as successful`)}if(r.fileContexts){let a=new Set(n.filter(u=>u.extension==="md").map(u=>u.path)),s=Object.keys(r.fileContexts).filter(u=>a.has(u));s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&F(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached files that match current project patterns as successful.`)}}markCachedItemAsSuccess(e){CO("total",r=>r.includes(e)?r:[...r,e]),CO("success",r=>r.includes(e)?r:[...r,e])}makeItemFailed(e,r,n){CO("total",o=>o.includes(e)?o:[...o,e]),CO("failed",o=>{if(!o.find(a=>a.path===e)){let a={path:e,type:r,error:n,timestamp:Date.now()};return[...o,a]}return o})}};var ry=class t{constructor(e,r){this.projectUsageTimestampsManager=new kJ;this.app=e,this.plugin=r,this.currentProjectId=null,this.chainMangerInstance=new ede(e),this.projectContextCache=Fw.getInstance(),this.fileParserManager=new Tq(Ql.getInstance(),this.app.vault,!0,null),this.loadTracker=o$e.getInstance(this.app),mDt(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),hDt(async()=>{if(a5())return;let n=te(),o=n.enableSemanticSearchV3&&n.indexVaultToVectorStore==="ON MODE SWITCH"&&(ex()==="vault_qa"||ex()==="copilot_plus");await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})}),i5(async n=>{await this.switchProject(n)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){hl(async(e,r)=>{if(!e||!r)return;let n=e.projectList||[],o=r.projectList||[];for(let i of o){let a=n.find(s=>s.id===i.id);a&&this.hasMeaningfulProjectConfigChange(a,i)&&(await this.compareAndUpdateCache(a,i),this.currentProjectId===i.id&&await Promise.all([this.loadProjectContext(i,!0),this.getCurrentChainManager().createChainWithNewModel()]))}})}hasMeaningfulProjectConfigChange(e,r){let n={...e,UsageTimestamps:0},o={...r,UsageTimestamps:0};return JSON.stringify(n)!==JSON.stringify(o)}static getInstance(e,r){return t.instance||(t.instance=new t(e,r)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}getCurrentProjectId(){return this.currentProjectId}touchProjectUsageTimestamps(e){this.projectUsageTimestampsManager.touch(e.id);let r=te().projectList||[],n=r.find(i=>i.id===e.id);if(!n)return;let o=this.projectUsageTimestampsManager.shouldPersist(e.id,n.UsageTimestamps);o!==null&&(Re("projectList",r.map(i=>i.id===e.id?{...i,UsageTimestamps:o}:i)),this.projectUsageTimestampsManager.markPersisted(e.id,o))}getProjectUsageTimestampsManager(){return this.projectUsageTimestampsManager}async switchProject(e){try{if(this.loadTracker.clearAllLoadStates(),wO(!0),F("Project loading started..."),!e){await this.saveCurrentProjectMessage(),this.currentProjectId=null,await this.loadNextProjectMessage(),this.refreshChatView();return}let r=e.id;if(this.currentProjectId===r)return;await this.saveCurrentProjectMessage(),this.currentProjectId=r,await this.loadNextProjectMessage(),await this.getCurrentChainManager().createChainWithNewModel(),this.fileParserManager=new Tq(Ql.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),this.touchProjectUsageTimestamps(e),F(`Switched to project: ${e.name}`)}catch(r){throw ne(`Failed to switch project: ${r}`),r}finally{wO(!1)}}async saveCurrentProjectMessage(){await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){await this.plugin.chatUIState.handleProjectSwitch()}async loadProjectContext(e,r=!1){r&&(this.loadTracker.clearAllLoadStates(),wO(!0));try{if(!e.contextSource)return Te(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;F(`[loadProjectContext] Starting for project: ${e.name}`);let n=await this.projectContextCache.getOrInitializeCache(e),o=this.getProjectAllFiles(e);this.loadTracker.preComputeAllItems(e,o),this.loadTracker.markAllCachedItemsAsSuccess(e,n,o);let[i]=await Promise.all([this.processMarkdownFiles(e,n,o),this.processWebUrls(e,n),thi
`).filter(m=>m.trim()),p=l.split(`
`).filter(m=>m.trim());await this.projectContextCache.removeWebUrls(r,f.filter(m=>!p.includes(m)))}let c=e.contextSource?.youtubeUrls||"",d=r.contextSource?.youtubeUrls||"";if(c!==d){let f=c.split(`
`).filter(m=>m.trim()),p=d.split(`
`).filter(m=>m.trim());await this.projectContextCache.removeYoutubeUrls(r,f.filter(m=>!p.includes(m)))}}catch(n){ne(`Error comparing project configurations: ${n}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(Nu)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=te().projectList.find(o=>o.id===e);if(!r)return Te(`[getProjectContext] Project not found for ID: ${e}`),null;F(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?F(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):F(`[getProjectContext] Project ${r.name}: Memory cache miss. Triggering full load.`);let o=await this.loadProjectContext(r,!0);if(!o)return ne(`[getProjectContext] Project ${r.name}: loadProjectContext returned null.`),null;n=o}else F(`[getProjectContext] Project ${r.name}: Memory cache hit and markdown OK. Using existing context.`);return this.formatProjectContextWithFiles(n,r)}async formatProjectContextWithFiles(e,r){let n=[];if(e.markdownContext&&n.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&n.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&n.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let o=Object.entries(e.fileContexts).filter(([i])=>i.split(".").pop()?.toLowerCase()!=="md");if(o.length>0){let i=o.map(async([s,u])=>{let l=s.split("/"),c=l[l.length-1],d=c.split(".").pop()||"",f=await this.projectContextCache.getOrReuseFileContext(r,s)||"[Content not available]";return`[[${c}]]
path: ${s}
type: ${d}
modified: ${new Date(u.timestamp).toISOString()}
${f}`}),a=await Promise.all(i);a.length>0&&n.push(`## Other Files
${a.join(`
`)}`)}}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${n.join(`
`)}
</ProjectContext>
`}formatProjectContext(e){let r=[];if(e.markdownContext&&r.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&r.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&r.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let n="";for(let[o,i]of Object.entries(e.fileContexts)){let a=o.split("/"),s=a[a.length-1],u=s.split(".").pop()||"";n+=`[[${s}]]
path: ${o}
type: ${u}
modified: ${new Date(i.timestamp).toISOString()}
`}n&&r.push(`## Other Files
${n}`)}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${r.join(`
`)}
</ProjectContext>
`}async processMarkdownFiles(e,r,n){if(F(`[processMarkdownFiles] Starting for project: ${e.name}`),r.markdownNeedsReload||!r.markdownContext||!r.markdownContext.trim()){F(`[processMarkdownFiles] Project ${e.name}: Processing markdown content.`);let o=await this.processMarkdownFileContext(n);this.projectContextCache.updateProjectMarkdownFilesFromPatterns(e,r,n),r.markdownContext=o,r.markdownNeedsReload=!1,F(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else F(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`);return F(`[processMarkdownFiles] Completed for project: ${e.name}. Total fileContexts: ${Object.keys(r.fileContexts||{}).length}`),r}async processMarkdownFileContext(e){let r=e.filter(o=>o.extension==="md");F(`Found ${r.length} markdown files to process for project context`);let n=await Promise.all(r.map(async o=>{let i="",a="";try{let[s,u]=await this.loadTracker.executeWithProcessTracking(o.path,"md",async()=>Promise.all([this.app.vault.adapter.stat(o.path),this.app.vault.read(o)]));a=`[[${o.basename}]]
path: ${o.path}
type: ${o.extension}
created: ${s?new Date(s.ctime).toISOString():"unknown"}
modified: ${s?new Date(s.mtime).toISOString():"unknown"}`,i=u,F(`Completed processing markdown file: ${o.path}`)}catch(s){ne(`Error processing file ${o.path}: ${s}`),i=`[Error: ${zr(s)}]`}return`${a}
${i}`}));return F("All markdown files processed for project context"),n.join(`
`)}async processWebUrls(e,r){F(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(F(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());F(`[processWebUrls] Project ${e.name}: Found ${o.length} URLs in config.`);let i=Object.keys(r.webContexts),a=o.filter(c=>!r.webContexts[c]);a.length>0&&F(`[processWebUrls] Project ${e.name}: Fetching content for ${a.length} new/updated Web URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){F(`[processWebUrls] Project ${e.name}: Removing ${s.length} obsolete Web URL contexts.`);for(let c of s)delete r.webContexts[c]}let u=a.map(async c=>{let d=await this.processWebUrlContext(c);return d&&F(`[processWebUrls] Project ${e.name}: Successfully fetched content for URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.webContexts[c.url]=c.context:c&&!c.context&&Te(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),F(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){F(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(F(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());F(`[processYoutubeUrls] Project ${e.name}: Found ${o.length} YouTube URLs in config.`);let i=Object.keys(r.youtubeContexts),a=o.filter(c=>!r.youtubeContexts[c]);a.length>0&&F(`[processYoutubeUrls] Project ${e.name}: Fetching transcripts for ${a.length} new/updated YouTube URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){F(`[processYoutubeUrls] Project ${e.name}: Removing ${s.length} obsolete YouTube URL contexts.`);for(let c of s)delete r.youtubeContexts[c]}let u=a.map(async c=>{let d=await this.processYoutubeUrlContext(c);return d&&F(`[processYoutubeUrls] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.youtubeContexts[c.url]=c.context:c&&!c.context&&Te(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),F(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}async processWebUrlContext(e){if(!e?.trim())return"";try{let r=s9.getInstance(),{urlContext:n}=await this.loadTracker.executeWithProcessTracking(e,"web",async()=>{let o=await r.processUrls(e);if(o.processedErrorUrls[e])throw new Error(o.processedErrorUrls[e]);return o});return n||""}catch(r){return ne(`Failed to process web URL: ${r}`),""}}async processYoutubeUrlContext(e){if(!e?.trim())return"";try{let r=await this.loadTracker.executeWithProcessTracking(e,"youtube",async()=>Ql.getInstance().youtube4llm(e));return r.response.transcript?`
YouTube transcript from ${e}:
${r.response.transcript}`:""}catch(r){return ne(`Failed to process YouTube URL ${e}: ${r}`),new dW.Notice(`Failed to process YouTube URL ${e}: ${zr(r)}`),""}}async processNonMarkdownFiles(e,r){let n=r.filter(i=>i.extension!=="md");if(F(`[loadProjectContext] Project ${e.name}: Checking for non-markdown processing: ${n.length} files .`),n.length<=0)return;this.fileParserManager=new Tq(Ql.getInstance(),this.app.vault,!0,e);let o=0;for(let i of n){let a=i.path;if(this.fileParserManager.supportsExtension(i.extension))try{await this.loadTracker.executeWithProcessTracking(a,"nonMd",async()=>{await this.projectContextCache.getOrReuseFileContext(e,a)||(F(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${a}`),await this.fileParserManager.parseFile(i,this.app.vault)),o++})}catch(s){if(ne(`[loadProjectContext] Project ${e.name}: Error parsing file ${a}:`,s),DD(s))throw s}}o>0&&F(`[loadProjectContext] Project ${e.name}: Processed and cached ${o} non-markdown files.`)}async retryFailedItem(e){try{if(!this.currentProjectId){Te("[retryFailedItem] No current project, aborting retry");return}let r=te().projectList.find(n=>n.id===this.currentProjectId);if(!r){ne(`[retryFailedItem] Current project not found: ${this.currentProjectId}`);return}switch(F(`[retryFailedItem] Starting retry for ${e.type} item: ${e.path}`),e.type){case"web":await this.retryWebUrl(r,e.path);break;case"youtube":await this.retryYoutubeUrl(r,e.path);break;case"md":await this.retryMarkdownFile(r,e.path);break;case"nonMd":await this.retryNonMarkdownFile(r,e.path);break;default:Te(`[retryFailedItem] Unknown item type: ${e.type}`);return}F(`[retryFailedItem] Successfully retried ${e.type} item: ${e.path}`),new dW.Notice(`Retry successful: ${e.path}`)}catch(r){ne(`[retryFailedItem] Failed to retry ${e.type} item ${e.path}:`,r),new dW.Notice(`Retry failed: ${zr(r)}`)}}async retryWebUrl(e,r){let n=await this.processWebUrlContext(r);if(!n){Te(`[retryWebUrl] Project ${e.name}: Fetched empty content for Web URL: ${r}`);return}F(`[retryWebUrl] Project ${e.name}: Successfully fetched content for URL: ${r.substring(0,50)}...`),await this.projectContextCache.updateWebUrl(e,r,n)}async retryYoutubeUrl(e,r){let n=await this.processYoutubeUrlContext(r);if(!n){Te(`[retryYoutubeUrl] Project ${e.name}: Fetched empty transcript for YouTube URL: ${r}`);return}F(`[retryYoutubeUrl] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${r.substring(0,50)}...`),await this.projectContextCache.updateYoutubeUrl(e,r,n)}async retryMarkdownFile(e,r){let n=this.app.vault.getAbstractFileByPath(r);if(!(n instanceof dW.TFile)||n.extension!=="md")throw new Error(`File not found or not a markdown file: ${r}`);try{await this.loadTracker.executeWithProcessTracking(n.path,"md",async()=>{}),F(`[retryMarkdownFile] Successfully reprocessed markdown file: ${r}`),await this.projectContextCache.invalidateMarkdownContext(e)}catch(o){throw ne(`[retryMarkdownFile] Error processing file ${r}: ${o}`),o}}async retryNonMarkdownFile(e,r){let n=this.app.vault.getAbstractFileByPath(r);if(!(n instanceof dW.TFile)||n.extension==="md")throw new Error(`File not found or is a markdown file: ${r}`);if(!this.fileParserManager.supportsExtension(n.extension))throw new Error(`Unsupported file extension: ${n.extension}`);try{await this.loadTracker.executeWithProcessTracking(r,"nonMd",async()=>this.fileParserManager.parseFile(n,this.app.vault)),F(`[retryNonMarkdownFile] Successfully reprocessed non-markdown file: ${r}`)}catch(o){throw ne(`[retryNonMarkdownFile] Error processing file ${r}: ${o}`),o}}getProjectAllFiles(e){let{inclusions:r,exclusions:n}=el({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0});return this.app.vault.getFiles().filter(o=>Hs(o,r,n,!0))}onunload(){this.projectContextCache.cleanup()}};ra();O4();Xe();var NWr=require("obsidian");Cn();var i$e=$(J());$r();var ri=i$e.forwardRef(({className:t,type:e,...r},n)=>i$e.createElement("input",{type:e,className:we("!tw-h-9 !tw-min-w-[50px] !tw-rounded-md !tw-border tw-border-solid tw-border-border
2026-01-05 13:03:55 +08:00
1. Preserve the meaning and tone
2. Maintain appropriate cultural context
3. Keep formatting and structure
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:
1. Each tweet must be under 240 characters
2. Start with "THREAD START" on its own line
3. Separate tweets with "
---
"
4. End with "THREAD END" on its own line
5. Make content engaging and clear
2026-01-21 08:46:13 +08:00
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.
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
IMPORTANT: If no YouTube video context is found, remind the user to:
1. Open a YouTube video in Web Viewer (or use @ to select a YouTube web tab)
2. Then use this command again
Generate the note with this exact structure:
---
title: "<video title>"
description: "<first 200 chars of description>"
channel: "<channel name>"
url: "<video url>"
duration: "<duration>"
published: <upload date in YYYY-MM-DD format>
thumbnailUrl: "<YouTube thumbnail URL: i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg with https protocol>"
genre:
- "<genre>"
watched:
---
![<video title>](<video url>)
> [!summary]- Description
> <full video description, preserve line breaks>
## Summary
<Brief 2-3 paragraph summary of the video 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
- Do NOT use icons or emojis
- Keep all node text short and simple - max 3-4 words per node
- Use only letters, numbers, and spaces
Example of CORRECT syntax:
\`\`\`mermaid
mindmap
root(Video Main Topic)
First Theme
Detail one
Detail two
Second Theme
Detail three
Third Theme
\`\`\`
## Notable Quotes
<List 5-10 notable quotes from the transcript. Format each as:>
- [<timestamp>: <quote text>](<video_url>&t=<seconds>s)
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>
2026-02-24 07:55:02 +08:00
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1140,modelKey:"",lastUsedMs:0}];Xe();var lZ=require("obsidian");Ye();XC();XC();var pW=pF(),mW=bc([]),Mgt=new Set;function hW(t){Mgt.add(t)}function gW(t){Mgt.delete(t)}function rde(t){return Mgt.has(t)}function nde(t){let e=pW.get(mW);pW.set(mW,e.filter(r=>r.title!==t))}function yW(t,e){let r=pW.get(mW),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],pW.set(mW,n)}function h$e(t){pW.set(mW,t)}function g$e(){return L_(mW,{store:pW})}function Pv(){return pW.get(mW)}Nte();Bt();l1();mr();function y$e(t,e,r){let n=t.trim();return n?t!==n?"Command name cannot have leading or trailing spaces":r&&t===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A command with this name already exists":null:"Command name cannot be empty"}function cZ(t){return encodeURIComponent(t.toLowerCase())}function mB(){return(0,lZ.normalizePath)(te().customPromptsFolder)}function dZ(t){return`${mB()}/${t}.md`}function fZ(t){if(!(t instanceof lZ.TFile)||t.extension!=="md")return!1;let e=mB();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function IWr(t){return app.metadataCache.getFileCache(t)?.frontmatter?.[cN]!=null}async function ode(t){let e=await app.vault.read(t),r=HJ(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[$$]??lN.showInContextMenu,i=n?.frontmatter?.[L$]??lN.showInSlashMenu,a=n?.frontmatter?.[k$]??lN.lastUsedMs,s=n?.frontmatter?.[cN]??lN.order,u=n?.frontmatter?.[F$]??lN.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}async function b$e(){let t=app.vault.getFiles().filter(r=>fZ(r)),e=await Promise.all(t.map(ode));return h$e(e),e}function ide(t){return mO(t,"manual",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0,getManualOrder:e=>e.order})}function Nai(t){return mO(t,"recent",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:e=>e.lastUsedMs})}function Dai(t){return mO(t,"name",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0})}function _$e(t){switch(te().promptSortStrategy){case"timestamp":return Nai(t);case"alphabetical":return Dai(t);case"manual":return ide(t);default:return t}}async function ade(t,e,r=!1){let o=(await sde(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${q_}}`)||r)return o;let i=o.indexOf(Pgt);return i===-1?e.trim()?o+`
2026-01-21 08:46:13 +08:00
2026-02-24 07:55:02 +08:00
<`+q_+">"+e+"</"+q_+">":o:o.slice(0,i)+e+o.slice(i+Pgt.length)}var jai=/\{(?!copilot-selection\}|\[\[)([^}]+)\}/g;async function $ai(t,e,r){let n=new Map,o=new Set,i;for(;(i=jai.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]},u=a.toLowerCase();if(u==="activenote")if(r){let l=await WJ(r,e);l&&(s.content=`<${R4}>
2026-01-05 13:03:55 +08:00
<path>${r.path}</path>
2026-02-24 07:55:02 +08:00
## ${hye(r)}
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
${l}
2026-02-24 07:55:02 +08:00
</${R4}>`,s.files.push(r))}else new lZ.Notice("No active note found.");else{if(u==="activewebtab")continue;if(a.startsWith("#")){let l=a.slice(1).split(",").map(f=>f.trim()),c=await mye(e,l),d=[];for(let f of c){let p=await WJ(f,e);p&&(d.push(`<${R4}>
2026-01-05 13:03:55 +08:00
<path>${f.path}</path>
2026-02-24 07:55:02 +08:00
## ${hye(f)}
2026-01-21 08:46:13 +08:00
${p}
2026-02-24 07:55:02 +08:00
</${R4}>`),s.files.push(f))}s.content=d.join(`
2026-01-21 08:46:13 +08:00
2026-02-24 07:55:02 +08:00
`)}else{let l=x1t(a),c=await Ote(e,l),d=[];for(let f of c){let p=await WJ(f,e);p&&(d.push(`<${R4}>
2026-01-21 08:46:13 +08:00
<path>${f.path}</path>
2026-02-24 07:55:02 +08:00
## ${hye(f)}
2026-01-21 08:46:13 +08:00
${p}
2026-02-24 07:55:02 +08:00
</${R4}>`),s.files.push(f))}s.content=d.join(`
2026-01-21 08:46:13 +08:00
2026-02-24 07:55:02 +08:00
`)}}s.content?(n.set(a,s.content),s.files.forEach(l=>o.add(l))):u!=="activenote"&&u!=="activewebtab"&&(a.startsWith('"')||Te(`No notes found for variable: ${a}`))}return{variablesMap:n,includedFiles:o}}async function sde(t,e,r,n,o=!1){let i=te(),a=new Set;if(!i.enableCustomPromptTemplating)return!o&&t.includes("{}")&&!e&&n&&a.add(n),{processedPrompt:t+`
2026-01-21 08:46:13 +08:00
2026-02-24 07:55:02 +08:00
`,includedFiles:Array.from(a)};let{variablesMap:s,includedFiles:u}=await $ai(t,r,n);u.forEach(p=>a.add(p));let l=t,c="",d=null;!o&&l.includes("{}")&&(l=l.replace(/\{\}/g,`{${q_}}`),e?c+=`<${q_}>
2026-01-21 08:46:13 +08:00
${e}
2026-02-24 07:55:02 +08:00
</${q_}>`:n?(d=await WJ(n,r),c+=`<${q_} type="active_note">
2026-01-21 08:46:13 +08:00
${d||""}
2026-02-24 07:55:02 +08:00
</${q_}>`,a.add(n)):c+=`<${q_}>
2026-01-21 08:46:13 +08:00
(No selected text or active note available)
2026-02-24 07:55:02 +08:00
</${q_}>`);for(let[p,m]of s.entries())p.toLowerCase()==="activenote"&&d!==null||(c?c+=`
2026-01-21 08:46:13 +08:00
2026-02-24 07:55:02 +08:00
<${jte} name="${p}">
2026-01-21 08:46:13 +08:00
${m}
2026-02-24 07:55:02 +08:00
</${jte}>`:c+=`<${jte} name="${p}">
2026-01-21 08:46:13 +08:00
${m}
2026-02-24 07:55:02 +08:00
</${jte}>`);let f=C1t(l,r);for(let p of f)if(!a.has(p)){let m=await WJ(p,r);if(m){let h=await r.adapter.stat(p.path),y=h?new Date(h.ctime).toISOString():"Unknown",g=h?new Date(h.mtime).toISOString():"Unknown",b=`<${Dte}>
2026-01-21 08:46:13 +08:00
<title>${p.basename}</title>
<path>${p.path}</path>
<ctime>${y}</ctime>
2026-01-05 13:03:55 +08:00
<mtime>${g}</mtime>
<content>
2026-01-21 08:46:13 +08:00
${m}
2026-01-05 13:03:55 +08:00
</content>
2026-02-24 07:55:02 +08:00
</${Dte}>`;c&&(c+=`
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
`),c+=`${b}`,a.add(p)}}return{processedPrompt:c?`${l}
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
${c}`:`${l}
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`,includedFiles:Array.from(a)}}function AWr(t,e){let n=`${t} (copy)`,o=1;for(;e.some(i=>i.title.toLowerCase()===n.toLowerCase());)o++,n=`${t} (copy ${o})`;return n}function v$e(){let e=Pv().reduce((r,n)=>r>n.order?r:n.order,0);return e===Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+10}async function Rgt(t,e){try{hW(t.path),await app.fileManager.processFrontMatter(t,r=>{r[$$]==null&&(r[$$]=e.showInContextMenu),r[L$]==null&&(r[L$]=e.showInSlashMenu),r[cN]==null&&(r[cN]=e.order),r[F$]==null&&(r[F$]=e.modelKey),r[k$]==null&&(r[k$]=e.lastUsedMs)})}finally{gW(t.path)}}function Lai({commands:t,command:e,onConfirm:r,onCancel:n}){let i=Br().activeModels.filter(f=>f.enabled).map(f=>({label:PWr(f),value:no(f)})),[a,s]=(0,Ls.useState)(e),[u,l]=(0,Ls.useState)({}),c=(f,p)=>{s(m=>({...m,[f]:p})),l(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=y$e(a.title,t,e.title);if(p&&(f.title=p),a.content.trim()||(f.content="Prompt is required"),Object.keys(f).length>0){l(f);return}r(a)};return Ls.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},Ls.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ls.default.createElement(Xc,{htmlFor:"title"},"Name"),Ls.default.createElement(ri,{id:"title",value:a.title,onChange:f=>c("title",f.target.value),placeholder:"Enter command name"}),u.title&&Ls.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.title)),Ls.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ls.default.createElement(Xc,{htmlFor:"content"},"Prompt"),Ls.default.createElement(MWr,null),Ls.default.createElement(h_,{id:"content",value:a.content,onChange:f=>c("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),u.content&&Ls.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.content)),Ls.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ls.default.createElement(Xc,{htmlFor:"modelKey"},"Model (Optional)"),Ls.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},Ls.default.createElement("select",{value:a.modelKey,onChange:f=>{let p=f.target.value;if(!p){c("modelKey","");return}if(!i.find(h=>h.value===p)){ne(`Model ${p} not found`),c("modelKey","");return}c("modelKey",f.target.value)},className:we("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-text-sm !tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal")},Ls.default.createElement("option",{value:""},"Inherit from chat model"),i.map(f=>Ls.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),Ls.default.createElement("div",{className:we("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal")},Ls.default.createElement(Wi,{className:"tw-size-4"})))),Ls.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ls.default.createElement(Rl,{id:"showInContextMenu",checked:a.showInContextMenu,onCheckedChange:f=>c("showInContextMenu",f)}),Ls.default.createElement(Xc,{htmlFor:"showInContextMenu"},"Show in context menu")),Ls.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ls.default.createElement(Rl,{id:"showInSlashMenu",checked:a.showInSlashMenu,onCheckedChange:f=>c("showInSlashMenu",f)}),Ls.default.createElement(Xc,{htmlFor:"showInSlashMenu"},"Show in slash menu")),Ls.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Ls.default.createElement(pe,{variant:"secondary",onClick:n},"Cancel"),Ls.default.createElement(pe,{variant:"default",onClick:d},"Save")))}var hB=class extends NWr.Modal{constructor(r,n,o,i){super(r);this.commands=n;this.command=o;this.onUpdate=i;this.setTitle("Edit Command")}onOpen(){let{contentEl:r}=this;this.root=(0,DWr.createRoot)(r);let n=o=>{this.onUpdate(o),this.close()};this
2026-01-05 13:03:55 +08:00
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).
2026-02-24 07:55:02 +08:00
`;function S$e(t,e){if(!e)return t;let r=t.includes("{}"),n=/\{activenote\}/i.test(t),o=[];return r||o.push("{}"),n||o.push("{activeNote}"),o.length>0?t+`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
${o.join(`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`)}`:t}ra();var Igt=$(J());$r();function Agt({onMouseDown:t,className:e}){return Igt.createElement("div",{className:we("tw-flex tw-h-4 tw-items-center tw-justify-center","tw-cursor-grab active:tw-cursor-grabbing","hover:tw-bg-[color-mix(in_srgb,var(--background-modifier-hover)_20%,transparent)]",e),onMouseDown:t},Igt.createElement("div",{className:"tw-h-[5px] tw-w-16 tw-rounded-sm tw-bg-[color-mix(in_srgb,var(--text-muted)_40%,transparent)] hover:tw-bg-[color-mix(in_srgb,var(--text-muted)_65%,transparent)]"}))}var Ngt=$(J());Or();$r();Cn();function Dgt({onClose:t,className:e}){return Ngt.createElement(pe,{className:we("tw-absolute tw-right-2 tw-top-1 tw-rounded tw-p-1 tw-text-normal",e),variant:"ghost2",onClick:t,title:"Close","aria-label":"Close"},Ngt.createElement(qo,{className:"tw-size-4"}))}var C$e=$(J());Or();$r();function jgt({icon:t,label:e,className:r}){let n=t===null?null:t!==void 0?t:C$e.createElement(JF,{className:"tw-size-4 tw-text-muted"});return C$e.createElement("div",{className:we("tw-flex tw-flex-none tw-items-center tw-justify-center tw-gap-2","tw-px-4 tw-py-2",r)},n,C$e.createElement("span",{className:"tw-truncate tw-text-sm tw-font-medium tw-text-normal"},e))}var OW=$(J());$r();Or();Cn();Cn();var bde=$(J());var ni=$(J(),1);var kEs=!!(typeof window<"u"&&window.document&&window.document.createElement);function bW(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var $Wr=$(J(),1);function jWr(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function $gt(...t){return e=>{let r=!1,n=t.map(o=>{let i=jWr(o,e);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let o=0;o<n.length;o++){let i=n[o];typeof i=="function"?i():jWr(t[o],null)}}}}function lde(...t){return $Wr.useCallback($gt(...t),t)}var q$=$(J(),1),LWr=$(St(),1);function FWr(t,e=[]){let r=[];function n(i,a){let s=q$.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,y=q$.useMemo(()=>m,Object.values(m));return(0,LWr.jsx)(h.Provider,{value:y,children:p})};l.displayName=i+"Provider";function c(d,f){let p=f?.[t]?.[u]||s,m=q$.useContext(p);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}let o=()=>{let i=r.map(a=>q$.createContext(a));return function(s){let u=s?.[t]||i;return q$.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};return o.scopeName=t,[n,Fai(o,...e)]}function Fai(...t){let e=t[0];if(t.length===1)return e;let r=()=>{let n=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return q$.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return r.scopeName=e.scopeName,r}var Ic=$(J(),1);var zEs=!!(typeof window<"u"&&window.document&&window.document.createElement);function x$e(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var BWr=$(J(),1),zWr=$(hu(),1);var rh=$(J(),1);var qWr=$(J(),1);function kWr(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Lgt(...t){return e=>{let r=!1,n=t.map(o=>{let i=kWr(o,e);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let o=0;o<n.length;o++){let i=n[o];typeof i=="function"?i():kWr(t[o],null)}}}}function Fgt(...t){return qWr.useCallback(Lgt(...t),t)}var T$e=$(St(),1);function UWr(t){let e=kai(t),r=rh.forwardRef((n,o)=>{let{children:i,...a}=n,s=rh.Children.toArray(i),u=s.find(Uai);if(u){let l=u.props.children,c=s.map(d=>d===u?rh.Children.count(l)>1?rh.Children.only(null):rh.isValidElement(l)?l.props.children:null:d);return(0,T$e.jsx)(e,{...a,ref:o,children:rh.isValidElement(l)?rh.cloneElement(l,void 0,c):null})}return(0,T$e.jsx)(e,{...a,ref:o,children:i})});return r.displayName=`${t}.Slot`,r}function kai(t){let e=rh.forwardRef((r,n)=>{let{children:o,...i}=r;if(rh.isValidElement(o)){let a=zai(o),s=Bai(i,o.props);return o.type!==rh.Fragment&&(s.ref=n?Lgt(n,a):a),rh.cloneElement(o,s)}return rh.Children.count(o)>1?rh.Chil
.`.concat(Ryt,` {
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
}
body[`).concat(PZ,`] {
overflow: hidden `).concat(n,`;
overscroll-behavior: contain;
`).concat([e&&"position: relative ".concat(n,";"),r==="margin"&&`
padding-left: `.concat(o,`px;
padding-top: `).concat(i,`px;
padding-right: `).concat(a,`px;
margin-left:0;
margin-top:0;
margin-right: `).concat(s,"px ").concat(n,`;
`),r==="padding"&&"padding-right: ".concat(s,"px ").concat(n,";")].filter(Boolean).join(""),`
}
.`).concat(PW,` {
right: `).concat(s,"px ").concat(n,`;
}
.`).concat(MW,` {
margin-right: `).concat(s,"px ").concat(n,`;
}
.`).concat(PW," .").concat(PW,` {
right: 0 `).concat(n,`;
}
.`).concat(MW," .").concat(MW,` {
margin-right: 0 `).concat(n,`;
}
body[`).concat(PZ,`] {
`).concat(Iyt,": ").concat(s,`px;
}
`)},AKr=function(){var t=parseInt(document.body.getAttribute(PZ)||"0",10);return isFinite(t)?t:0},Rci=function(){MZ.useEffect(function(){return document.body.setAttribute(PZ,(AKr()+1).toString()),function(){var t=AKr()-1;t<=0?document.body.removeAttribute(PZ):document.body.setAttribute(PZ,t.toString())}},[])},qyt=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;Rci();var i=MZ.useMemo(function(){return kyt(o)},[o]);return MZ.createElement(Pci,{styles:Mci(i,!e,o,r?"":"!important")})};var Uyt=!1;if(typeof window<"u")try{Ode=Object.defineProperty({},"passive",{get:function(){return Uyt=!0,!0}}),window.addEventListener("test",Ode,Ode),window.removeEventListener("test",Ode,Ode)}catch{Uyt=!1}var Ode,RW=Uyt?{passive:!1}:!1;var Ici=function(t){return t.tagName==="TEXTAREA"},NKr=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!Ici(t)&&r[e]==="visible")},Aci=function(t){return NKr(t,"overflowY")},Nci=function(t){return NKr(t,"overflowX")},Byt=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=DKr(t,n);if(o){var i=jKr(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},Dci=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},jci=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},DKr=function(t,e){return t==="v"?Aci(e):Nci(e)},jKr=function(t,e){return t==="v"?Dci(e):jci(e)},$ci=function(t,e){return t==="h"&&e==="rtl"?-1:1},$Kr=function(t,e,r,n,o){var i=$ci(t,window.getComputedStyle(e).direction),a=i*n,s=r.target,u=e.contains(s),l=!1,c=a>0,d=0,f=0;do{if(!s)break;var p=jKr(t,s),m=p[0],h=p[1],y=p[2],g=h-y-i*m;(m||g)&&DKr(t,s)&&(d+=g,f+=m);var b=s.parentNode;s=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!u&&s!==document.body||u&&(e.contains(s)||e===s));return(c&&(o&&Math.abs(d)<1||!o&&a>d)||!c&&(o&&Math.abs(f)<1||!o&&-a>f))&&(l=!0),l};var vLe=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},LKr=function(t){return[t.deltaX,t.deltaY]},FKr=function(t){return t&&"current"in t?t.current:t},Lci=function(t,e){return t[0]===e[0]&&t[1]===e[1]},Fci=function(t){return`
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},kci=0,RZ=[];function kKr(t){var e=Il.useRef([]),r=Il.useRef([0,0]),n=Il.useRef(),o=Il.useState(kci++)[0],i=Il.useState(Tde)[0],a=Il.useRef(t);Il.useEffect(function(){a.current=t},[t]),Il.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=CKr([t.lockRef.current],(t.shards||[]).map(FKr),!0).filter(Boolean);return h.forEach(function(y){return y.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=Il.useCallback(function(h,y){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=vLe(h),b=r.current,_="deltaX"in h?h.deltaX:b[0]-g[0],w="deltaY"in h?h.deltaY:b[1]-g[1],T,O=h.target,E=Math.abs(_)>Math.abs(w)?"h":"v";if("touches"in h&&E==="h"&&O.type==="range")return!1;var P=Byt(E,O);if(!P)return!0;if(P?T=E:(T=E==="v"?"h":"v",P=Byt(E,O)),!P)return!1;if(!n.current&&"changedTouches"in h&&(_||w)&&(n.current=T),!T)return!0;var R=n.current||T;return $Kr(R,y,h,R==="h"?_:w,!0)},[]),u=Il.useCallback(function(h){var y=h;if(!(!RZ.length||RZ[RZ.length-1]!==i)){var g="deltaY"in y?LKr(y):vLe(y),b=e.current.filter(function(T){return T.name===y.type&&(T.target===y.target||y.target===T.shadowParent)&&Lci(T.delta,g)})[0];if(b&&b.should){y.cancelable&&y.preventDefault();return}if(!b){var _=(a.current.shards||[]).map(FKr).filter(Boolean).filter(function(T){return T.contains(y.target)}),w=_.length>0?s(y,_[0]):!a.current.noIsolation;w&&y.cancelable&&y.preventDefault()}}},[]),l=Il.useCallback(function(h,y,g,b){var _={name:h,delta:y,target:g,should:b,shadowParent:qci(g)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(w){return w!==_})},1)},[]),c=Il.useCallback(function(h){r.current=vLe(h),n.current=void 0},[]),d=Il.useCallback(function(h){l(h.type,LKr(h),h.target,s(h,t.lockRef.current))},[]),f=Il.useCallback(function(h){l(h.type,vLe(h),h.target,s(h,t.lockRef.current))},[]);Il.useEffect(function(){return RZ.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,RW),document.addEventListener("touchmove",u,RW),document.addEventListener("touchstart",c,RW),function(){RZ=RZ.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,RW),document.removeEventListener("touchmove",u,RW),document.removeEventListener("touchstart",c,RW)}},[]);var p=t.removeScrollBar,m=t.inert;return Il.createElement(Il.Fragment,null,m?Il.createElement(i,{styles:Fci(o)}):null,p?Il.createElement(qyt,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function qci(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var qKr=Dyt(_Le,kKr);var UKr=wLe.forwardRef(function(t,e){return wLe.createElement(xde,Nv({},t,{ref:e,sideCar:qKr}))});UKr.classNames=xde.classNames;var Z$=UKr;var Ro=$(St(),1),zyt=["Enter"," "],Uci=["ArrowDown","PageUp","Home"],zKr=["ArrowUp","PageDown","End"],Bci=[...Uci,...zKr],zci={ltr:[...zyt,"ArrowRight"],rtl:[...zyt,"ArrowLeft"]},Vci={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Rde="Menu",[Pde,Hci,Wci]=vB(Rde),[IW,Vyt]=N5r(Rde,[Wci,fC,Pyt]),Ide=fC(),VKr=Pyt(),[HKr,OB]=IW(Rde),[Jci,Ade]=IW(Rde),WKr=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=Ide(e),[u,l]=Wr.useState(null),c=Wr.useRef(!1),d=pLe(i),f=D5r(o);return Wr.useEffect(()=>{let p=()=>{c.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>c.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),(0,Ro.jsx)(z$,{...s,children:(0,Ro.jsx)(HKr,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,Ro.jsx)(Jci,{scope:e,onClose:Wr.useCallb
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
Source: ${d.url}
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
${d.transcript}`;await navigator.clipboard.writeText(w),new NZ.Notice("Transcript copied to clipboard!")}catch(w){ne("Failed to copy to clipboard:",w),new NZ.Notice("Failed to copy to clipboard")}},g=async()=>{if(d)try{let w=`# YouTube Video Transcript
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
Source: ${d.url}
${d.transcript}`;await KJ(w,!1),t()}catch(w){ne("Failed to insert to note:",w),new NZ.Notice("Failed to insert to note")}},b=()=>{r("input"),o(""),u(""),f(null)},_=w=>{w.key==="Enter"&&!i&&l&&h()};return e==="display"&&d?Bu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Bu.createElement("div",{className:"tw-rounded tw-bg-secondary tw-p-3"},Bu.createElement("a",{href:d.url,className:"tw-text-sm tw-text-muted hover:tw-text-normal",target:"_blank",rel:"noopener noreferrer"},d.url)),Bu.createElement("div",{className:"tw-max-h-96 tw-overflow-y-auto tw-rounded tw-border tw-border-border tw-bg-primary tw-p-4"},Bu.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-sm tw-leading-relaxed"},d.transcript)),Bu.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Bu.createElement(pe,{variant:"ghost",onClick:b},"Download Another"),Bu.createElement(pe,{variant:"default",onClick:y},"Copy to Clipboard"),Bu.createElement(pe,{variant:"default",onClick:g},"Insert at Cursor"),Bu.createElement(pe,{variant:"secondary",onClick:t},"Close"))):Bu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Bu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Bu.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enter a valid YouTube video URL"),Bu.createElement(ri,{placeholder:"https://www.youtube.com/watch?v=...",value:n,onChange:w=>m(w.target.value),onKeyDown:_,disabled:i}),s&&Bu.createElement("div",{className:"tw-text-sm tw-text-error"},s)),Bu.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Bu.createElement(pe,{variant:"secondary",onClick:t,disabled:i},"Cancel"),Bu.createElement(pe,{variant:"default",onClick:h,disabled:i||!l},i?"Downloading...":"Download Transcript")))}var MLe=class extends NZ.Modal{constructor(e){super(e),this.setTitle("Download YouTube Script (plus)")}onOpen(){let{contentEl:e}=this;this.root=(0,Y8r.createRoot)(e);let r=()=>{this.close()};this.root.render(Bu.createElement(Xdi,{onClose:r}))}onClose(){this.root.unmount()}};Fc();ob();Bt();var oi=require("obsidian");qN();mr();ra();function lg(t,e,r){t.addCommand({id:e,name:xye[e],callback:r})}function jGr(t,e,r){t.addCommand({id:e,name:xye[e],editorCallback:r})}function $Gr(t,e,r){t.addCommand({id:e,name:xye[e],checkCallback:r})}function Obt(t,e,r){jGr(t,Sn.COUNT_WORD_AND_TOKENS_SELECTION,async n=>{let o=await n.getSelection(),i=o.split(" ").length,a=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(o);new oi.Notice(`Selected text contains ${i} words and ${a} tokens.`)}),lg(t,Sn.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await Kit(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);new oi.Notice(`Total tokens in your vault: ${o}`)}catch(n){ne("Error counting tokens: ",n),new oi.Notice("An error occurred while counting tokens.")}}),lg(t,Sn.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),lg(t,Sn.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),lg(t,Sn.NEW_CHAT,()=>{c9(),t.newChat()}),$Gr(t,Sn.TRIGGER_QUICK_COMMAND,n=>{let o=t.app.workspace.getActiveViewOfType(oi.MarkdownView);if(n)return!!(!Ite()&&o&&o.editor);if(Ite())return new oi.Notice("Quick command is not available in source mode."),!1;if(!o||!o.editor)return new oi.Notice("No active editor found."),!1;let a=o.editor.getSelection();if(!a.trim())return new oi.Notice("Please select some text first. Selected text is required for quick commands."),!1;let s={title:"Quick Command",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:0,modelKey:"",lastUsedMs:Date.now()};return new EB(t.app,{selectedText:a,command:s,systemPrompt:w$e,behaviorConfig:{autoExecuteOnOpen:!1,hideContentAreaOnIdle:!0,commandLabel:"Quick Command",commandIcon:null,showIncludeNoteContext:!0,modelSelectionScope:"quick-command",firstSubmitTransform:(l,c)=>S$e(l,c)}}).open(),!0}),lg(t,Sn.CLEAR_LOCAL_COPILOT_INDEX,async()=>{try{await(await Promise.resolve().then(()=>(Pl(),Vc))).default.getInstance().clearIndex(),new oi.Notice("Cleared local Copilot semantic index.")}catch(n){ne("Error clearing semantic index:",n),
`),h=`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`,y="copilot",g=`${y}/${h}`;await $c(y);let b=t.app.vault.getAbstractFileByPath(g);b?await t.app.vault.modify(b,m):await t.app.vault.create(g,m);let _=t.app.vault.getAbstractFileByPath(g);_&&(await t.app.workspace.getLeaf().openFile(_),new oi.Notice(`Listed ${p.size} indexed files`))}catch(n){ne("Error listing indexed files:",n),new oi.Notice("Failed to list indexed files.")}}),lg(t,Sn.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,async()=>{try{let n=t.app.workspace.getActiveFile();if(!n){new oi.Notice("No active file. Please open a note first.");return}let o=(await Promise.resolve().then(()=>(Pl(),Vc))).default,{DBOperations:i}=await Promise.resolve().then(()=>(FEe(),N_r)),a=await o.getInstance().getDb(),s=await i.getDocsByPath(a,n.path);if(!s||s.length===0){new oi.Notice(`No embedding data found for: ${n.path}`);return}let u=s.map(h=>h.document),l=[`# Embedding Debug: ${n.basename}`,"",`**Path:** ${n.path}`,`**Chunks:** ${u.length}`,`**Embedding Model:** ${u[0]?.embeddingModel||"unknown"}`,"",...u.flatMap((h,y)=>{let g=h.embedding||[],b=g.slice(0,10).map(_=>_.toFixed(6)).join(", ");return[`## Chunk ${y+1}`,`- **ID:** ${h.id}`,`- **Content Preview:** "${(h.content||"").substring(0,200)}..."`,`- **Vector Length:** ${g.length}`,`- **Vector Preview:** [${b}${g.length>10?", ...":""}]`,`- **Tags:** ${(h.tags||[]).join(", ")||"none"}`,`- **Characters:** ${h.nchars||0}`,""]})].join(`
`),c=`Copilot-Embedding-Debug-${n.basename.replace(/[\\/:*?"<>|]/g,"_")}.md`,d="copilot",f=`${d}/${c}`;await $c(d);let p=t.app.vault.getAbstractFileByPath(f);p?await t.app.vault.modify(p,l):await t.app.vault.create(f,l);let m=t.app.vault.getAbstractFileByPath(f);m&&(await t.app.workspace.getLeaf().openFile(m),new oi.Notice(`Embedding debug info for ${u.length} chunk(s)`))}catch(n){ne("Error inspecting embeddings:",n),new oi.Notice("Failed to inspect embeddings. Is the index loaded?")}}),lg(t,Sn.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await Fw.getInstance().clearAllCache(),await i9.getInstance().clear(),new oi.Notice("All Copilot caches cleared successfully")}catch(n){ne("Error clearing Copilot caches:",n),new oi.Notice("Failed to clear Copilot caches")}}),lg(t,Sn.OPEN_LOG_FILE,async()=>{try{await QEe(),await Im.openLogFile()}catch(n){ne("Error creating Copilot log file:",n),new oi.Notice("Failed to create Copilot log file.")}}),lg(t,Sn.CLEAR_LOG_FILE,async()=>{try{await Im.clear(),new oi.Notice("Copilot log cleared.")}catch(n){ne("Error clearing Copilot log file:",n),new oi.Notice("Failed to clear Copilot log file.")}}),jGr(t,Sn.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=n.getSelection();if(!o){new oi.Notice("No text selected");return}let i=t.app.workspace.getActiveFile();if(!i){new oi.Notice("No active file");return}let a=n.listSelections()[0];if(!a){new oi.Notice("Could not determine selection range");return}let s=a.anchor.line+1,u=a.head.line+1,l={id:od(),content:o,sourceType:"note",noteTitle:i.basename,notePath:i.path,startLine:Math.min(s,u),endLine:Math.max(s,u)};SO([l]),t.activateView()}),lg(t,Sn.ADD_WEB_SELECTION_TO_CHAT_CONTEXT,async()=>{let{Platform:n}=await import("obsidian");if(!n.isDesktopApp){new oi.Notice("Web selection is only available on desktop");return}let{getWebViewerService:o}=await Promise.resolve().then(()=>(jW(),DGr));try{let i=o(t.app),a=i.getActiveLeaf()??i.getLastActiveLeaf();if(!a){new oi.Notice("No active Web Tab found");return}let s=await i.getSelectedMarkdown(a);if(!s.trim()){new oi.Notice("No text selected in Web Tab");return}let u=i.getPageInfo(a),l={id:od(),content:s,sourceType:"web",title:u.title||"Untitled",url:u.url,faviconUrl:u.faviconUrl||void 0};SO([l]),t.activateView()}catch(i){ne("Error adding web selection to context:",i),new oi.Notice("Failed to get web selection")}}),lg(t,Sn.ADD_CUSTOM_COMMAND,async()=>{let n=Pv(),o={...lN};new hB(t.app,n,o,async a=>{await th.getInstance().createCommand(a)}).open()}),lg(t,Sn.APPLY_CUSTOM_COMMAND,()=>{new ELe(t.app).open()}),lg(t,Sn.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await E0()){new oi.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}new MLe(t.app).open()}),$Gr(t,Sn.TRIGGER_QUICK_ASK,n=>{let o=t.app.workspace.getActiveViewOfType(oi.MarkdownView);if(n)return!!(!Ite()&&o&&o.editor);if(Ite())return new oi.Notice("Quick Ask is not available in source mode."),!1;if(!o||!o.editor)return new oi.Notice("No active editor found."),!1;let i=o.editor.cm;return i?(t.quickAskController.show(o,i),!0):(new oi.Notice("Could not access CodeMirror editor."),!1)})}ra();var BZ={title:"",content:"",createdMs:0,modifiedMs:0,lastUsedMs:0},zZ="copilot-system-prompt-created",VZ="copilot-system-prompt-modified",HZ="copilot-system-prompt-last-used",Ebt="copilot-system-prompt-default";var MB=require("obsidian");Ye();Bt();Xe();function kde(t,e,r){let n=t.trim();return n?t!==n?"Prompt name cannot have leading or trailing spaces":r&&t===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Prompt name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A prompt with this name already exists":null:"Prompt name cannot be empty"}function _C(){return(0,MB.normalizePath)(te().userSystemPromptsFolder)}function vC(t){return(0,MB.normalizePath)(`${_C()}/${t}.md`)}function Mfi(t,e){let r=e?(0,MB.normalizePath)(e):_C();return(0,MB.normalizePath)(`${r}/${t}.md`)}function WZ(t){if(!(t instanceof MB.TFile)||t.extension!=="md")return!1;let e=_C();if(!t.path.starts
`).replace(/\r/g,`
`)}async function zGr(t,e,r){let n=_C(),o=`${n}/unsupported`;await $c(o);let i="Migrated System Prompt (Failed Verification)",a=i,s=1;for(;t.getAbstractFileByPath(`${o}/${a}.md`);)s++,a=`${i} ${s}`;let u=`${o}/${a}.md`,l=`> Migration failed: ${r}
>
> To fix: Review the content below, then move this file to ${n}
${e}`;return await t.create(u,l),u}async function Nfi(t,e,r){try{let n=await t.read(e),o=HJ(n,{trimStart:!1}),i=Abt(o).replace(/^\n+/,""),a=Abt(r).replace(/^\n+/,"");return i!==a?(Te(`Migration verification failed: content mismatch. Expected ${a.length} chars, got ${i.length} chars`),!1):!0}catch(n){return ne("Migration verification failed: unable to read back file",n),!1}}async function Nbt(t){let r=te().userSystemPrompt;if(!r||r.trim().length===0){F("No legacy userSystemPrompt to migrate");return}try{F("Migrating legacy userSystemPrompt from settings to file system");let n=_C();await $c(n);let o=Afi(BGr,t),i=vC(o);o!==BGr&&F(`Default name already exists, using unique name: "${o}"`);let a=Date.now(),s=Abt(r),u={title:o,content:s,createdMs:a,modifiedMs:a,lastUsedMs:0};await t.create(i,s);let l=t.getAbstractFileByPath(i);if(!(l instanceof VGr.TFile))throw new Error("File not found after creation");if(await LW(l,u),await Nfi(t,l,r)){Re("defaultSystemPromptTitle",o);try{await JZ()}catch(d){Te("Failed to reload prompts after migration:",d)}Re("userSystemPrompt",""),F("Cleared legacy userSystemPrompt field"),new zu(app,()=>{},`We have upgraded your system prompt to the new file-based format. It is now stored as "${o}" in ${n}.
You can now:
\u2022 Edit your system prompt directly in the file
\u2022 Create multiple system prompts
\u2022 Manage prompts through the settings UI
Your migrated prompt has been set as the default system prompt.`,"\u{1F680} System Prompt Upgraded","OK","").open()}else{let d=await zGr(t,r,"content verification mismatch");try{await JZ()}catch(f){Te("Failed to reload prompts after failed migration:",f)}Re("userSystemPrompt",""),F("Cleared legacy userSystemPrompt field (saved to unsupported)"),new zu(app,()=>{},`\u26A0\uFE0F System Prompt Migration Issue
Your system prompt was migrated but verification failed. Your data has been saved to:
${d}
To recover:
1. Open the file and review the content
2. Move it to ${n}
3. The prompt will be available immediately`,"Migration Verification Failed","OK","").open()}}catch(n){ne("Failed to migrate legacy userSystemPrompt:",n);try{let o=await zGr(t,r,n.message||String(n));Re("userSystemPrompt",""),F("Cleared legacy userSystemPrompt field (saved to unsupported after error)"),new zu(app,()=>{},`\u26A0\uFE0F System Prompt Migration Failed
An error occurred during migration. Your data has been saved to:
${o}
To recover:
1. Open the file and review the content
2. Move it to ${_C()}
3. The prompt will be available immediately`,"Migration Failed","OK","").open()}catch(o){ne("Failed to save to unsupported folder:",o),Te("Preserving userSystemPrompt in settings for manual recovery"),new zu(app,()=>{},`Failed to migrate system prompt: ${n.message}
Unable to save to file system. Your system prompt is still in settings and will continue to work.
Please check:
- Folder permissions for ${_C()}
- Available disk space
- Vault is accessible
You can retry by reloading the plugin.`,"Migration Failed - Data Preserved","OK","").open()}}}sd();sd();ra();function ULe(){let[t]=fw(),[e]=Dye(),[r]=s5();return(()=>{if(t!=="project")return"initial";let{total:o,success:i,failed:a,processingFiles:s}=r;return e||s.length>0?"loading":a.length>0?"error":o.length>0&&i.length===o.length?"success":"initial"})()}Xe();ra();sd();Cn();mr();Xe();Fc();Ye();Or();var sS=require("obsidian"),pr=$(J());var Ln=$(J());Or();Cn();var XZ=$(J());Cn();Or();var ZZ=({value:t,onChange:e,placeholder:r="Search..."})=>XZ.default.createElement("div",{className:"tw-relative"},XZ.default.createElement(ri,{type:"text",placeholder:r,value:t,onChange:n=>e(n.target.value),className:"tw-pr-10"}),t&&XZ.default.createElement(pe,{variant:"secondary",onClick:()=>e(""),className:"tw-absolute tw-right-8 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-rounded-full tw-p-0 tw-transition-colors","aria-label":"Clear search"},XZ.default.createElement(RO,{className:"tw-size-4 tw-text-muted/60 hover:tw-text-accent-hover"})),XZ.default.createElement(Y4,{className:"tw-absolute tw-right-3 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-text-muted"}));var Hde=$(J());var dc=$(J(),1);var r$s=!!(typeof window<"u"&&window.document&&window.document.createElement);function YZ(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var WGr=$(J(),1);function HGr(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Dbt(...t){return e=>{let r=!1,n=t.map(o=>{let i=HGr(o,e);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let o=0;o<n.length;o++){let i=n[o];typeof i=="function"?i():HGr(t[o],null)}}}}function zde(...t){return WGr.useCallback(Dbt(...t),t)}var Q$=$(J(),1),JGr=$(St(),1);function KGr(t,e=[]){let r=[];function n(i,a){let s=Q$.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,y=Q$.useMemo(()=>m,Object.values(m));return(0,JGr.jsx)(h.Provider,{value:y,children:p})};l.displayName=i+"Provider";function c(d,f){let p=f?.[t]?.[u]||s,m=Q$.useContext(p);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}let o=()=>{let i=r.map(a=>Q$.createContext(a));return function(s){let u=s?.[t]||i;return Q$.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};return o.scopeName=t,[n,Dfi(o,...e)]}function Dfi(...t){let e=t[0];if(t.length===1)return e;let r=()=>{let n=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return Q$.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return r.scopeName=e.scopeName,r}var jbt=$(J(),1);var GGr=$(J(),1),qW=globalThis?.document?GGr.useLayoutEffect:()=>{};var jfi=jbt[" useId ".trim().toString()]||(()=>{}),$fi=0;function XGr(t){let[e,r]=jbt.useState(jfi());return qW(()=>{t||r(n=>n??String($fi++))},[t]),t||(e?`radix-${e}`:"")}var Lv=$(J(),1);var ZGr=$(J(),1);function Lfi(t,e){return ZGr.useReducer((r,n)=>e[r][n]??r,t)}var zLe=t=>{let{present:e,children:r}=t,n=Ffi(e),o=typeof r=="function"?r({present:n.isPresent}):Lv.Children.only(r),i=zde(n.ref,kfi(o));return typeof r=="function"||n.isPresent?Lv.cloneElement(o,{ref:i}):null};zLe.displayName="Presence";function Ffi(t){let[e,r]=Lv.useState(),n=Lv.useRef(null),o=Lv.useRef(t),i=Lv.useRef("none"),a=t?"mounted":"unmounted",[s,u]=Lfi(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Lv.useEffect(()=>{let l=BLe(n.current);i.current=s==="mounted"?l:"none"},[s]),qW(()=>{let l=n.current,c=o.current;if(c!==t){let f=i.current,p=BLe(l);t?u("MOUNT"):p==="none"||l?.display==="none"?u("UNMOUNT"):u(c&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,u]),qW(()=>{if(e){let l,c=e.ownerDocument.defaultView??window,d=p=>{let h=BLe(n.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(u("ANIMATION_END"),!o.current)){let y=e.style.animationFillM
`,xhi=e6?"\xA0":YFe,xZr="\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",TZr="A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF",Thi=new RegExp("^[^"+TZr+"]*["+xZr+"]"),Ohi=new RegExp("^[^"+xZr+"]*["+TZr+"]"),vb={bold:1,capitalize:1024,code:16,highlight:ZFe,italic:2,lowercase:256,strikethrough:ife,subscript:32,superscript:64,underline:afe,uppercase:512},Ehi={directionless:1,unmergeable:2},IXr={center:rvt,end:avt,justify:ovt,left:tvt,right:nvt,start:ivt},Phi={[rvt]:"center",[avt]:"end",[ovt]:"justify",[tvt]:"left",[nvt]:"right",[ivt]:"start"},Mhi={normal:0,segmented:2,token:1},Rhi={[ghi]:"normal",[bhi]:"segmented",[yhi]:"token"},Ihi="$",AXr="$config";function OZr(t,e,r,n,o,i){let a=t.getFirstChild();for(;a!==null;){let s=a.__key;a.__parent===e&&(et(a)&&OZr(a,s,r,n,o,i),r.has(s)||i.delete(s),o.push(s)),a=a.getNextSibling()}}var Ahi=100,P_t=!1,svt=0;function Nhi(t){svt=t.timeStamp}function h_t(t,e,r){let n=t.nodeName==="BR",o=e.__lexicalLineBreak;return o&&(t===o||n&&t.previousSibling===o)||n&&ike(t,r)!==void 0}function Dhi(t,e,r){let n=CN(OC(r)),o=null,i=null;n!==null&&n.anchorNode===t&&(o=n.anchorOffset,i=n.focusOffset);let a=t.nodeValue;a!==null&&Evt(e,a,o,i,!1)}function jhi(t,e,r){if(fn(t)){let n=t.anchor.getNode();if(n.is(r)&&t.format!==n.getFormat())return!1}return xN(e)&&r.isAttached()}function $hi(t,e,r,n){for(let o=t;o&&!GYr(o);o=yfe(o)){let i=ike(o,e);if(i!==void 0){let a=Sh(i,r);if(a)return Vu(a)||!w_(o)?void 0:[o,a]}else if(o===n)return[n,NYr(r)]}}function EZr(t,e,r){P_t=!0;let n=performance.now()-svt>Ahi;try{uS(t,()=>{let o=ks()||function(f){return f.getEditorState().read(()=>{let p=ks();return p!==null?p.clone():null})}(t),i=new Map,a=t.getRootElement(),s=t._editorState,u=t._blockCursorElement,l=!1,c="";for(let f=0;f<e.length;f++){let p=e[f],m=p.type,h=p.target,y=$hi(h,t,s,a);if(!y)continue;let[g,b]=y;if(m==="characterData")n&&Mr(b)&&xN(h)&&jhi(o,h,b)&&Dhi(h,b,t);else if(m==="childList"){l=!0;let _=p.addedNodes;for(let O=0;O<_.length;O++){let E=_[O],P=IYr(E),R=E.parentNode;if(R!=null&&E!==u&&P===null&&!h_t(E,R,t)){if(e6){let I=(w_(E)?E.innerText:null)||E.nodeValue;I&&(c+=I)}R.removeChild(E)}}let w=p.removedNodes,T=w.length;if(T>0){let O=0;for(let E=0;E<T;E++){let P=w[E];(h_t(P,h,t)||u===P)&&(h.appendChild(P),O++)}T!==O&&i.set(g,b)}}}if(i.size>0)for(let[f,p]of i)p.reconcileObservedMutation(f,t);let d=r.takeRecords();if(d.length>0){for(let f=0;f<d.length;f++){let p=d[f],m=p.addedNodes,h=p.target;for(let y=0;y<m.length;y++){let g=m[y],b=g.parentNode;b==null||g.nodeName!=="BR"||h_t(g,h,t)||b.removeChild(g)}}r.takeRecords()}o!==null&&(l&&zv(o),e6&&kYr(t)&&o.insertRawText(c))})}finally{P_t=!1}}function PZr(t){let e=t._observer;e!==null&&EZr(t,e.takeRecords(),e)}function MZr(t){(function(e){svt===0&&OC(e).addEventListener("textInput",Nhi,!0)})(t),t._observer=new MutationObserver((e,r)=>{EZr(t,e,r)})}var M_t=class{constructor(e,r){this.key=e,this.parse=r.parse.bind(r),this.unparse=(r.unparse||qhi).bind(r),this.isEqual=(r.isEqual||Object.is).bind(r),this.defaultValue=this.parse(void 0)}};function Lhi(t,e){return new M_t(t,e)}function jFe(t,e,r="latest"){let n=(r==="latest"?t.getLatest():t).__state;return n?n.getValue(e):e.defaultValue}function Fhi(t,e,r){let n=jFe(t,r,"direct"),o=jFe(e,r,"direct");return r.isEqual(n,o)?null:[n,o]}function khi(t,e,r){let n;if(fg(),typeof r=="function"){let i=t.getLatest(),a=jFe(i,e);if(n=r(a),e.isEqual(a,n))return i}else n=r;let o=t.getWritable();return uvt(o).updateFromKnown(e,n),o}function RZr(t){let e=new Map,r=new Set;for(let n=typeof t=="function"?t:t.replace;n.prototype&&n.prototype.getType!==void 0;n=Object.getPrototypeOf(n)){let{ownNodeConfig:o}=Nvt(n);if(o&&o.stateConfigs)for(let i of o.stateConfigs){let a;"stateConfig"in i?(a=i.stateConfig,i.flat&&r.add(a.key)):a=i,e.set(a.key,a)}}return{flatKeys:r,sharedConfigMap:e}}var R_t=class t{constructor(e,r,n=void 0,o=new Map,i=void 0){this.node=e,this.sharedNodeState=r,this.unknownState=n,this.knownState=o;let{sharedConfigMap:a}=this.sharedNodeState,s=i!==void 0?i:function(u,l,c){let
`)r.preventDefault(),_r(n,Yde,!1);else if(u===mL)r.preventDefault(),_r(n,L_t,void 0);else if(u==null&&r.dataTransfer){let p=r.dataTransfer.getData("text/plain");r.preventDefault(),a.insertRawText(p)}else u!=null&&sYr(a,i,u,r.timeStamp,!0)?(r.preventDefault(),_r(n,dY,u)):lY=u;iYr=r.timeStamp}})}(t,e)]);var Qde=0,oYr=null,iYr=0,lY=null,UFe=new WeakMap,B_t=!1,z_t=!1,efe=!1,Gde=!1,y_t=!1,b_t="",YW=null,aYr=[0,"",0,"root",0];function sYr(t,e,r,n,o){let i=t.anchor,a=t.focus,s=i.getNode(),u=fc(),l=CN(OC(u)),c=l!==null?l.anchorNode:null,d=i.key,f=u.getElementByKey(d),p=r.length;return d!==a.key||!Mr(s)||(!o&&(!AFe||iYr<n+50)||s.isDirty()&&p<2||DYr(r))&&i.offset!==a.offset&&!s.isComposing()||uL(s)||s.isDirty()&&p>1||(o||!AFe)&&f!==null&&!s.isComposing()&&c!==i6(f)||l!==null&&e!==null&&(!e.collapsed||e.startContainer!==l.anchorNode||e.startOffset!==l.anchorOffset)||s.getFormat()!==t.format||s.getStyle()!==t.style||function(m,h){if(h.isSegmented())return!0;if(!m.isCollapsed())return!1;let y=m.anchor.offset,g=h.getParentOrThrow(),b=VB(h);return y===0?!h.canInsertTextBefore()||!g.canInsertTextBefore()&&!h.isComposing()||b||function(_){let w=_.getPreviousSibling();return(Mr(w)||et(w)&&w.isInline())&&!w.canInsertTextAfter()}(h):y===h.getTextContentSize()&&(!h.canInsertTextAfter()||!g.canInsertTextAfter()&&!h.isComposing()||b)}(t,s)}function BXr(t,e){return xN(t)&&t.nodeValue!==null&&e!==0&&e!==t.nodeValue.length}function zXr(t,e,r){let{anchorNode:n,anchorOffset:o,focusNode:i,focusOffset:a}=t;B_t&&(B_t=!1,BXr(n,o)&&BXr(i,a)&&!YW)||uS(e,()=>{if(!r)return void zv(null);if(!hfe(e,n,i))return;let s=ks();if(YW&&fn(s)&&s.isCollapsed()){let u=s.anchor,l=YW.anchor;(u.key===l.key&&u.offset===l.offset+1||u.offset===1&&l.getNode().is(u.getNode().getPreviousSibling()))&&(s=YW.clone(),zv(s))}if(YW=null,fn(s)){let u=s.anchor,l=u.getNode();if(s.isCollapsed()){t.type==="Range"&&t.anchorNode===t.focusNode&&(s.dirty=!0);let c=OC(e).event,d=c?c.timeStamp:performance.now(),[f,p,m,h,y]=aYr,g=Bv(),b=e.isComposing()===!1&&g.getTextContent()==="";if(d<y+200&&u.offset===m&&u.key===h)MFe(s,f,p);else if(u.type==="text")Mr(l)||nt(141),uYr(s,l);else if(u.type==="element"&&!b){et(l)||nt(259);let _=u.getNode();_.isEmpty()?function(w,T){let O=T.getTextFormat(),E=T.getTextStyle();MFe(w,O,E)}(s,_):MFe(s,0,"")}}else{let c=u.key,d=s.focus.key,f=s.getNodes(),p=f.length,m=s.isBackward(),h=m?a:o,y=m?o:a,g=m?d:c,b=m?c:d,_=CZr,w=!1;for(let T=0;T<p;T++){let O=f[T],E=O.getTextContentSize();if(Mr(O)&&E!==0&&!(T===0&&O.__key===g&&h===E||T===p-1&&O.__key===b&&y===0)&&(w=!0,_&=O.getFormat(),_===0))break}s.format=w?_:0}}_r(e,lvt,void 0)})}function MFe(t,e,r){t.format===e&&t.style===r||(t.format=e,t.style=r,t.dirty=!0)}function uYr(t,e){MFe(t,e.getFormat(),e.getStyle())}function lYr(t){if(!t.getTargetRanges)return null;let e=t.getTargetRanges();return e.length===0?null:e[0]}function CFe(t,e){let r=t._compositionKey;if(pg(null),r!==null&&e!=null){if(e===""){let n=Sh(r),o=i6(t.getElementByKey(r));return void(o!==null&&o.nodeValue!==null&&Mr(n)&&Evt(n,o.nodeValue,null,null,!0))}if(e[e.length-1]===`
`){let n=ks();if(fn(n)){let o=n.focus;return n.anchor.set(o.key,o.offset,o.type),void _r(t,qFe,null)}}}Ovt(!0,t,e)}function cYr(t){let e=t.__lexicalEventHandles;return e===void 0&&(e=[],t.__lexicalEventHandles=e),e}var fY=new Map;function dYr(t){let e=VYr(t.target);if(e===null)return;let r=xvt(e.anchorNode);if(r===null)return;z_t&&(z_t=!1,uS(r,()=>{let u=s6(),l=e.anchorNode;(w_(l)||xN(l))&&zv(rke(u,e,r,t))}));let n=Tvt(r),o=n[n.length-1],i=o._key,a=fY.get(i),s=a||o;s!==r&&zXr(e,s,!1),zXr(e,r,!0),r!==o?fY.set(i,r):a&&fY.delete(i)}function VXr(t){t._lexicalHandled=!0}function HXr(t){return t._lexicalHandled===!0}var Qhi=()=>{};function egi(t){let e=t.ownerDocument,r=UFe.get(e);if(r===void 0)return void Qhi();let n=r-1;n>=0||nt(164),UFe.set(e,n),n===0&&e.removeEventListener("selectionchange",dYr);let o=gfe(t);oke(o)?(function(a){if(a._parentEditor!==null){let s=Tvt(a),u=s[s.length-1]._key;fY.get(u)===a&&fY.delete(u)}else fY.delete(a._key)}(o),t.__lexicalEditor=null):o&&nt(198);let i=cYr(t);for(let a=0;a<i.length;a++)i[a]();t.__lexicalEventHandles=[]}function V_t(t,e,r){fg();let n=t.__key,o=t.getParent();if(o===null)return;let i=function(s){let u=ks();if(!fn(u)||!et(s))return u;let{anchor:l,focus:c}=u,d=l.getNode(),f=c.getNode();return GFe(d,s)&&l.set(s.__key,0,"element"),GFe(f,s)&&c.set(s.__key,0,"element"),u}(t),a=!1;if(fn(i)&&e){let s=i.anchor,u=i.focus;s.key===n&&(VFe(s,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0),u.key===n&&(VFe(u,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0)}else tke(i)&&e&&t.isSelected()&&t.selectPrevious();if(fn(i)&&e&&!a){let s=t.getIndexWithinParent();HB(t),zFe(i,o,s,-1)}else HB(t);r||DT(o)||o.canBeEmpty()||!o.isEmpty()||V_t(o,e),e&&i&&qv(o)&&o.isEmpty()&&o.selectEnd()}function tgi(t){return t}var JB=class{static getType(){let{ownNodeType:e}=Nvt(this);return e===void 0&&nt(64,this.name),e}static clone(e){nt(65,this.name)}$config(){return{}}config(e,r){let n=r.extends||Object.getPrototypeOf(this.constructor);return Object.assign(r,{extends:n,type:e}),{[e]:r}}afterCloneFrom(e){this.__key===e.__key?(this.__parent=e.__parent,this.__next=e.__next,this.__prev=e.__prev,this.__state=e.__state):e.__state&&(this.__state=e.__state.getWritable(this))}constructor(e){this.__type=this.constructor.getType(),this.__parent=null,this.__prev=null,this.__next=null,Object.defineProperty(this,"__state",{configurable:!0,enumerable:!1,value:void 0,writable:!0}),RYr(this,e)}getType(){return this.__type}isInline(){nt(137,this.constructor.name)}isAttached(){let e=this.__key;for(;e!==null;){if(e==="root")return!0;let r=Sh(e);if(r===null)break;e=r.__parent}return!1}isSelected(e){let r=e||ks();if(r==null)return!1;let n=r.getNodes().some(o=>o.__key===this.__key);if(Mr(this))return n;if(fn(r)&&r.anchor.type==="element"&&r.focus.type==="element"){if(r.isCollapsed())return!1;let o=this.getParent();if(Vu(this)&&this.isInline()&&o){let i=r.isBackward()?r.focus:r.anchor;if(o.is(i.getNode())&&i.offset===o.getChildrenSize()&&this.is(o.getLastChild()))return!1}}return n}getKey(){return this.__key}getIndexWithinParent(){let e=this.getParent();if(e===null)return-1;let r=e.getFirstChild(),n=0;for(;r!==null;){if(this.is(r))return n;n++,r=r.getNextSibling()}return-1}getParent(){let e=this.getLatest().__parent;return e===null?null:Sh(e)}getParentOrThrow(){let e=this.getParent();return e===null&&nt(66,this.__key),e}getTopLevelElement(){let e=this;for(;e!==null;){let r=e.getParent();if(DT(r))return et(e)||e===this&&Vu(e)||nt(194),e;e=r}return null}getTopLevelElementOrThrow(){let e=this.getTopLevelElement();return e===null&&nt(67,this.__key),e}getParents(){let e=[],r=this.getParent();for(;r!==null;)e.push(r),r=r.getParent();return e}getParentKeys(){let e=[],r=this.getParent();for(;r!==null;)e.push(r.__key),r=r.getParent();return e}getPreviousSibling(){let e=this.getLatest().__prev;return e===null?null:Sh(e)}getPreviousSiblings(){let e=[],r=this.getParent();if(r===null)return e;let n=r.getFirstChild();for(;n!==null&&!n.is(this);)e.push(n),n=n.getNextSibling();return e}getNextSibling(){let e=this.getLatest().__next;return e===null?nu
`}createDOM(){return document.createElement("br")}updateDOM(){return!1}isInline(){return!0}static importDOM(){return{br:e=>function(r){let n=r.parentElement;if(n!==null&&X_t(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&xFe(o)){let i=n.lastChild;if(i===r||i.previousSibling===r&&xFe(i))return!0}}return!1}(e)||function(r){let n=r.parentElement;if(n!==null&&X_t(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&xFe(o))return!1;let i=n.lastChild;if(i===r||i.previousSibling===r&&xFe(i))return!0}return!1}(e)?null:{conversion:rgi,priority:0}}}static importJSON(e){return yY().updateFromJSON(e)}};function rgi(t){return{node:yY()}}function yY(){return bfe(new gY)}function QW(t){return t instanceof gY}function xFe(t){return xN(t)&&/^( |\t|\r?\n)+$/.test(t.textContent||"")}function __t(t,e){return 16&e?"code":e&ZFe?"mark":32&e?"sub":64&e?"sup":null}function v_t(t,e){return 1&e?"strong":2&e?"em":"span"}function fYr(t,e,r,n,o){let i=n.classList,a=pY(o,"base");a!==void 0&&i.add(...a),a=pY(o,"underlineStrikethrough");let s=!1,u=e&afe&&e&ife;a!==void 0&&(r&afe&&r&ife?(s=!0,u||i.add(...a)):u&&i.remove(...a));for(let l in vb){let c=vb[l];if(a=pY(o,l),a!==void 0)if(r&c){if(s&&(l==="underline"||l==="strikethrough")){e&c&&i.remove(...a);continue}e&c&&(!u||l!=="underline")&&l!=="strikethrough"||i.add(...a)}else e&c&&i.remove(...a)}}function pYr(t,e,r){let n=e.firstChild,o=r.isComposing(),i=t+(o?YFe:"");if(n==null)e.textContent=i;else{let a=n.nodeValue;if(a!==i)if(o||e6){let[s,u,l]=function(c,d){let f=c.length,p=d.length,m=0,h=0;for(;m<f&&m<p&&c[m]===d[m];)m++;for(;h+m<f&&h+m<p&&c[f-h-1]===d[p-h-1];)h++;return[m,f-m-h,d.slice(m,p-h)]}(a,i);u!==0&&n.deleteData(s,u),n.insertData(s,l)}else n.nodeValue=i}}function WXr(t,e,r,n,o,i){pYr(o,t,e);let a=i.theme.text;a!==void 0&&fYr(0,0,n,t,a)}function TFe(t,e){let r=document.createElement(e);return r.appendChild(t),r}var n6=class t extends JB{static getType(){return"text"}static clone(e){return new t(e.__text,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__text=e.__text,this.__format=e.__format,this.__style=e.__style,this.__mode=e.__mode,this.__detail=e.__detail}constructor(e="",r){super(r),this.__text=e,this.__format=0,this.__style="",this.__mode=0,this.__detail=0}getFormat(){return this.getLatest().__format}getDetail(){return this.getLatest().__detail}getMode(){let e=this.getLatest();return Rhi[e.__mode]}getStyle(){return this.getLatest().__style}isToken(){return this.getLatest().__mode===1}isComposing(){return this.__key===zB()}isSegmented(){return this.getLatest().__mode===2}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(e){let r=vb[e];return!!(this.getFormat()&r)}isSimpleText(){return this.__type==="text"&&this.__mode===0}getTextContent(){return this.getLatest().__text}getFormatFlags(e,r){return JFe(this.getLatest().__format,e,r)}canHaveFormat(){return!0}isInline(){return!0}createDOM(e,r){let n=this.__format,o=__t(0,n),i=v_t(0,n),a=o===null?i:o,s=document.createElement(a),u=s;this.hasFormat("code")&&s.setAttribute("spellcheck","false"),o!==null&&(u=document.createElement(i),s.appendChild(u)),WXr(u,this,0,n,this.__text,e);let l=this.__style;return l!==""&&(s.style.cssText=l),s}updateDOM(e,r,n){let o=this.__text,i=e.__format,a=this.__format,s=__t(0,i),u=__t(0,a),l=v_t(0,i),c=v_t(0,a);if((s===null?l:s)!==(u===null?c:u))return!0;if(s===u&&l!==c){let h=r.firstChild;h==null&&nt(48);let y=document.createElement(c);return WXr(y,this,0,a,o,n),r.replaceChild(y,h),!1}let d=r;u!==null&&s!==null&&(d=r.firstChild,d==null&&nt(49)),pYr(o,d,this);let f=n.theme.text;f!==void 0&&i!==a&&fYr(0,i,a,d,f);let p=e.__style,m=this.__style;return p!==m&&(r.style.cssText=m),!1}static importDOM(){return{"#text":()=>({conversion:agi,priority:0}),b:()=>({conversion:ogi,priority:0}),code:()=>({conversion:aL,priority:0}),em:()=>({conversion:aL,priority:0}),i:()=>({conversion:aL,priority:0}),mark:()=>({conversion:aL,priority:0}),s:()=>({conversion:aL,priority:0}),span:()=>({conversion:ngi,priority:0}),strong:()=>({conversion:aL,priority:0}),sub
`||s===`\r
`?o.push(yY()):s===" "?o.push(eke()):s!==""&&o.push(dg(s))}return{node:o}}if(r=r.replace(/\r/g,"").replace(/[ \t\n]+/g," "),r==="")return{node:null};if(r[0]===" "){let n=e,o=!0;for(;n!==null&&(n=KXr(n,!1))!==null;){let i=n.textContent||"";if(i.length>0){/[ \t\n]$/.test(i)&&(r=r.slice(1)),o=!1;break}}o&&(r=r.slice(1))}if(r[r.length-1]===" "){let n=e,o=!0;for(;n!==null&&(n=KXr(n,!0))!==null;)if((n.textContent||"").replace(/^( |\t|\r?\n)+/,"").length>0){o=!1;break}o&&(r=r.slice(0,r.length-1))}return r===""?{node:null}:{node:dg(r)}}function KXr(t,e){let r=t;for(;;){let n;for(;(n=e?r.nextSibling:r.previousSibling)===null;){let i=r.parentElement;if(i===null)return null;r=i}if(r=n,w_(r)){let i=r.style.display;if(i===""&&!WYr(r)||i!==""&&!i.startsWith("inline"))return null}let o=r;for(;(o=e?r.firstChild:r.lastChild)!==null;)r=o;if(xN(r))return r;if(r.nodeName==="BR")return null}}var sgi={code:"code",em:"italic",i:"italic",mark:"highlight",s:"strikethrough",strong:"bold",sub:"subscript",sup:"superscript",u:"underline"};function aL(t){let e=sgi[t.nodeName.toLowerCase()];return e===void 0?{node:null}:{forChild:hvt(t.style,e),node:null}}function dg(t=""){return bfe(new n6(t))}function Mr(t){return t instanceof n6}function hvt(t,e){let r=t.fontWeight,n=t.textDecoration.split(" "),o=r==="700"||r==="bold",i=n.includes("line-through"),a=t.fontStyle==="italic",s=n.includes("underline"),u=t.verticalAlign;return l=>(Mr(l)&&(o&&!l.hasFormat("bold")&&l.toggleFormat("bold"),i&&!l.hasFormat("strikethrough")&&l.toggleFormat("strikethrough"),a&&!l.hasFormat("italic")&&l.toggleFormat("italic"),s&&!l.hasFormat("underline")&&l.toggleFormat("underline"),u!=="sub"||l.hasFormat("subscript")||l.toggleFormat("subscript"),u!=="super"||l.hasFormat("superscript")||l.toggleFormat("superscript"),e&&!l.hasFormat(e)&&l.toggleFormat(e)),l)}var bY=class t extends n6{static getType(){return"tab"}static clone(e){return new t(e.__key)}constructor(e){super(" ",e),this.__detail=2}static importDOM(){return null}createDOM(e){let r=super.createDOM(e),n=pY(e.theme,"tab");return n!==void 0&&r.classList.add(...n),r}static importJSON(e){return eke().updateFromJSON(e)}setTextContent(e){return e!==" "&&e!==""&&nt(126),super.setTextContent(" ")}spliceText(e,r,n,o){return n===""&&r===0||n===" "&&r===1||nt(286),this}setDetail(e){return e!==2&&nt(127),this}setMode(e){return e!=="normal"&&nt(128),this}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}};function eke(){return bfe(new bY)}function gvt(t){return t instanceof bY}var H_t=class{constructor(e,r,n){this._selection=null,this.key=e,this.offset=r,this.type=n}is(e){return this.key===e.key&&this.offset===e.offset&&this.type===e.type}isBefore(e){return this.key===e.key?this.offset<e.offset:Lvt(MT(ZB(this,"next")),MT(ZB(e,"next")))<0}getNode(){let e=Sh(this.key);return e===null&&nt(20),e}set(e,r,n,o){let i=this._selection,a=this.key;o&&this.key===e&&this.offset===r&&this.type===n||(this.key=e,this.offset=r,this.type=n,PY()||(zB()===a&&pg(e),i!==null&&(i.setCachedNodes(null),i.dirty=!0)))}};function NT(t,e,r){return new H_t(t,e,r)}function w_t(t,e){let r=e.__key,n=t.offset,o="element";if(Mr(e)){o="text";let i=e.getTextContentSize();n>i&&(n=i)}else if(!et(e)){let i=e.getNextSibling();if(Mr(i))r=i.__key,n=0,o="text";else{let a=e.getParent();a&&(r=a.__key,n=e.getIndexWithinParent()+1)}}t.set(r,n,o)}function GXr(t,e){if(et(e)){let r=e.getLastDescendant();et(r)||Mr(r)?w_t(t,r):w_t(t,e)}else w_t(t,e)}var BFe=class t{constructor(e){this._cachedNodes=null,this._nodes=e,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){if(!tke(e))return!1;let r=this._nodes,n=e._nodes;return r.size===n.size&&Array.from(r).every(o=>n.has(o))}isCollapsed(){return!1}isBackward(){return!1}getStartEndPoints(){return null}add(e){this.dirty=!0,this._nodes.add(e),this._cachedNodes=null}delete(e){this.dirty=!0,this._nodes.delete(e),this._cachedNodes=null}clear(){this.dirty=!0,this._nodes.clear(),this._cachedNodes=null}has(e){return this._nodes.has(e)}clone(){return new t(new Set(this._nodes))}extract(){re
`),c=!f.isEmpty();else if(c=!1,Mr(f)){let p=f.getTextContent();f===r?f===n?o.type==="element"&&i.type==="element"&&i.offset!==o.offset||(p=s<u?p.slice(s,u):p.slice(u,s)):p=a?p.slice(s):p.slice(u):f===n&&(p=a?p.slice(0,u):p.slice(0,s)),l+=p}else!Vu(f)&&!QW(f)||f===n&&this.isCollapsed()||(l+=f.getTextContent())}return l}applyDOMRange(e){let r=fc(),n=r.getEditorState()._selection,o=hYr(e.startContainer,e.startOffset,e.endContainer,e.endOffset,r,n);if(o===null)return;let[i,a]=o;this.anchor.set(i.key,i.offset,i.type,!0),this.focus.set(a.key,a.offset,a.type,!0),$Fe(this)}clone(){let e=this.anchor,r=this.focus;return new t(NT(e.key,e.offset,e.type),NT(r.key,r.offset,r.type),this.format,this.style)}toggleFormat(e){this.format=JFe(this.format,e,null),this.dirty=!0}setFormat(e){this.format=e,this.dirty=!0}setStyle(e){this.style=e,this.dirty=!0}hasFormat(e){let r=vb[e];return!!(this.format&r)}insertRawText(e){let r=e.split(/(\r?\n|\t)/),n=[],o=r.length;for(let i=0;i<o;i++){let a=r[i];a===`
`||a===`\r
`?n.push(yY()):a===" "?n.push(eke()):n.push(dg(a))}this.insertNodes(n)}insertText(e){let r=this.anchor,n=this.focus,o=this.format,i=this.style,a=r,s=n;!this.isCollapsed()&&n.isBefore(r)&&(a=n,s=r),a.type==="element"&&function(y,g,b,_){let w=y.getNode(),T=w.getChildAtIndex(y.offset),O=dg(),E=qv(w)?fL().append(O):O;O.setFormat(b),O.setStyle(_),T===null?w.append(E):T.insertBefore(E),y.is(g)&&g.set(O.__key,0,"text"),y.set(O.__key,0,"text")}(a,s,o,i),s.type==="element"&&EY(s,MT(ZB(s,"next")));let u=a.offset,l=s.offset,c=this.getNodes(),d=c.length,f=c[0];Mr(f)||nt(26);let p=f.getTextContent().length,m=f.getParentOrThrow(),h=c[d-1];if(d===1&&s.type==="element"&&(l=p,s.set(a.key,l,"text")),this.isCollapsed()&&u===p&&(uL(f)||!f.canInsertTextAfter()||!m.canInsertTextAfter()&&f.getNextSibling()===null)){let y=f.getNextSibling();if(Mr(y)&&y.canInsertTextBefore()&&!uL(y)||(y=dg(),y.setFormat(o),y.setStyle(i),m.canInsertTextAfter()?f.insertAfter(y):m.insertAfter(y)),y.select(0,0),f=y,e!=="")return void this.insertText(e)}else if(this.isCollapsed()&&u===0&&(uL(f)||!f.canInsertTextBefore()||!m.canInsertTextBefore()&&f.getPreviousSibling()===null)){let y=f.getPreviousSibling();if(Mr(y)&&!uL(y)||(y=dg(),y.setFormat(o),m.canInsertTextBefore()?f.insertBefore(y):m.insertBefore(y)),y.select(),f=y,e!=="")return void this.insertText(e)}else if(f.isSegmented()&&u!==p){let y=dg(f.getTextContent());y.setFormat(o),f.replace(y),f=y}else if(!this.isCollapsed()&&e!==""){let y=h.getParent();if(!m.canInsertTextBefore()||!m.canInsertTextAfter()||et(y)&&(!y.canInsertTextBefore()||!y.canInsertTextAfter()))return this.insertText(""),mYr(this.anchor,this.focus,null),void this.insertText(e)}if(d===1){if(VB(f)){let _=dg(e);return _.select(),void f.replace(_)}let y=f.getFormat(),g=f.getStyle();if(u!==l||y===o&&g===i){if(gvt(f)){let _=dg(e);return _.setFormat(o),_.setStyle(i),_.select(),void f.replace(_)}}else{if(f.getTextContent()!==""){let _=dg(e);if(_.setFormat(o),_.setStyle(i),_.select(),u===0)f.insertBefore(_,!1);else{let[w]=f.splitText(u);w.insertAfter(_,!1)}return void(_.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length))}f.setFormat(o),f.setStyle(i)}let b=l-u;f=f.spliceText(u,b,e,!0),f.getTextContent()===""?f.remove():this.anchor.type==="text"&&(f.isComposing()?this.anchor.offset-=e.length:(this.format=y,this.style=g))}else{let y=new Set([...f.getParentKeys(),...h.getParentKeys()]),g=et(f)?f:f.getParentOrThrow(),b=et(h)?h:h.getParentOrThrow(),_=h;if(!g.is(b)&&b.isInline())do _=b,b=b.getParentOrThrow();while(b.isInline());if(s.type==="text"&&(l!==0||h.getTextContent()==="")||s.type==="element"&&h.getIndexWithinParent()<l)if(Mr(h)&&!VB(h)&&l!==h.getTextContentSize()){if(h.isSegmented()){let P=dg(h.getTextContent());h.replace(P),h=P}qv(s.getNode())||s.type!=="text"||(h=h.spliceText(0,l,"")),y.add(h.__key)}else{let P=h.getParentOrThrow();P.canBeEmpty()||P.getChildrenSize()!==1?h.remove():P.remove()}else y.add(h.__key);let w=b.getChildren(),T=new Set(c),O=g.is(b),E=g.isInline()&&f.getNextSibling()===null?g:f;for(let P=w.length-1;P>=0;P--){let R=w[P];if(R.is(f)||et(R)&&R.isParentOf(f))break;R.isAttached()&&(!T.has(R)||R.is(_)?O||E.insertAfter(R,!1):R.remove())}if(!O){let P=b,R=null;for(;P!==null;){let I=P.getChildren(),N=I.length;(N===0||I[N-1].is(R))&&(y.delete(P.__key),R=P),P=P.getParent()}}if(VB(f))if(u===p)f.select();else{let P=dg(e);P.select(),f.replace(P)}else f=f.spliceText(u,p-u,e,!0),f.getTextContent()===""?f.remove():f.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length);for(let P=1;P<d;P++){let R=c[P],I=R.__key;y.has(I)||R.remove()}}}removeText(){let e=ks()===this;nfe(this,QYr(evt(this))),e&&ks()!==this&&zv(this)}formatText(e,r=null){if(this.isCollapsed())return this.toggleFormat(e),void pg(null);let n=this.getNodes(),o=[];for(let w of n)Mr(w)&&o.push(w);let i=w=>{n.forEach(T=>{if(et(T)){let O=T.getFormatFlags(e,w);T.setTextFormat(O)}})},a=o.length;if(a===0)return this.toggleFormat(e),pg(null),void i(r);let s=this.anchor,u=this.focus,l=this.isBackward(),c=l?u:s,d=l?s:u,f=0,p=o[0],m=c.type==="element"?0:c.of
`);let u=s.length;if(!Zi(n)||o>=u){let l=n.getParent();n.remove(),l==null||l.getChildrenSize()!==0||AY(l)||l.remove(),o-=u+a,n=i}else{let l=n.getKey(),c=t.getEditorState().read(()=>{let p=uQr(l);return Zi(p)&&p.isSimpleText()?p.getTextContent():null}),d=u-o,f=s.slice(0,d);if(c!==null&&c!==s){let p=vfe(),m=n;if(n.isSimpleText())n.setTextContent(c);else{let h=lS(c);n.replace(h),m=h}if(Nr(p)&&p.isCollapsed()){let h=p.anchor.offset;m.select(h,h)}}else if(n.isSimpleText()){let p=e.key===l,m=e.offset;m<o&&(m=u);let h=p?m-o:0,y=p?m:d;if(p&&h===0){let[g]=n.splitText(h,y);g.remove()}else{let[,g]=n.splitText(h,y);g.remove()}}else{let p=lS(f);n.replace(p)}o=0}}}function Byi(t){let e=t.getStyle(),r=Hen(e);Vke.set(e,r)}function pwt(t,e){(Nr(t)?t.isCollapsed():Zi(t)||_i(t))||gwt(280);let r=Hke(Nr(t)?t.style:Zi(t)?t.getStyle():t.getTextStyle()),n=Object.entries(e).reduce((i,[a,s])=>(typeof s=="function"?i[a]=s(r[a],t):s===null?delete i[a]:i[a]=s,i),{...r}),o=Wen(n);Nr(t)||Zi(t)?t.setStyle(o):t.setTextStyle(o),Vke.set(o,n)}function zyi(t,e){if(Nr(t)&&t.isCollapsed()){pwt(t,e);let r=t.anchor.getNode();_i(r)&&r.isEmpty()&&pwt(r,e)}Ken(r=>{pwt(r,e)})}function Ken(t){let e=_n();if(!e)return;let r=new Map;if(Nr(e))for(let i of rQr(e).getTextSlices())i&&r.set(i.caret.origin.getKey(),i.getSliceIndices());let n=e.getNodes();for(let i of n){if(!Zi(i)||!i.canHaveFormat())continue;let[a,s]=(o=i,r.get(o.getKey())||[0,o.getTextContentSize()]);s!==a&&(Vvt(i)||a===0&&s===i.getTextContentSize()?t(i):t(i.splitText(a,s)[a===0?0:1]))}var o;Nr(e)&&e.anchor.type==="text"&&e.focus.type==="text"&&e.anchor.key===e.focus.key&&Gen(e)}function Gen(t){if(t.isBackward()){let{anchor:e,focus:r}=t,{key:n,offset:o,type:i}=e;e.set(r.key,r.offset,r.type),r.set(n,o,i)}}function Xen(t,e){let r=t.getFormatType(),n=t.getIndent();r!==e.getFormatType()&&e.setFormat(r),n!==e.getIndent()&&e.setIndent(n)}function Vyi(t,e,r=Xen){if(t===null)return;let n=t.getStartEndPoints(),o=new Map,i=null;if(n){let[a,s]=n;i=uke(),i.anchor.set(a.key,a.offset,a.type),i.focus.set(s.key,s.offset,s.type);let u=hwt(a.getNode(),xfe),l=hwt(s.getNode(),xfe);_i(u)&&o.set(u.getKey(),u),_i(l)&&o.set(l.getKey(),l)}for(let a of t.getNodes())if(_i(a)&&xfe(a))o.set(a.getKey(),a);else if(n===null){let s=hwt(a,xfe);_i(s)&&o.set(s.getKey(),s)}for(let[a,s]of o){let u=e();r(s,u),s.replace(u,!0),i&&(a===i.anchor.key&&i.anchor.set(u.getKey(),i.anchor.offset,i.anchor.type),a===i.focus.key&&i.focus.set(u.getKey(),i.focus.offset,i.focus.type))}i&&t.is(_n())&&l6(i)}function Ven(t){return t.getNode().isAttached()}function Hyi(t){let e=t;for(;e!==null&&!u6(e);){let r=e.getLatest(),n=e.getParent();r.getChildrenSize()===0&&e.remove(!0),e=n}}function Wyi(t,e,r=null){let n=t.getStartEndPoints(),o=n?n[0]:null,i=t.getNodes(),a=i.length;if(o!==null&&(a===0||a===1&&o.type==="element"&&o.getNode().getChildrenSize()===0)){let l=o.type==="text"?o.getNode().getParentOrThrow():o.getNode(),c=l.getChildren(),d=e();return d.setFormat(l.getFormatType()),d.setIndent(l.getIndent()),c.forEach(f=>d.append(f)),r&&(d=r.append(d)),void l.replace(d)}let s=null,u=[];for(let l=0;l<a;l++){let c=i[l];u6(c)?(mwt(t,u,u.length,e,r),u=[],s=c):s===null||s!==null&&cQr(c,s)?u.push(c):(mwt(t,u,u.length,e,r),u=[c])}mwt(t,u,u.length,e,r)}function mwt(t,e,r,n,o=null){if(e.length===0)return;let i=e[0],a=new Map,s=[],u=_i(i)?i:i.getParentOrThrow();u.isInline()&&(u=u.getParentOrThrow());let l=!1;for(;u!==null;){let m=u.getPreviousSibling();if(m!==null){u=m,l=!0;break}if(u=u.getParentOrThrow(),u6(u))break}let c=new Set;for(let m=0;m<r;m++){let h=e[m];_i(h)&&h.getChildrenSize()===0&&c.add(h.getKey())}let d=new Set;for(let m=0;m<r;m++){let h=e[m],y=h.getParent();if(y!==null&&y.isInline()&&(y=y.getParent()),y!==null&&fQr(h)&&!d.has(h.getKey())){let g=y.getKey();if(a.get(g)===void 0){let b=n();b.setFormat(y.getFormatType()),b.setIndent(y.getIndent()),s.push(b),a.set(g,b),y.getChildren().forEach(_=>{b.append(_),d.add(_.getKey()),_i(_)&&_.getChildrenKeys().forEach(w=>d.add(w))}),Hyi(y)}}else if(c.has(h.getKey())){_i(h)||gwt(179);let g=n();g.setFormat(h.getFormatType()),g
`||c===`\r
`?l.insertParagraph():c===" "?l.insertNodes([nQr()]):l.insertText(c)}}}else e.insertRawText(a)}function Pwt(t,e,r){t.dispatchCommand(HQr,{nodes:e,selection:r})||(r.insertNodes(e),function(n){if(Nr(n)&&n.isCollapsed()){let o=n.anchor,i=null,a=IY(o,"previous");if(a)if(fke(a))i=a.origin;else{let s=iQr(a,tz(Oi(),"next").getFlipped());for(let u of s){if(Zi(u.origin)){i=u.origin;break}if(_i(u.origin)&&!u.origin.isInline())break}}if(i&&Zi(i)){let s=i.getFormat(),u=i.getStyle();n.format===s&&n.style===u||(n.format=s,n.style=u,n.dirty=!0)}}}(r))}function Mtn(t,e,r,n=[]){let o=e===null||r.isSelected(e),i=_i(r)&&r.excludeFromCopy("html"),a=r;if(e!==null){let l=ez(r);l=Zi(l)&&e!==null?Wke(e,l):l,a=l}let s=_i(a)?a.getChildren():[],u=function(l){let c=l.exportJSON(),d=l.constructor;if(c.type!==d.getType()&&Kke(58,d.name),_i(l)){let f=c.children;Array.isArray(f)||Kke(59,d.name)}return c}(a);if(Zi(a)){let l=a.__text;l.length>0?u.text=l:o=!1}for(let l=0;l<s.length;l++){let c=s[l],d=Mtn(t,e,c,u.children);!o&&_i(r)&&d&&r.extractWithChild(c,e,"clone")&&(o=!0)}if(o&&!i)n.push(u);else if(Array.isArray(u.children))for(let l=0;l<u.children.length;l++){let c=u.children[l];n.push(c)}return o}function Rtn(t,e){let r=[],n=Oi().getChildren();for(let o=0;o<n.length;o++)Mtn(t,e,n[o],r);return{namespace:t._config.namespace,nodes:r}}function Itn(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r],o=gQr(n);Zi(o)&&Qen(o),e.push(o)}return e}var UY=null;async function Jbi(t,e,r){if(UY!==null)return!1;if(e!==null)return new Promise((l,c)=>{t.update(()=>{l(Otn(t,e,r))})});let n=t.getRootElement(),o=t._window||window,i=window.document,a=Jvt(o);if(n===null||a===null)return!1;let s=i.createElement("span");s.style.cssText="position: fixed; top: -1000px;",s.append(i.createTextNode("#")),n.append(s);let u=new Range;return u.setStart(s,0),u.setEnd(s,1),a.removeAllRanges(),a.addRange(u),new Promise((l,c)=>{let d=t.registerCommand(hke,f=>(Ffe(f,ClipboardEvent)&&(d(),UY!==null&&(window.clearTimeout(UY),UY=null),l(Otn(t,f,r))),!0),mke);UY=window.setTimeout(()=>{d(),UY=null,l(!1)},50),i.execCommand("copy"),s.remove()})}function Otn(t,e,r){if(r===void 0){let o=Jvt(t._window);if(!o)return!1;let i=o.anchorNode,a=o.focusNode;if(i!==null&&a!==null&&!een(t,i,a))return!1;let s=_n();if(s===null)return!1;r=Atn(s)}e.preventDefault();let n=e.clipboardData;return n!==null&&(Ntn(n,r),!0)}var Kbi=[["text/html",Etn],["application/x-lexical-editor",Ptn]];function Atn(t=_n()){let e={"text/plain":t?t.getTextContent():""};if(t){let r=lke();for(let[n,o]of Kbi){let i=o(r,t);i!==null&&(e[n]=i)}}return e}function Ntn(t,e){for(let r in e){let n=e[r];n!==void 0&&t.setData(r,n)}}var RN=Mwt,mHs=RN.$generateJSONFromSelectedNodes,hHs=RN.$generateNodesFromSerializedNodes,gHs=RN.$getClipboardDataFromSelection,Dtn=RN.$getHtmlContent,yHs=RN.$getLexicalContent,Rwt=RN.$insertDataTransferForPlainText,bHs=RN.$insertDataTransferForRichText,_Hs=RN.$insertGeneratedNodes,vHs=RN.copyToClipboard,wHs=RN.setLexicalClipboardDataTransfer;var Iwt={};En(Iwt,{registerPlainText:()=>e_i});var BY=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,Gbi=BY&&"documentMode"in document?document.documentMode:null,Xbi=!(!BY||!("InputEvent"in window)||Gbi)&&"getTargetRanges"in new window.InputEvent("input"),Zbi=BY&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),jtn=BY&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,Ybi=BY&&/^(?=.*Chrome).*/i.test(navigator.userAgent),Qbi=BY&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!Ybi;function $tn(t,e){e.update(()=>{if(t!==null){let r=Ffe(t,KeyboardEvent)?null:t.clipboardData,n=_n();if(n!==null&&r!=null){t.preventDefault();let o=Dtn(e);o!==null&&r.setData("text/html",o),r.setData("text/plain",n.getTextContent())}}})}function e_i(t){return SL(t.registerCommand(NY,e=>{let r=_n();return!!Nr(r)&&(r.deleteCharacter(e),!0)},il),t.registerCommand(MQr,e=>{let r=_n();return!!Nr(r)&&(r.deleteWord(e),!0)},il),t.registerCommand(PQr,e=>{let r=_n();return!!Nr(r)&&(r.deleteLine(e),!0)},il),t.registerCommand(OQr,e=>{let r=_n();if(!Nr(r))return!1;if(ty
`)};function _rn({onWebTabsChange:t,onWebTabsRemoved:e,onActiveWebTabAdded:r,onActiveWebTabRemoved:n}){return dz.default.createElement(dz.default.Fragment,null,dz.default.createElement(UT,{config:k_i,onChange:t,onRemoved:e}),(r||n)&&dz.default.createElement(q_i,{onActiveWebTabAdded:r,onActiveWebTabRemoved:n}))}function q_i({onActiveWebTabAdded:t,onActiveWebTabRemoved:e}){let r={isPillNode:iwt,extractData:()=>!0,getKey:()=>"active-web-tab"},n=dz.default.useCallback(i=>{i.length>0&&t&&t()},[t]),o=dz.default.useCallback(i=>{i.length>0&&e&&e()},[e]);return dz.default.createElement(UT,{config:r,onChange:n,onRemoved:o})}var vrn=$(J());function wrn({enableURLPills:t=!1,onImagePaste:e}){let[r]=Di();return vrn.default.useEffect(()=>r.registerCommand(bke,n=>{let o=n.clipboardData;if(!o)return!1;if(e){let p=o.items;if(p){let m=Array.from(p).filter(h=>h.type.indexOf("image")!==-1);if(m.length>0)return n.preventDefault(),Promise.all(m.map(h=>h.getAsFile())).then(h=>{let y=h.filter(g=>g!==null);y.length>0&&e(y)}),!0}}let i=o.getData("text/plain"),a=i.includes("[["),s=t&&i.includes("http"),u=i.includes("@"),l=i.includes("#"),c=i.includes("{")&&i.includes("}");if(!i||!a&&!s&&!u&&!l&&!c)return!1;let d=aqe(i,{includeNotes:!0,includeURLs:t,includeTools:!0,includeCustomTemplates:!0});return d.some(p=>p.type==="note-pill"||p.type==="active-note-pill"||t&&p.type==="url-pill"||p.type==="tool-pill"||p.type==="folder-pill")?(n.preventDefault(),r.update(()=>{let p=_n();if(!Nr(p))return;let m=sqe(d);m.length>0&&p.insertNodes(m)}),!0):!1},_L),[r,t,e]),null}var Srn=$(J());function Crn(){let[t]=Di();return Srn.default.useEffect(()=>t.registerCommand(iqe,e=>{let{text:r,options:n={}}=e;return t.update(()=>{Qtn(r,n)}),!0},il),[t]),null}var Hv=$(J());var xrn=(0,Hv.createContext)(void 0);function fz(){let t=(0,Hv.useContext)(xrn);if(t===void 0)throw new Error("useChatInput must be used within a ChatInputProvider");return t}function Trn({children:t}){let[e,r]=(0,Hv.useState)(null),[n,o]=(0,Hv.useState)(null),i=(0,Hv.useCallback)(c=>{r(c)},[]),a=(0,Hv.useCallback)(c=>{o(()=>c)},[]),s=(0,Hv.useCallback)((c,d=!1)=>{e&&e.dispatchCommand(iqe,{text:c,options:{enableURLPills:d,insertAtSelection:!0}})},[e]),u=(0,Hv.useCallback)(()=>{n&&n()},[n]),l={insertTextWithPills:s,focusInput:u,registerEditor:i,registerFocusHandler:a};return Hv.default.createElement(xrn.Provider,{value:l},t)}$r();Xe();sd();Ye();var U_i=({value:t,onChange:e,onSubmit:r,placeholder:n="Type a message...",disabled:o=!1,className:i="",onNotesChange:a,onNotesRemoved:s,onURLsChange:u,onURLsRemoved:l,onToolsChange:c,onToolsRemoved:d,onFoldersChange:f,onFoldersRemoved:p,onActiveNoteAdded:m,onActiveNoteRemoved:h,onWebTabsChange:y,onWebTabsRemoved:g,onActiveWebTabAdded:b,onActiveWebTabRemoved:_,onEditorReady:w,onImagePaste:T,onTagSelected:O,isCopilotPlus:E=!1,currentActiveFile:P=null,currentChain:R})=>{let[I,N]=Yi.default.useState(null),[z,V]=Yi.default.useState(null),k=fz(),X=Br(),B=Yi.default.useCallback(oe=>{N(()=>oe)},[]);(0,Yi.useEffect)(()=>{z&&k.registerEditor(z)},[z,k]),(0,Yi.useEffect)(()=>{I&&k.registerFocusHandler(I)},[I,k]);let Q=Yi.default.useMemo(()=>({namespace:"ChatEditor",theme:{root:"tw-outline-none",paragraph:"tw-m-0"},nodes:[oz,iz,p6,vL,wL,az,...u?[f6]:[]],onError:oe=>{ne("Lexical error:",oe)},editable:!o}),[u,o]),Y=(0,Yi.useCallback)(oe=>{oe.read(()=>{let de=Oi().getTextContent();e(de)})},[e]),K=(0,Yi.useCallback)(oe=>{V(oe),w?.(oe)},[w]);return Yi.default.createElement(Bke,{initialConfig:Q},Yi.default.createElement(jke,{currentActiveFile:P},Yi.default.createElement("div",{className:we("tw-relative",i)},Yi.default.createElement(Xke,{contentEditable:Yi.default.createElement(Zke,{className:"tw-max-h-40 tw-min-h-[60px] tw-w-full tw-resize-none tw-overflow-y-auto tw-rounded-md tw-border-none tw-bg-transparent tw-px-2 tw-text-sm tw-text-normal tw-outline-none focus-visible:tw-ring-0","aria-label":"Chat input"}),placeholder:Yi.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-left-2 tw-top-0 tw-select-none tw-text-sm tw-text-muted/60"},n),ErrorBoundary:oqe}),Yi
\u2026 (truncated ${(r.length-qfe).toLocaleString()} characters for display)`:r}catch{return e.length>qfe?`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`:e}},enn=({toolName:t,displayName:e,emoji:r,isExecuting:n,result:o,confirmationMessage:i,onAccept:a,onReject:s})=>{let[u,l]=(0,al.useState)(!1),c=(0,al.useMemo)(()=>uvi(t,o),[t,o]),d=n&&!o,f=!d&&c!==null;return al.default.createElement(_y,{open:f?u:!1,onOpenChange:l,disabled:!f,"aria-disabled":!f,className:"tw-my-3 tw-w-full sm:tw-max-w-sm"},al.default.createElement("div",{className:we("tw-rounded-md tw-border tw-border-border tw-bg-secondary/50",d&&"tw-relative tw-overflow-hidden")},d&&al.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-[1] tw-overflow-hidden"},al.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:svi}})),al.default.createElement(BT,{className:we("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")},al.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},al.default.createElement("span",{className:"tw-text-base"},r),al.default.createElement("span",{className:"tw-font-medium"},t==="readNote"?`${d?"Reading":"Read"} ${e}`:`${d?"Calling":"Called"} ${e}`,d&&t!=="readNote"&&"..."),d&&i&&al.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"\u2022 ",i,"...")),al.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!d&&a&&s&&al.default.createElement(al.default.Fragment,null,al.default.createElement("button",{onClick:p=>{p.stopPropagation(),a()},className:"hover:tw-bg-green-rgb/20 tw-rounded tw-p-1",title:"Accept"},al.default.createElement(Yu,{className:"tw-size-4 tw-text-success"})),al.default.createElement("button",{onClick:p=>{p.stopPropagation(),s()},className:"hover:tw-bg-red-rgb/20 tw-rounded tw-p-1",title:"Reject"},al.default.createElement(qo,{className:"tw-size-4 tw-text-error"}))),f&&al.default.createElement(ld,{className:we("tw-size-4 tw-text-muted tw-transition-transform",u&&"tw-rotate-90")}))),al.default.createElement(vy,null,al.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"},al.default.createElement("div",{className:"tw-text-sm tw-text-muted"},al.default.createElement("pre",{className:"tw-overflow-x-auto tw-whitespace-pre-wrap tw-font-mono tw-text-xs"},c??"No result available"))))))};Xe();var tnn=60*60*1e3,GY=()=>(window.__copilotToolCallRoots||(window.__copilotToolCallRoots=new Map),window.__copilotToolCallRoots),XY=()=>(window.__copilotErrorBlocks||(window.__copilotErrorBlocks=new Map),window.__copilotErrorBlocks),aSt=(t,e,r)=>{if(e.size>0)return;r.get(t)===e&&r.delete(t)},sSt=(t,e,r,n,o,i)=>{try{n.root.unmount()}catch(a){Te(`Error unmounting tool call root during ${o}`,r,a)}n.isUnmounting=!1,e.get(r)===n&&e.delete(r),aSt(t,e,i)},rnn=(t,e,r,n,o,i)=>{e.delete(r),n.isUnmounting=!0,setTimeout(()=>{try{n.root.unmount()}catch(a){Te(`Error unmounting tool call root during ${o}`,r,a)}n.isUnmounting=!1,aSt(t,e,i)},0)},mz=(t,e,r,n,o,i)=>{n.isUnmounting||(n.isUnmounting=!0,setTimeout(()=>{let a=i.get(t),s=a?.get(r);if(!a||s!==n){n.isUnmounting=!1,aSt(t,e,i);return}sSt(t,a,r,s,o,i)},0))},nnn=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(sSt(t,e,r,i,`${o} (finalizing stale root)`,GY()),i=void 0),i&&i.container&&i.container!==n&&(rnn(t,e,r,i,`${o} (container changed)`,GY()),i=void 0),i||(i={root:(0,iSt.createRoot)(n),isUnmounting:!1,container:n},e.set(r,i)),i},onn=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(sSt(t,e,r,i,`${o} (finalizing stale error root)`,XY()),i=void 0),i&&i.container&&i.container!==n&&(rnn(t,e,r,i,`${o} (container changed)`,XY()),i=void 0),i||(i={root:(0,iSt.createRoot)(n),isUnmounting:!1,container:n},e.set(r,i)),i},inn=(t,e)
<summary style="${qe}">${Ce}</summary>
<div class="tw-text-muted" style="${Nt}">${ht.trim()}</div>
</details>
`});let ct=new RegExp(`<${le}>([\\s\\S]*)$`);return Z=Z.replace(ct,(ze,ht)=>`<div style="${lt}">
<div style="${qe}">${He}</div>
<div class="tw-text-muted" style="${Nt}">${ht.trim()}</div>
</div>`),Z}let je=new RegExp(`<${le}>([\\s\\S]*?)<\\/${le}>`,"g");return Z.replace(je,(Gr,ct)=>{let ze=`${le}-${Ot}`;Ot+=1;let ht=uSt(h.current,ze),$e=_.get(ht)?" open":"";return`<details id="${ht}"${$e} style="${lt}">
<summary style="${qe}">${Ce}</summary>
<div class="tw-text-muted" style="${Nt}">${ct.trim()}</div>
</details>
`})},K=Z=>Y(Z,"think","Thought for a while","Thinking..."),oe=Z=>{let le=lt=>{let qe=/```(?:xml)?\s*([\s\S]*?<writeToFile>[\s\S]*?<\/writeToFile>[\s\S]*?)\s*```/g;return lt.replace(qe,(Nt,mt)=>mt.trim())},Ce=lt=>{if(!r)return lt;let qe=/```xml\s*([\s\S]*?<writeToFile>[\s\S]*?)$/g;return lt.replace(qe,(Nt,mt)=>mt.trim())},He=le(Z);return He=Ce(He),Y(He,"writeToFile","Generated new content","Generating changes...")},ue=(Z,le,Ce)=>Z.split(/(```[\s\S]*?```|`[^`]*`)/g).map((lt,qe)=>qe%2===0?lt.replace(le,(Nt,mt)=>{let Ot=e.metadataCache.getFirstLinkpathDest(mt,X);return Ot?Ce(Ot):Nt}):lt).join(""),de=B(V),W=Q(de).replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),ie=ue(W,/!\[\[(.*?)]]/g,Z=>`![](${e.vault.getResourcePath(Z)})`),j=K(ie),A=oe(j),U=G4r(A,w.enableInlineCitations),H=ue(U,/(?<!!)\[\[([^\]]+)]]/g,Z=>`<a href="obsidian://open?file=${encodeURIComponent(Z.path)}">${Z.basename}</a>`);return(Z=>{if(!r)return Z;let le=/!\[([^\]]*)\]\(([^)]+)\)/g;return Z.replace(le,(Ce,He,lt)=>{let qe=yWe(lt);if(!qe)return Ce;let Nt=He||"YouTube Video",mt=`https://i.ytimg.com/vi/${qe}/hqdefault.jpg`;return`[![${Nt}](${mt})](${lt})`})})(H)},[e,r,w.enableInlineCitations,_]);(0,ur.useEffect)(()=>{let V=f.current;if(!V||t.sender===Zs||!r)return;let k=Q=>{if(Q instanceof PointerEvent&&(Q.button!==0||!Q.isPrimary))return;let Y=Eqe(Q,V);if(!Y||!lSt(Q,Y))return;let K=!Y.open;Y.open=K,_.set(Y.id,K)},X=Q=>{let Y=Eqe(Q,V);!Y||!lSt(Q,Y)||Q.preventDefault()},B=Q=>{let Y=Eqe(Q,V);Y&&_.set(Y.id,Y.open)};return V.addEventListener("pointerdown",k,!0),V.addEventListener("click",X,!0),V.addEventListener("toggle",B,!0),()=>{V.removeEventListener("pointerdown",k,!0),V.removeEventListener("click",X,!0),V.removeEventListener("toggle",B,!0)}},[r,t.sender,_]),(0,ur.useEffect)(()=>{if(m.current=!1,f.current&&t.sender!==Zs){p.current||(p.current=new _6.Component),ynn(f.current,_,{overwriteExisting:!r});let V=t.message,k=Bce(V);k?.hasReasoning&&k.status!=="idle"?d({status:k.status,elapsedSeconds:k.elapsedSeconds,steps:k.steps}):d(null);let X=k?.contentAfter??V,B=O(X),Q=cst(B,h.current);if(!m.current){let Y=new Set,K=new Set;f.current.querySelectorAll('[id^="tool-call-"]').forEach(j=>{let A=j.id.replace("tool-call-","");Y.add(A)}),f.current.querySelectorAll('[id^="error-block-"]').forEach(j=>{let A=j.id.replace("error-block-","");K.add(A)}),f.current.querySelectorAll(".message-segment").forEach(j=>j.remove());let L=0;Q.segments.forEach(j=>{if(j.type==="text"&&j.content.trim()){let A=f.current.children[L],U=document.createElement("div");U.className="message-segment",A?f.current.insertBefore(U,A):f.current.appendChild(U),_6.MarkdownRenderer.renderMarkdown(j.content,U,"",p.current),pvi(U),L++}else if(j.type==="toolCall"&&j.toolCall){let A=j.toolCall.id,U=document.getElementById(`tool-call-${A}`);if(!U){let re=f.current.children[L],Z=document.createElement("div");Z.className="tool-call-container",Z.id=`tool-call-${A}`,re?f.current.insertBefore(Z,re):f.current.appendChild(Z),U=Z}let H=nnn(h.current,y.current,A,U,"render refresh");!m.current&&!H.isUnmounting&&inn(H,j.toolCall),L++}else if(j.type==="error"&&j.error){let A=j.error.id,U=document.getElementById(`error-block-${A}`);if(!U){let re=f.current.children[L],Z=document.createElement("div");Z.className="error-block-container",Z.id=`error-block-${A}`,re?f.current.insertBefore(Z,re):f.current.appendChild(Z),U=Z}let H=onn(h.current,g.current,A,U,"error render");!m.current&&!H.isUnmounting&&ann(H,j.error),L++}});let W=new Set(Q.segments.filter(j=>j.type==="toolCall"&&j.toolCall).map(j=>j.toolCall.id));Y.forEach(j=>{if(!W.has(j)){let A=document.getElementById(`tool-call-${j}`);A&&(snn(h.current,y.current,j,"tool call removal"),A.remove())}});let ie=new Set(Q.segments.filter(j=>j.type==="error"&&j.error).map(j=>j.error.id));K.forEach(j=>{if(!ie.has(j)){let A=document.getElementById(`error-block-${j}`);A&&(unn(h.current,g.current,j,"error block removal"),A.remove())}})}}return()=>{m.current=!0}},[t,e,p,r,O,_]),(0,ur.useEffect)(()=>{let V=p,k=h.current,X=y.current,B=g.current;retur
Use 'Refresh Vault Index' or 'Force Reindex Vault' commands to build the index after enabling. Pick your embedding model below.`:`Disabling semantic search will fall back to index-free lexical search (less resource-intensive, could be less accurate).
Your existing index will be preserved but not used.`,i=n?"Enable Semantic Search":"Disable Semantic Search",a=n?"Enable":"Disable";super(e,r,o,i,a,"Cancel")}};Xe();BG();NOe();Nte();var bnn=require("obsidian");function _nn(t,e=20){let r=app.metadataCache.getFileCache(t),n=[];if(r?.links)for(let o of r.links){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}if(r?.embeds&&n.length<e)for(let o of r.embeds){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}return[...new Set(n)]}function vnn(t,e=20){let r=[],n=app.metadataCache.getBacklinksForFile(t);if(n?.data)for(let[o]of n.data){let i=app.vault.getAbstractFileByPath(o);if(i instanceof bnn.TFile&&(r.push(i),r.length>=e))break}return r}FEe();Pl();Ye();Fc();var pSt=require("obsidian"),Rqe=20,wnn=.7,Mqe=.3;function gvi(){let t=te();return t.enableMiyo&&t.enableSemanticSearchV3&&yH()}function yvi(t,e){let r=new Map;for(let n of t){let o=r.get(n.document.path);o?n.score>o&&r.set(n.document.path,n.score):r.set(n.document.path,n.score)}return r.delete(e),r}function Cnn(t){if(t.size<=Rqe)return t;let e=Array.from(t.entries()).sort((r,n)=>n[1]-r[1]).slice(0,Rqe);return new Map(e)}function bvi(t){return Array.isArray(t.embedding)&&t.embedding.length>0}function _vi(t){return t.some(e=>e.content.trim().length>0)}async function vvi({db:t,filePath:e,currentNoteEmbeddings:r}){let n=r.map(s=>wq.getDocsByEmbedding(t,s,{limit:Rqe,similarity:0})),i=(await Promise.all(n)).flat(),a=yvi(i,e);return Cnn(a)}async function Snn(t){try{let e=te(),r=new S0,n=await r.resolveBaseUrl(e.selfHostUrl),o=zG(app),i=await r.searchRelated(n,t,{sourceId:o,limit:Rqe}),a=new Map,s=i.results||[];for(let u of s){if(u.path===t||typeof u.score!="number"||Number.isNaN(u.score))continue;let l=a.get(u.path);(l===void 0||u.score>l)&&a.set(u.path,u.score)}return te().debug&&F(`RelevantNotes(Miyo): received ${s.length} chunks, collected ${a.size} note scores`),Cnn(a)}catch(e){return Te("RelevantNotes(Miyo): failed to compute similarity scores",e),new Map}}async function wvi(t){if(gvi())return Snn(t);let e=await O0.getInstance().getDocumentsByPath(t);if(e.length===0)return new Map;let r=e.filter(n=>bvi(n)).map(n=>n.embedding);if(r.length>0)try{let n=await O0.getInstance().getDb();return vvi({db:n,filePath:t,currentNoteEmbeddings:r})}catch(n){return Te("RelevantNotes(Orama): failed to compute similarity scores",n),new Map}return _vi(e)?Snn(t):new Map}function Svi(t){let e=new Map,n=_nn(t).map(a=>a.path);for(let a of n)e.set(a,{links:!0,backlinks:!1});let i=vnn(t).map(a=>a.path);for(let a of i)e.has(a)?e.set(a,{links:!0,backlinks:!0}):e.set(a,{links:!1,backlinks:!0});return e}function Cvi(t,e){let r=new Map,n=wnn+Mqe;for(let[o,i]of t)r.set(o,i*wnn/n);for(let[o,i]of e){let a=0;i.links&&i.backlinks?a=Mqe:(i.links||i.backlinks)&&(a=Mqe*.8),r.set(o,(r.get(o)??0)+a)}return r}async function xnn({filePath:t}){let e=app.vault.getAbstractFileByPath(t);if(!(e instanceof pSt.TFile))return[];let r=await wvi(t),n=Svi(e),o=Cvi(r,n);return Array.from(o.entries()).sort((a,s)=>{let u=a[0],l=s[0],c=Iqe(r.get(u)??0),d=Iqe(r.get(l)??0);return c!==d?d-c:s[1]-a[1]}).map(([a,s])=>{let u=app.vault.getAbstractFileByPath(a);return!(u instanceof pSt.TFile)||u.extension!=="md"?null:{document:{path:a,title:u.basename},metadata:{score:s,similarityScore:r.get(a),hasOutgoingLinks:n.get(a)?.links??!1,hasBacklinks:n.get(a)?.backlinks??!1}}}).filter(a=>a!==null)}function Iqe(t){return t>.7?3:t>.55?2:1}Bat();Or();var Ufe=require("obsidian"),At=$(J()),xvi=15*24*60*60*1e3;function Tvi(t){return!t.enableMiyo||!t.enableSemanticSearchV3||t.selfHostModeValidatedAt==null?!1:(t.selfHostValidationCount??0)>=3?!0:Date.now()-t.selfHostModeValidatedAt<xvi}function Ovi(t){let[e,r]=(0,At.useState)([]),[n,o]=(0,At.useState)(0),i=fSt();return(0,At.useEffect)(()=>Uat(()=>o(a=>a+1)),[]),(0,At.useEffect)(()=>{async function a(){if(i?.path)try{let s=await xnn({filePath:i.path});r(s)}catch(s){Te("Failed to fetch relevant notes",s),r([])}}a()},[i?.path,t,n]),e}function Evi(t,e){let[r,n]=(0,At
`).map(b=>{if(!b.trim())return b;try{return new URL(b.trim()),b}catch{return b}});p("contextSource.webUrls",g.join(`
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),vn.default.createElement(Vo,{label:"YouTube URLs"},vn.default.createElement(h_,{value:u.contextSource?.youtubeUrls,onChange:h=>{let g=h.target.value.split(`
`).map(b=>{if(!b.trim())return b;try{let _=new URL(b.trim());return _.hostname.includes("youtube.com")||_.hostname.includes("youtu.be"),b}catch{return b}});p("contextSource.youtubeUrls",g.join(`
`))},placeholder:"Enter YouTube URLs, one per line",className:"tw-min-h-20 tw-w-full"})))),vn.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},vn.default.createElement(pe,{variant:"ghost",onClick:r,disabled:o},"Cancel"),vn.default.createElement(pe,{onClick:m,disabled:o||!f()},o?"Saving...":"Save")))}var Xfe=class extends Gfe.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,fon.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(vn.default.createElement(ywi,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};Cn();$r();Xe();Ye();l1();Or();var mon=require("obsidian"),ot=$(J());function bwi(t,e,r={}){let{caseSensitive:n=!1,searchInName:o=!0,searchInDescription:i=!0}=r;if(!e.trim())return!0;let a=n?e:e.toLowerCase();return!!(o&&(n?t.name:t.name.toLowerCase()).includes(a)||i&&t.description&&(n?t.description:t.description.toLowerCase()).includes(a))}function pon(t,e,r={}){return!t||t.length===0?[]:e.trim()?t.filter(n=>bwi(n,e,r)):t}function _wi(t){let[e,r]=(0,ot.useState)(()=>t?.getRevision()??0);return(0,ot.useEffect)(()=>{if(!t){r(0);return}return r(t.getRevision()),t.subscribe(()=>{r(t.getRevision())})},[t]),e}function vwi({project:t,loadContext:e,onEdit:r,onDelete:n}){return ot.default.createElement("div",{className:"tw-group tw-flex tw-cursor-pointer tw-items-center tw-justify-between tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-border-border tw-p-3 tw-transition-all tw-duration-200 tw-bg-secondary/40 hover:tw-border-interactive-accent hover:tw-text-accent hover:tw-shadow-[0_2px_12px_rgba(0,0,0,0.1)] active:tw-scale-[0.98]",onClick:()=>e(t)},ot.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-gap-2 tw-overflow-hidden"},ot.default.createElement("div",{className:"tw-text-accent"},ot.default.createElement($m,{className:"tw-size-4"})),ot.default.createElement("div",{className:"tw-flex tw-flex-1 tw-flex-col tw-gap-1.5 tw-overflow-hidden"},ot.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[13px] tw-font-medium tw-text-normal"},t.name),t.description&&ot.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[12px] tw-text-muted/80"},t.description))),ot.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-1 tw-opacity-100 tw-transition-opacity tw-duration-200"},ot.default.createElement(yn,null,ot.default.createElement(bn,{asChild:!0},ot.default.createElement(pe,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),r(t)}},ot.default.createElement(Xb,{className:"tw-size-4"}))),ot.default.createElement(dn,{side:"bottom"},"Edit Project")),ot.default.createElement(yn,null,ot.default.createElement(bn,{asChild:!0},ot.default.createElement(pe,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),e(t)}},ot.default.createElement(V5,{className:"tw-size-4"}))),ot.default.createElement(dn,{side:"bottom"},"Start Chat")),ot.default.createElement(yn,null,ot.default.createElement(bn,{asChild:!0},ot.default.createElement(pe,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),new zu(app,()=>n(t),`Are you sure you want to delete project "${t.name}"?`,"Delete Project").open()}},ot.default.createElement(Vy,{className:"tw-size-4"}))),ot.default.createElement(dn,{side:"bottom"},"Delete Project"))))}var ISt=(0,ot.memo)(({className:t,projects:e,defaultOpen:r=!1,app:n,plugin:o,onProjectAdded:i,onEditProject:a,hasMessages:s=!1,showChatUI:u,onClose:l,onProjectClose:c})=>{let[d,f]=(0,ot.useState)(r),[p,m]=(0,ot.useState)(!1),[h,y]=(0,ot.useState)(null),[g,b]=(0,ot.useState)(""),_=fz(),w=Br(),T=o?.projectManager?.getProjectUsageTimestampsManager?.(),O=_wi(T);(0,ot.useEffect)(()=>{s&&f(!1)},[s]);let E=(0,ot.useMemo)(()=>mO(e,w.projectListSortStrategy,{getName:k=>k.name,getCreatedAtMs:k=>k.created,getLastUsedAtMs:k=>T?T.getEffectiveLastUsedAt(k.id,k.UsageTimestamps):k.UsageTimestamps}),[e,w.projectListSortStrategy,T,O]),P=(0,ot.useM
- a positive number
- less than the value passed to \`max\` (or ${jSt} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`}var $St=xon,Pon=Oon;$r();var Yfe=Zfe.forwardRef(({className:t,value:e,...r},n)=>Zfe.createElement($St,{ref:n,className:we("tw-relative tw-h-2 tw-w-full tw-overflow-hidden tw-rounded-full tw-bg-interactive-accent/20 tw-border-interactive-accent/30",t),...r},Zfe.createElement(Pon,{className:"tw-size-full tw-flex-1 tw-bg-interactive-accent tw-transition-all",style:{transform:`translateX(-${100-Math.min(Math.max(e||0,0),100)}%)`}})));Yfe.displayName=$St.displayName;Cn();Or();ra();function LSt({onClose:t,onPause:e,onResume:r,onStop:n}){let[o]=l5(),i=(0,Jqe.useRef)(null),{isActive:a,isPaused:s,indexedCount:u,totalFiles:l,errors:c,completionStatus:d}=o,f=l>0?Math.round(u/l*100):0;(0,Jqe.useEffect)(()=>(i.current&&(clearTimeout(i.current),i.current=null),!a&&d!=="none"&&!(d==="error"&&l===0)&&(i.current=setTimeout(()=>{t()},3e3)),()=>{i.current&&(clearTimeout(i.current),i.current=null)}),[a,d,l,t]);let p=()=>d==="success"?l===0?"Index Up to Date":"Indexing Complete":d==="cancelled"?"Indexing Cancelled":d==="error"?l===0?"Indexing Failed":"Indexing Complete (with errors)":s?"Indexing Paused":"Indexing Vault";return Qi.createElement(OL,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},Qi.createElement(EL,null,Qi.createElement(v6,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},Qi.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!a&&d!=="none"?d==="error"?Qi.createElement(Gb,{className:"tw-size-4 tw-text-error"}):d==="success"?Qi.createElement(K_,{className:"tw-size-4 tw-text-success"}):Qi.createElement(cx,{className:"tw-size-4"}):s?Qi.createElement(H5,{className:"tw-size-4 tw-text-warning"}):Qi.createElement(Bs,{className:"tw-size-4 tw-animate-spin tw-text-accent"}),Qi.createElement("span",{className:"tw-text-sm"},p())),Qi.createElement(pe,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close",onClick:t},Qi.createElement(qo,{className:"tw-size-4"})))),Qi.createElement(PL,{className:"tw-space-y-3"},l>0&&Qi.createElement("div",{className:"tw-space-y-2"},Qi.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},Qi.createElement("span",{className:"tw-text-muted"},u,"/",l," files"),Qi.createElement("span",{className:"tw-font-medium"},f,"%")),Qi.createElement(Yfe,{value:f,className:"tw-h-2"})),c.length>0&&Qi.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},Qi.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Qi.createElement(Gb,{className:"tw-size-3 tw-text-error"}),Qi.createElement(Qc,{variant:"destructive",className:"tw-text-xs"},c.length," ",c.length===1?"error":"errors")),l===0&&c[0]&&Qi.createElement("span",{className:"tw-text-xs tw-text-error"},c[0])),a&&Qi.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Qi.createElement(pe,{size:"sm",variant:"ghost",className:"tw-h-6 tw-px-2 tw-text-xs",onClick:s?r:e},s?Qi.createElement(Qi.Fragment,null,Qi.createElement(ine,{className:"tw-mr-1 tw-size-3"}),"Resume"):Qi.createElement(Qi.Fragment,null,Qi.createElement(H5,{className:"tw-mr-1 tw-size-3"}),"Pause")),Qi.createElement(pe,{size:"sm",variant:"ghost",className:"tw-h-6 tw-px-2 tw-text-xs",onClick:n},Qi.createElement(e2,{className:"tw-mr-1 tw-size-3"}),"Stop"))))}var Tn=$(J()),FSt=$(J());Or();ra();Cn();Xe();function kSt({plugin:t,setHiddenCard:e,onEditContext:r}){let[n]=s5(),o=n.total,i=n.success,a=n.failed,s=n.processingFiles,[u,l]=(0,FSt.useState)(!1),[c,d]=(0,FSt.useState)(!1),f=i.length+a.length,p=o.length>0?Math.round(f/o.length*100):0,m=y=>y.path,h=async y=>{if(!t?.projectManager){ne("ProjectManager not available");return}try{await t.projectManager.retryFailedItem(y)}catch(g){ne(`Error retrying failed item: ${g}`)}};return Tn.createElement(OL,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},Tn.createElement(EL,null,Tn.createElement(v6,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},Tn.createElement("div",{className:"tw-flex tw-items-center tw-gap-2
`).filter(o=>o.trim()),n=[];for(let o of r){let i=Lwi(t,o.trim());i&&n.push(i)}return n}function Ron(t){let{app:e,contextNotes:r,setContextNotes:n,selectedImages:o,onAddImage:i,containerRef:a}=t,[s,u]=(0,Kqe.useState)(!1);return(0,Kqe.useEffect)(()=>{let l=a.current;if(!l)return;let c=p=>{if(p.preventDefault(),p.dataTransfer){p.dataTransfer.dropEffect="copy";let m=Array.from(p.dataTransfer.items).some(y=>y.kind==="string"),h=Array.from(p.dataTransfer.items).some(y=>y.kind==="file");(m||h)&&u(!0)}},d=p=>{let m=l.getBoundingClientRect(),h=p.clientX,y=p.clientY;(h<m.left||h>=m.right||y<m.top||y>=m.bottom)&&u(!1)},f=async p=>{if(!p.dataTransfer)return;p.preventDefault(),u(!1);let m=p.dataTransfer.items,h=[],y=[];for(let g=0;g<m.length;g++){let b=m[g];b.kind==="string"?h.push(b):b.kind==="file"&&y.push(b)}if(h.length>0){p.stopPropagation();let g=h.map(w=>new Promise(T=>{w.getAsString(O=>T(O))})),b=await Promise.all(g),_=new Map;for(let w of b){let T=Fwi(e,w);for(let O of T)_.set(O.path,O)}for(let w of _.values())if(["png","gif","jpeg","jpg","webp"].includes(w.extension)){if(o.some(I=>I.name===w.name)){new x6.Notice("This image is already in the context");continue}let E=await e.vault.readBinary(w),P=new Blob([E]),R=new File([P],w.name,{type:`image/${w.extension}`});i([R])}else if(yO(w)){if(r.some(E=>E.path===w.path)){new x6.Notice("This note is already in the context");continue}n(E=>[...E,w])}else new x6.Notice(`Unsupported file type: ${w.extension}. Supported types: md, pdf, canvas, and images.`)}else if(y.length>0){let g=[];for(let b of y){let _=b.getAsFile();_&&_.type.startsWith("image/")&&g.push(_)}g.length>0&&i(g)}};return l.addEventListener("dragover",c),l.addEventListener("dragleave",d),l.addEventListener("drop",f),()=>{l.removeEventListener("dragover",c),l.removeEventListener("dragleave",d),l.removeEventListener("drop",f)}},[e,r,o,i,n,a]),{isDragActive:s}}mr();Bt();Xe();qN();var qSt=async(t,e,r,n,o,i={})=>{let a=new AbortController;o(a);try{await e.runChain(t,a,n,r,i)}catch(s){ne("Model request failed:",s);let u=ePe("Model request failed: "+zr(s));r({id:od(),sender:cw,isErrorMessage:!0,message:u,isVisible:!0,timestamp:Mg(new Date)})}};O4();Fc();Ye();Bt();HEe();var Al=require("obsidian");var qt=$(J());qN();var kwi=({chainManager:t,onSaveChat:e,updateUserMessageHistory:r,fileParserManager:n,plugin:o,chatUIState:i,chatInput:a})=>{let s=Br(),u=(0,qt.useContext)(ZY),{messages:l,addMessage:c}=Mon(i),[d]=bF(),[f]=fw(),[p,m]=(0,qt.useState)(""),[h,y]=(0,qt.useState)(""),[g,b]=(0,qt.useState)(null),_=(0,qt.useRef)(null),w=(0,qt.useRef)(null),T=(0,qt.useCallback)(rt=>{let Rr=w.current,Ee=Rr&&rt.sender===cw&&!rt.isErrorMessage&&!rt.id?{...rt,id:Rr}:rt;c(Ee),Ee.sender===cw&&Ee.responseMetadata?.tokenUsage?.totalTokens&&b(Ee.responseMetadata.tokenUsage.totalTokens)},[c]),O=(0,qt.useCallback)(rt=>{_.current=rt},[]),[E,P]=(0,qt.useState)(!1),[R,I]=(0,qt.useState)(dw.DEFAULT),[N,z]=(0,qt.useState)([]),[V,k]=(0,qt.useState)(!1),[X,B]=(0,qt.useState)(!1),[Q,Y]=(0,qt.useState)([]),[K,oe]=(0,qt.useState)(!1),[ue,de]=(0,qt.useState)([]),[L,W]=(0,qt.useState)(null),[ie,j]=(0,qt.useState)(null),[A]=l5(),U=(0,qt.useRef)(!1),H=(0,qt.useRef)(null),re=(0,qt.useCallback)(()=>{o.chatSelectionHighlightController.persistFromPointerDown()},[o]),Z=(0,qt.useMemo)(()=>({setCurrentAiMessage:rt=>U.current&&m(rt),setLoadingMessage:rt=>U.current&&I(rt),setLoading:rt=>U.current&&P(rt)}),[]),[le]=bDt(),Ce=le.length>0,He=V&&!Ce,lt=X&&!Ce,{activeWebTabForMentions:qe}=rz(),Nt=ULe(),mt=()=>Ue!=="project"?!1:L!==null?L:Nt==="loading"||Nt==="error";(0,qt.useEffect)(()=>{W(null)},[Nt]);let Ot=()=>Ue==="project"||ie===!1?!1:A.isActive||A.completionStatus!=="none";(0,qt.useEffect)(()=>{(A.isActive||A.completionStatus!=="none")&&j(null)},[A.isActive,A.completionStatus]);let je=(0,qt.useCallback)(()=>{j(!1),A.isActive||Ig({completionStatus:"none"})},[A.isActive]),Gr=(0,qt.useCallback)(async()=>{(await Promise.resolve().then(()=>(Pl(),Vc))).default.getInstance().pauseIndexing()},[]),ct=(0,qt.useCallback)(async()=>{(await Promise.resolve().then(()=>(Pl(),Vc))).default.ge
`));let Eh={notes:Xv,urls:zb(f)?Rr||[]:[],tags:Ee||[],folders:It||[],selectedTextContexts:le,webTabs:Qt||[]};y(""),Y([]),w.current=`msg-${od()}`,Z.setLoading(!0),Z.setLoadingMessage(dw.DEFAULT);let FC=await i.sendMessage(DL,Eh,f,He,lt,cl.length>0?cl:void 0,Z.setLoadingMessage);h&&r(h),s.autosaveChat&&Dl();let Zv=i.getLLMMessage(FC);Zv&&await qSt(Zv,t,T,Z.setCurrentAiMessage,O,{debug:s.debug,updateLoadingMessage:Z.setLoadingMessage}),s.autosaveChat&&Dl()}catch(cl){ne("Error sending message:",cl),new Al.Notice("Failed to send message. Please try again.")}finally{Z.setLoading(!1),Z.setLoadingMessage(dw.DEFAULT),w.current=null}},Dl=(0,qt.useCallback)(async()=>{if(!iu){ne("App instance is not available.");return}try{await i.saveChat(d)}catch(rt){ne("Error saving chat as note:",zr(rt)),new Al.Notice("Failed to save chat as note. Check console for details.")}},[iu,i,d]),Vi=(0,qt.useCallback)(rt=>{_.current&&(F(`stopping generation..., reason: ${rt}`),_.current.abort(rt),Z.setLoading(!1),Z.setLoadingMessage(dw.DEFAULT))},[Z]);(0,qt.useEffect)(()=>(U.current=!0,()=>{U.current=!1,_.current&&_.current.abort("component-unmount")}),[]);let O_=(0,qt.useCallback)(async rt=>{if(rt<=0){new Al.Notice("Cannot regenerate the first message.");return}let Rr=l[rt];if(!Rr){new Al.Notice("Message not found.");return}Z.setCurrentAiMessage(""),w.current=`msg-${od()}`,Z.setLoading(!0);try{await i.regenerateMessage(Rr.id,Z.setCurrentAiMessage,T)?s.debug&&console.log("Message regenerated successfully"):new Al.Notice("Failed to regenerate message. Please try again."),s.autosaveChat&&Dl()}catch(Be){ne("Error regenerating message:",Be),new Al.Notice("Failed to regenerate message. Please try again.")}finally{Z.setLoading(!1),w.current=null}},[l,i,s.debug,s.autosaveChat,Dl,T,Z]),wg=(0,qt.useCallback)(async(rt,Rr)=>{let Be=l[rt];if(!(!Be||Be.message===Rr))try{if(!await i.editMessage(Be.id,Rr,f,He)){new Al.Notice("Failed to edit message. Please try again.");return}if(Be.sender===Zs){let It=rt<l.length-1;if(await i.truncateAfterMessageId(Be.id),It){w.current=`msg-${od()}`,Z.setLoading(!0);try{let Qt=i.getLLMMessage(Be.id);Qt&&await qSt(Qt,t,T,Z.setCurrentAiMessage,O,{debug:s.debug,updateLoadingMessage:Z.setLoadingMessage})}catch(Qt){ne("Error regenerating AI response:",Qt),new Al.Notice("Failed to regenerate AI response. Please try again.")}finally{Z.setLoading(!1),w.current=null}}}s.autosaveChat&&Dl()}catch(Ee){ne("Error editing message:",Ee),new Al.Notice("Failed to edit message. Please try again.")}},[l,i,f,He,T,t,s.debug,s.autosaveChat,Dl,Z,O]);(0,qt.useEffect)(()=>{e&&e(Dl)},[e,Dl]);let yS=(0,qt.useCallback)(rt=>{let Rr=s.projectList||[];if(Rr.findIndex(Qt=>Qt.name===rt.name)>=0)throw new Error(`Project "${rt.name}" already exists, please use a different name`);let Ee=[...Rr,rt];return Re("projectList",Ee),Gu()?.id===rt.id?wFe().then(()=>{new Al.Notice(`${rt.name} added and context loaded`)}).catch(Qt=>{ne("Error loading project context:",Qt),new Al.Notice(`${rt.name} added but context loading failed`)}):new Al.Notice(`${rt.name} added successfully`),!0},[s.projectList]),ji=(0,qt.useCallback)((rt,Rr)=>{let Be=s.projectList||[];if(!Be.find(Fn=>Fn.name===rt.name))throw new Error(`Project "${rt.name}" does not exist`);let It=Be.map(Fn=>Fn.name===rt.name?Rr:Fn);return Re("projectList",It),Gu()?.id===rt.id?(D4(Rr),wFe().then(()=>{new Al.Notice(`${rt.name} updated and context reloaded`)}).catch(Fn=>{ne("Error reloading project context:",Fn),new Al.Notice(`${rt.name} updated but context reload failed`)})):new Al.Notice(`${rt.name} updated successfully`),!0},[s.projectList]),KT=(0,qt.useCallback)(rt=>{let Be=tx().find(Ee=>Ee.id===rt);gDt(rt),Be?.sourceType==="web"&&o.suppressCurrentWebSelection(Be.url)},[o]);(0,qt.useEffect)(()=>{o.chatSelectionHighlightController.clearIfNoNoteContexts(le)},[le,o]),(0,qt.useEffect)(()=>{let rt=()=>{a.focusInput()};return u?.addEventListener(US.CHAT_IS_VISIBLE,rt),()=>{u?.removeEventListener(US.CHAT_IS_VISIBLE,rt)}},[u,a]);let LC=(0,qt.useCallback)(async rt=>{let Rr=l[rt];if(!Rr){new Al.Notice("Message not found.");return}try{a
Original name: ${a.title}
${a.content}`}):e.push(a)}await th.getInstance().updateCommands([...n.map(a=>({...a,showInSlashMenu:!0})),...e]);let i=`We have upgraded your commands to the new format. They are now also stored as notes in ${mB()}.`;r.length>0&&(await zwi(r),i+=`
We found ${r.length} unsupported commands. They are saved in ${mB()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),Re("inlineEditCommands",[]),new zu(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function USt(){let t=Pv(),e=RWr.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];th.getInstance().updateCommands(r)}async function Fon(){if(te().suggestedDefaultCommands)return;Pv().length===0&&(new zu(app,()=>{USt()},"Would you like to add Copilot recommended commands in your custom prompts folder? These commands will be available through the right-click context menu and slash commands in chat.","Welcome to Copilot","Confirm","Skip").open(),Re("suggestedDefaultCommands",!0))}mr();Ye();sd();ra();Xe();mr();async function kon(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Zs){let o=t[r+1];o?.sender===cw&&await e.saveContext({input:n.message},{output:o.message})}}}ra();sd();mr();var Bon=$(gH());Xe();var qon=["L1_SYSTEM","L2_PREVIOUS","L3_TURN","L4_STRIP","L5_USER"],Uon={L1_SYSTEM:"System Instructions",L2_PREVIOUS:"Previous Turn Context",L3_TURN:"Current Turn Context",L4_STRIP:"Conversation Strip",L5_USER:"User Message"};var bz=class bz{constructor(){}static getInstance(){return bz.instance||(bz.instance=new bz),bz.instance}buildEnvelope(e){let r=qon.map(s=>this.buildLayer(s,e.layerSegments[s]??[])),n=this.serializeLayers(r),o=this.collectLayerHashes(r),i=this.hash(n),a=typeof e.metadata?.debugLabel=="string"?e.metadata.debugLabel:void 0;return a&&F(`[PromptContextEngine] Built envelope for ${a}`,o),{version:bz.ENVELOPE_VERSION,conversationId:e.conversationId,messageId:e.messageId,layers:r,serializedText:n,layerHashes:o,combinedHash:i,debug:{warnings:this.collectWarnings(r)}}}buildLayer(e,r){let n=r.map((i,a)=>({...i,id:i.id||`${e}-segment-${a}`,content:this.normalizeWhitespace(i.content),stable:i.stable??!0})),o=this.normalizeWhitespace(n.map(i=>i.content).filter(Boolean).join(`
`));return{id:e,label:Uon[e],text:o,segments:n,stable:n.every(i=>i.stable),metadata:n.length===1?n[0].metadata:void 0,hash:this.hash(o)}}serializeLayers(e){return e.map(r=>r.text).filter(r=>r.length>0).join(`
`)}collectLayerHashes(e){return e.reduce((r,n)=>(r[n.id]=n.hash,r),{})}hash(e){return(0,Bon.SHA256)(e||"").toString()}normalizeWhitespace(e){return e.replace(/\s+$/g,"").trim()}collectWarnings(e){let r=[];return e.forEach(n=>{if(!n.text)return;n.text.includes("\0")&&r.push(`Layer ${n.id} contains control characters and was normalized`)}),r}};bz.ENVELOPE_VERSION=1;var Yqe=bz;function Vwi(t){let e=/<path>([^<]+)<\/path>/.exec(t);if(e)return e[1];let r=/<url>([^<]+)<\/url>/.exec(t);if(r)return r[1];let n=/<name>([^<]+)<\/name>/.exec(t);return n?n[1]:""}function Hwi(t,e,r,n={}){let o=n.verbatimThreshold??nS.verbatimThreshold;if(t.length<=o)return t;let i=n.previewCharsPerSection??nS.previewCharsPerSection,a=n.maxSections??nS.maxSections,s=aW(t,i,a);return`<prior_context source="${Gje(e)}" type="${r}">
${s}
</prior_context>`}function BSt(t,e,r={}){if(!Kje(e))return t;let n=r.verbatimThreshold??nS.verbatimThreshold;if(t.length<=n)return t;let o=tZ(t,e)||Vwi(t),i=Hce(t),a=iW(e);return Hwi(i,o,a,r)}function zon(){return`<prior_context_note>
The above prior_context blocks contain previews of content from earlier turns.
To access full content: use [[note title]] for notes, or ask to read a specific URL/video.
</prior_context_note>`}function Von(t,e){if(!t.trim())return[];let r=[],o=[...Vce.map(u=>u.tag),"prior_context"],i=new RegExp(`<(${o.join("|")})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,"g"),a=new Map,s;for(;(s=i.exec(t))!==null;){let u=s[0],l=s[1];if(l==="prior_context"){let d=/source="([^"]+)"/.exec(u)?.[1]??"prior_context";r.push({id:d,content:u,stable:e,metadata:{source:"previous_turns_compacted",notePath:d}})}else{let c=tZ(u,l),d;if(c)d=c;else{let p=(a.get(l)||0)+1;a.set(l,p),d=p===1?l:`${l}:${p}`}let f=iW(l)==="note";r.push({id:d,content:u,stable:e,metadata:{source:e?"previous_turns":"current_turn",...f?{notePath:d}:{}}})}}return r}ra();mr();Xe();jW();jZ();Bt();qZ();var npe=require("obsidian");mr();var Qqe=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processEmbeddedPDFs(e,r,n){let o=/!\[\[(.*?\.pdf)\]\]/g,i=[...e.matchAll(o)];for(let a of i){let s=a[1],u=r.getAbstractFileByPath(s);if(u instanceof npe.TFile)try{let l=await n.parseFile(u,r);e=e.replace(a[0],`
<${$te}>
2026-01-05 13:03:55 +08:00
<name>${s}</name>
<content>
${l}
</content>
2026-02-24 07:55:02 +08:00
</${$te}>
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
`)}catch(l){ne(`Error processing embedded PDF ${s}:`,l),e=e.replace(a[0],`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
<${$te}>
2026-01-05 13:03:55 +08:00
<name>${s}</name>
<error>Could not process PDF</error>
2026-02-24 07:55:02 +08:00
</${$te}>
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
`)}}return e}async processDataviewBlocks(e,r){let n=app.plugins?.plugins?.dataview;if(!n)return e;let o=n.api;if(!o)return e;let i=/```(dataview|dataviewjs)\s*\n([\s\S]*?)```/g,a=[...e.matchAll(i)];for(let s=a.length-1;s>=0;s--){let u=a[s],l=u[1],c=u[2].trim(),d=u.index,f=d+u[0].length;try{let p=await Promise.race([this.executeDataviewQuery(o,c,l,r),new Promise((h,y)=>setTimeout(()=>y(new Error("Query timeout")),5e3))]),m=`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
<${Lte}>
2026-01-05 13:03:55 +08:00
<query_type>${l}</query_type>
<original_query>
${c}
</original_query>
<executed_result>
${p}
</executed_result>
2026-02-24 07:55:02 +08:00
</${Lte}>
2026-01-05 13:03:55 +08:00
2026-01-21 08:46:13 +08:00
`;e=e.slice(0,d)+m+e.slice(f)}catch(p){ne("Error executing Dataview query:",p);let m=`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
<${Lte}>
2026-01-05 13:03:55 +08:00
<query_type>${l}</query_type>
<original_query>
${c}
</original_query>
<error>${p instanceof Error?p.message:"Query execution failed"}</error>
2026-02-24 07:55:02 +08:00
</${Lte}>
2026-01-05 13:03:55 +08:00
`;e=e.slice(0,d)+m+e.slice(f)}}return e}async executeDataviewQuery(e,r,n,o){if(n==="dataviewjs")return"[DataviewJS execution not yet supported - showing original query]";let i=await e.query(r,o);if(!i.successful)throw new Error(i.error||"Query failed");return this.formatDataviewResult(i.value)}formatDataviewResult(e){return e?e.type==="list"?this.formatDataviewList(e.values):e.type==="table"?this.formatDataviewTable(e.headers,e.values):e.type==="task"?this.formatDataviewTasks(e.values):Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(`
`):String(e):"No results"}formatDataviewList(e){return!e||e.length===0?"No results":e.map(r=>`- ${this.formatDataviewValue(r)}`).join(`
`)}formatDataviewTable(e,r){if(!r||r.length===0)return"No results";let n=`| ${e.join(" | ")} |
`;n+=`| ${e.map(()=>"---").join(" | ")} |
`;for(let o of r)n+=`| ${o.map(i=>this.formatDataviewValue(i)).join(" | ")} |
`;return n}formatDataviewTasks(e){return!e||e.length===0?"No results":e.map(r=>`- ${r.completed?"[x]":"[ ]"} ${this.formatDataviewValue(r.text||r)}`).join(`
2026-02-24 07:55:02 +08:00
`)}formatDataviewValue(e){return e==null?"":e&&typeof e=="object"&&e.path?`[[${e.path}]]`:Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(", "):String(e)}async buildMarkdownContextContent(e,r,n,o){let i=await n.parseFile(e,r);return i=await this.processEmbeddedNotes(i,e,r,n,o),zb(o)&&(i=await this.processEmbeddedPDFs(i,r,n)),await this.processDataviewBlocks(i,e.path)}async processEmbeddedNotes(e,r,n,o,i){let a=/!\[\[([^\]]+)\]\]/g,s,u=0,l="";for(;(s=a.exec(e))!==null;){l+=e.slice(u,s.index);let c=s[1].trim(),d=await this.buildEmbeddedNoteBlock(c,s[0],r,n,o,i);l+=d,u=s.index+s[0].length}return l+=e.slice(u),l}async buildEmbeddedNoteBlock(e,r,n,o,i,a){let s=this.parseEmbeddedLinkTarget(e);if(!s)return r;let u=s.path===null?n:app.metadataCache.getFirstLinkpathDest(s.path,n.path);if(!(u instanceof npe.TFile))return this.formatEmbeddedNoteBlock({title:s.path??n.basename,path:s.path??n.path,heading:s.heading,blockId:s.blockId,error:"Embedded note not found"});if(u.extension!=="md")return r;try{let l=await i.parseFile(u,o);if(s.heading||s.blockId){let c=this.extractMarkdownSegment(u,l,s);if(!c.found){let d=s.blockId?`block reference "${s.blockId}"`:`heading "${s.heading??""}"`;throw new Error(`Embedded note ${d} not found in ${u.path}`)}l=c.content}return zb(a)&&(l=await this.processEmbeddedPDFs(l,o,i)),l=await this.processDataviewBlocks(l,u.path),this.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,content:l})}catch(l){Te("Failed to process embedded note",l);let c=l instanceof Error?l.message:"Could not process embedded note";return this.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,error:c})}}parseEmbeddedLinkTarget(e){if(!e)return null;let r=e.indexOf("|"),o=(r>=0?e.slice(0,r):e).trim();if(!o)return{path:null};let i,a,s=o.indexOf("#^");s!==-1&&(i=o.slice(s+2).trim(),o=o.slice(0,s));let u=o.indexOf("#");return u!==-1&&(a=o.slice(u+1).trim(),o=o.slice(0,u)),{path:o.length>0?o:null,heading:a&&a.length>0?a:void 0,blockId:i&&i.length>0?i:void 0}}extractMarkdownSegment(e,r,n){let o=app.metadataCache.getFileCache(e);if(n.blockId){let i=o?.blocks?.[n.blockId],a=i?.position?.start?.offset,s=i?.position?.end?.offset;return a===void 0||s===void 0?{content:"",found:!1}:{content:r.slice(a,s),found:!0}}if(n.heading){let i=o?.headings??[],a=this.normalizeHeadingForMatch(n.heading),s=i.findIndex(d=>this.normalizeHeadingForMatch(d.heading)===a);if(s===-1)return{content:"",found:!1};let u=i[s],l=u.position?.start?.offset??0,c=r.length;for(let d=s+1;d<i.length;d++)if(i[d].level<=u.level){c=i[d].position?.start?.offset??c;break}return{content:r.slice(l,c),found:!0}}return{content:r,found:!0}}normalizeHeadingForMatch(e){return e.trim().toLowerCase().replace(/\s+/g," ")}formatEmbeddedNoteBlock(e){let{title:r,path:n,heading:o,blockId:i,content:a,error:s}=e,u=`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
<${SWe}>
2026-01-05 13:03:55 +08:00
<title>${r}</title>
<path>${n}</path>`;return o&&(u+=`
<heading>${o}</heading>`),i&&(u+=`
<block_id>${i}</block_id>`),s?u+=`
<error>${s}</error>`:u+=`
<content>
${a??""}
</content>`,u+=`
2026-02-24 07:55:02 +08:00
</${SWe}>
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`,u}async processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=Dte)=>{try{if(e.has(d.path)){F(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(!r.supportsExtension(d.extension)){Te(`Unsupported file type: ${d.extension}`);return}if(!zb(s)&&d.extension!=="md"&&d.extension!=="canvas"){Te(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new npe.Notice(YJ.NON_MARKDOWN_FILES_RESTRICTED);return}let p=d.extension==="md"?await this.buildMarkdownContextContent(d,n,r,s):await r.parseFile(d,n),m=await n.adapter.stat(d.path),h=m?new Date(m.ctime).toISOString():"Unknown",y=m?new Date(m.mtime).toISOString():"Unknown";u+=`
2026-01-05 13:03:55 +08:00
<${f}>
2026-02-24 07:55:02 +08:00
<title>${Rc(d.basename)}</title>
2026-01-05 13:03:55 +08:00
<path>${d.path}</path>
<ctime>${h}</ctime>
2026-01-21 08:46:13 +08:00
<mtime>${y}</mtime>
2026-01-05 13:03:55 +08:00
<content>
${p}
</content>
2026-01-21 08:46:13 +08:00
</${f}>`}catch(p){ne(`Error processing file ${d.path}:`,p),u+=`
2026-01-05 13:03:55 +08:00
<${f}_error>
2026-02-24 07:55:02 +08:00
<title>${Rc(d.basename)}</title>
2026-01-05 13:03:55 +08:00
<path>${d.path}</path>
<error>[Error: Could not process file]</error>
2026-02-24 07:55:02 +08:00
</${f}_error>`}},c=new Set;i&&a&&(await l(a,"active_note"),c.add(a.path));for(let d of o)c.has(d.path)||(await l(d),c.add(d.path));return u}async hasEmbeddedPDFs(e){return/!\[\[(.*?\.pdf)\]\]/g.test(e)}async addNoteToContext(e,r,n,o,i,a){if(n.some(l=>l.path===e.path))return;let s=await r.read(e),u=await this.hasEmbeddedPDFs(s);o&&e.path===o.path&&a(!0),i(l=>[...l,Object.assign(e,{wasAddedViaReference:!0,hasEmbeddedPDFs:u})])}processSelectedTextContexts(){let e=tx();if(!e||e.length===0)return"";let r="";for(let n of e)n.sourceType==="web"?r+=`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
<${wWe}>
<title>${Rc(n.title)}</title>
<url>${Rc(n.url)}</url>
2026-01-21 08:46:13 +08:00
<content>
2026-02-24 07:55:02 +08:00
${Rc(n.content)}
2026-01-21 08:46:13 +08:00
</content>
2026-02-24 07:55:02 +08:00
</${wWe}>`:r+=`
2026-01-21 08:46:13 +08:00
2026-02-24 07:55:02 +08:00
<${q_}>
<title>${Rc(n.noteTitle)}</title>
<path>${Rc(n.notePath)}</path>
2026-01-05 13:03:55 +08:00
<start_line>${n.startLine.toString()}</start_line>
<end_line>${n.endLine.toString()}</end_line>
<content>
${n.content}
</content>
2026-02-24 07:55:02 +08:00
</${q_}>`;return r}async processContextWebTabs(e){if(!e||e.length===0)return"";let r=2500,n=8e3,o=15e3,i=2,a=(b,_)=>{let w=[`
2026-01-21 08:46:13 +08:00
<${b}>`,`
2026-02-24 07:55:02 +08:00
<title>${Rc(_.title)}</title>`,`
<url>${Rc(_.url)}</url>`];return _.mode&&w.push(`
<mode>${Rc(_.mode)}</mode>`),_.error?w.push(`
<error>${Rc(_.error)}</error>`):_.content!==void 0&&w.push(`
2026-01-21 08:46:13 +08:00
<content>
2026-02-24 07:55:02 +08:00
${Rc(_.content)}
2026-01-21 08:46:13 +08:00
</content>`),w.push(`
</${b}>`),w.join("")},s=b=>{let _=[`
2026-02-24 07:55:02 +08:00
<${TWe}>`,`
<title>${Rc(b.title)}</title>`,`
<url>${Rc(b.url)}</url>`,`
<video_id>${Rc(b.videoId)}</video_id>`];b.isActive&&_.push(`
2026-01-21 08:46:13 +08:00
<is_active>true</is_active>`),b.channel&&_.push(`
2026-02-24 07:55:02 +08:00
<channel>${Rc(b.channel)}</channel>`),b.uploadDate&&_.push(`
<upload_date>${Rc(b.uploadDate)}</upload_date>`),b.duration&&_.push(`
<duration>${Rc(b.duration)}</duration>`),b.genre&&_.push(`
<genre>${Rc(b.genre)}</genre>`),b.description&&_.push(`
<description>${Rc(b.description)}</description>`),b.error&&_.push(`
<error>${Rc(b.error)}</error>`);let w=b.transcript||"No transcript available for this video";return _.push(`
2026-01-21 08:46:13 +08:00
<content>
2026-02-24 07:55:02 +08:00
${Rc(w)}
2026-01-21 08:46:13 +08:00
</content>`),_.push(`
2026-02-24 07:55:02 +08:00
</${TWe}>`),_.join("")},u=null,l=[],c=new Set,d=new Set,f=_d(app),p=b=>{let _=f.getYouTubeVideoId(b);return _?d.has(_)?!0:(d.add(_),!1):c.has(b)?!0:(c.add(b),!1)};for(let b of e){let _=_b(b.url);_&&b.isActive&&!u&&(u={...b,url:_},p(_))}for(let b of e){let _=_b(b.url);!_||p(_)||l.push({...b,url:_})}if(!u&&l.length===0)return"";let m=f.getAvailability();if(!m.supported||!m.available){let b=m.reason??(m.supported?"Web Viewer is not available.":"Web Viewer is not supported on this platform."),_=[];u&&_.push(a(vye,{title:u.title||"Unknown",url:u.url,error:b}));for(let w of l)_.push(a(xWe,{title:w.title||"Unknown",url:w.url,error:b}));return _.join("")}let h=async(b,_)=>{try{let w=b.url,T=f.getYouTubeVideoId(w);if(T)return await y(b,T,_===vye);let O=f.findLeafByUrl(w,{title:b.title});if(!O)return a(_,{title:b.title||"Unknown",url:w,error:"Web tab not found or closed"});let E=f.getPageInfo(O),P=O.view;if(!(P.webviewMounted===void 0||P.webviewFirstLoadFinished===void 0?!0:!!(P.webviewMounted&&P.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(O,r),E=f.getPageInfo(O)}catch(z){return Te(`Web tab content not loaded yet for ${w}:`,z),a(_,{title:E.title||b.title||"Untitled",url:E.url||w,mode:E.mode,error:"Web tab content not loaded yet"})}let I=new AbortController,N=setTimeout(()=>{I.abort()},n);try{let z=await f.getReaderModeMarkdown(O,{signal:I.signal});return E=f.getPageInfo(O),a(_,{title:E.title||b.title||"Untitled",url:E.url||w,mode:E.mode,content:z})}finally{clearTimeout(N)}}catch(w){return ne(`Error processing web tab ${b.url}:`,w),a(_,{title:b.title||"Unknown",url:b.url,error:w instanceof PB?"Web tab content extraction timed out":"Could not process web tab"})}},y=async(b,_,w)=>{try{let T=null,O=b.url;for(let N of f.getLeaves()){let z=f.getPageInfo(N).url;if(f.getYouTubeVideoId(z)===_){T=N,O=z;break}}if(!T)return s({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:"Web tab not found or closed"});let E=T.view;if(!(E.webviewMounted===void 0||E.webviewFirstLoadFinished===void 0?!0:!!(E.webviewMounted&&E.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(T,r)}catch(N){return Te(`YouTube tab content not loaded yet for ${O}:`,N),s({title:b.title||"YouTube Video",url:O,videoId:_,isActive:w,error:"Web tab content not loaded yet"})}let R=await f.getYouTubeTranscript(T,{timeoutMs:o}),I=R.transcript.length>0?R.transcript.map(N=>`${N.timestamp}: ${N.text}`).join(`
`):void 0;return s({title:R.title||b.title||"YouTube Video",url:O,videoId:R.videoId,channel:R.channel,description:R.description,uploadDate:R.uploadDate,duration:R.duration,genre:R.genre,transcript:I,isActive:w})}catch(T){return Te(`YouTube transcript extraction failed for ${b.url}:`,T),s({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:T instanceof Error?T.message:"Failed to extract video info"})}},g=[];if(u){let b=await h(u,vye);g.push(b)}for(let b=0;b<l.length;b+=i){let _=l.slice(b,b+i),w=await Promise.all(_.map(T=>h(T,xWe)));g.push(...w)}return g.join("")}};Xe();Ye();Bt();var VSt=null;async function Wwi(){return VSt||(VSt=(await Promise.resolve().then(()=>(Won(),Hon))).ContextCompactor),VSt.getInstance()}var eUe=class t{constructor(){this.contextProcessor=Qqe.getInstance(),this.mention=s9.getInstance(),this.promptContextEngine=Yqe.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processMessageContext(e,r,n,o,i,a,s,u,l=[],c){try{F(`[ContextManager] Processing context for message ${e.id}`);let d=e.originalMessage||e.message,{processedPrompt:f,includedFiles:p}=await sde(d,"",n,a),{l2Context:m,l2Paths:h}=this.buildL2ContextFromPreviousTurns(e.id,s),y=e.context?.urls||[],g=o==="copilot_plus"?await this.mention.processUrlList(y):{urlContext:"",imageUrls:[]},b=new Set([...p.map(W=>W.path),...l.map(W=>W.path),...h]),_=new Set,T=(e.context?.notes||[]).filter(W=>!h.has(W.path));i&&o!=="project"&&a&&!b.has(a.path)&&!T.some(W=>W.path===a.path)&&T.push(a);let O=await this.contextProcessor.processContextNotes(b,r,n,T,i,a,o);T.forEach(W=>{b.add(W.path),_.add(W.path)});let E=e.context?.tags||[],P="",R=[];if(E.length>0){let ie=mye(n,E).filter(j=>!b.has(j.path));ie.length>0&&(P=await this.contextProcessor.processContextNotes(new Set,r,n,ie,!1,null,o),ie.forEach(j=>{b.add(j.path),_.add(j.path),R.push(j.path)}))}let I=e.context?.folders||[],N="",z=[];if(I.length>0){let ie=I.flatMap(j=>Ote(n,j)).filter(j=>!b.has(j.path));ie.length>0&&(N=await this.contextProcessor.processContextNotes(new Set,r,n,ie,!1,null,o),ie.forEach(j=>{b.add(j.path),_.add(j.path),z.push(j.path)}))}let V=this.contextProcessor.processSelectedTextContexts(),k=e.context?.webTabs||[],X=await this.contextProcessor.processContextWebTabs(k),B=m+O+P+N+g.urlContext+V+X,Q=f+B,oe=(o==="project"?1e6:te().autoCompactThreshold)*4,ue=!1,de=B;if(Q.length>oe){c?.(dw.COMPACTING);let ie=await(await Wwi()).compact(B);ie.wasCompacted&&(de=ie.content,Q=f+de,ue=!0,F(`[ContextManager] Compacted context: ${ie.originalCharCount} -> ${ie.compactedCharCount} chars`)),c?.(dw.DEFAULT)}F(`[ContextManager] Successfully processed context for message ${e.id}`);let L=ue?this.buildCompactedEnvelope({chainType:o,message:e,systemPrompt:u||"",processedUserMessage:f,compactedContext:de,compactedPaths:Array.from(_)}):this.buildPromptContextEnvelope({chainType:o,message:e,systemPrompt:u||"",processedUserMessage:f,l2PreviousContext:m,noteContextAddition:O,tagContextAddition:P,tagNotePaths:R,folderContextAddition:N,folderNotePaths:z,urlContext:g.urlContext,selectedText:V,webTabContext:X});return{processedContent:Q,contextEnvelope:L}}catch(d){return F(`[ContextManager] Error processing context for message ${e.id}:`,d),{processedContent:e.originalMessage||e.message,contextEnvelope:void 0}}}async reprocessMessageContext(e,r,n,o,i,a,s,u,l=[]){let c=r.getMessage(e);if(!c||c.sender!=="user"||!c.id)return;F(`[ContextManager] Reprocessing context for message ${e}`);let{processedContent:d,contextEnvelope:f}=await this.processMessageContext(c,n,o,i,a,s,r,u,l);r.updateProcessedText(c.id,d,f),F(`[ContextManager] Completed context reprocessing for message ${e}`)}buildL2ContextFromPreviousTurns(e,r){let n=r.getDisplayMessages(),o=n.findIndex(p=>p.id===e);if(o===-1||o===0)return{l2Context:"",l2Paths:new Set};let i=n.slice(0,o).filter(p=>p.sender==="user"),a=new Map,s=[],u=new Set,l=-1;for(let p=i.length-1;p>=0;p--)if(i[p].contextEnvelope?.layers?.find(g=>g.id==="L3_TURN")?.segments?.some(g=>g.metadata?.wasCompacted)){l=p;break}for(let p=0;p<i.length;p++){let h=i[p]
`);return{l2Context:c.includes("<prior_context ")?c+`
2026-01-05 13:03:55 +08:00
2026-02-24 07:55:02 +08:00
`+zon():c,l2Paths:u}}buildPromptContextEnvelope(e){let r=e.message.id;if(!r)return;let n={};if(e.systemPrompt&&(n.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.l2PreviousContext){let i=this.parseContextIntoSegments(e.l2PreviousContext,!0);i.length>0&&(n.L2_PREVIOUS=i)}let o=[];if(e.noteContextAddition){let i=this.parseContextIntoSegments(e.noteContextAddition,!1);o.push(...i)}return this.appendParsedSegments(o,e.tagContextAddition,{source:"tags",notePaths:e.tagNotePaths}),this.appendParsedSegments(o,e.folderContextAddition,{source:"folders",notePaths:e.folderNotePaths}),this.appendParsedSegments(o,e.urlContext),this.appendParsedSegments(o,e.selectedText),this.appendParsedSegments(o,e.webTabContext),o.length>0&&(n.L3_TURN=o),n.L5_USER=[{id:`${r}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:r,layerSegments:n,metadata:{debugLabel:`message:${r}`,chainType:e.chainType}})}buildCompactedEnvelope(e){let r=e.message.id;if(!r)return;let n={};return e.systemPrompt&&(n.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.compactedContext.trim()&&(n.L3_TURN=[{id:"compacted_context",content:e.compactedContext,stable:!1,metadata:{source:"compacted",wasCompacted:!0,compactedPaths:e.compactedPaths}}]),n.L5_USER=[{id:`${r}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:r,layerSegments:n,metadata:{debugLabel:`message:${r}:compacted`,chainType:e.chainType}})}parseContextIntoSegments(e,r){return Von(e,r)}appendParsedSegments(e,r,n){let o=(r||"").trim();if(!o)return;let i=this.parseContextIntoSegments(o,!1);if(i.length>0)for(let a of i)n&&(a.metadata={...a.metadata,...n}),e.push(a);else e.push({id:`unparsed-${Date.now()}`,content:o,stable:!1,metadata:{source:"unparsed",...n}})}createMessageContext(e,r,n=tx()){return{notes:e,urls:r,selectedTextContexts:n}}async extractContextNotes(e,r,n=[]){return[...await kS(e,r),...n].filter((s,u,l)=>l.findIndex(c=>c.path===s.path)===u)}needsContextReprocessing(e){return e.needsContextReprocessing===!0}getSelectedTextContexts(){return tx()}compactSegmentForL2(e){let r=Vce.map(a=>a.tag).join("|"),n=new RegExp(`<(${r})[^>]*>[\\s\\S]*?</\\1>`,"g"),o=e.match(n);if(!o||o.length===0)return e;if(o.length===1){let a=pgt(o[0]);return a?BSt(o[0],a):e}return o.map(a=>{let s=pgt(a);return s?BSt(a,s):a}).join(`
`)}};Bt();Xe();var lQ=class{constructor(){this.messages=[]}generateId(){return`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}addMessage(e,r,n,o,i){if(typeof e=="object"){let c=e,d=c.id||this.generateId(),f=c.timestamp||Mg(new Date),p={id:d,displayText:c.message,processedText:c.originalMessage||c.message,sender:c.sender,timestamp:f,context:c.context,contextEnvelope:c.contextEnvelope,isVisible:c.isVisible!==!1,isErrorMessage:c.isErrorMessage,sources:c.sources,content:c.content,responseMetadata:c.responseMetadata};return this.messages.push(p),F(`[MessageRepository] Added message with ID: ${d}`),d}if(r===void 0||n===void 0)throw new Error("processedText and sender are required when using string-based addMessage");let a=e,s=this.generateId(),u=Mg(new Date),l={id:s,displayText:a,processedText:r,sender:n,timestamp:u,context:o,contextEnvelope:void 0,isVisible:!0,isErrorMessage:!1,content:i};return this.messages.push(l),F(`[MessageRepository] Added message with ID: ${s}`),s}editMessage(e,r){let n=this.messages.find(o=>o.id===e);return n?n.displayText===r?(F(`[MessageRepository] No changes needed for message: ${e}`),!0):(n.displayText=r,n.sender==="user"||n.sender==="USER"?F(`[MessageRepository] Edited user message ${e}, needs context reprocessing`):(n.processedText=r,F(`[MessageRepository] Edited AI message ${e}`)),!0):(F(`[MessageRepository] Message not found for edit: ${e}`),!1)}updateProcessedText(e,r,n){let o=this.messages.find(i=>i.id===e);return o?(o.processedText=r,o.contextEnvelope=n,F(`[MessageRepository] Updated processed text for message ${e}`),!0):(F(`[MessageRepository] Message not found for processed text update: ${e}`),!1)}deleteMessage(e){let r=this.messages.findIndex(n=>n.id===e);return r===-1?(F(`[MessageRepository] Message not found for deletion: ${e}`),!1):(this.messages.splice(r,1),F(`[MessageRepository] Deleted message ${e}`),!0)}clear(){this.messages=[],F("[MessageRepository] Cleared all messages")}truncateAfter(e){this.messages=this.messages.slice(0,e+1),F(`[MessageRepository] Truncated messages after index ${e}`)}truncateAfterMessageId(e){let r=this.messages.findIndex(n=>n.id===e);r!==-1&&(this.messages=this.messages.slice(0,r+1),F(`[MessageRepository] Truncated messages after message ${e}`))}getDisplayMessages(){return this.messages.filter(e=>e.isVisible).map(e=>({id:e.id,message:e.displayText,originalMessage:e.displayText,sender:e.sender,timestamp:e.timestamp,isVisible:!0,context:e.context,contextEnvelope:e.contextEnvelope,isErrorMessage:e.isErrorMessage,sources:e.sources,content:e.content,responseMetadata:e.responseMetadata}))}getLLMMessage(e){let r=this.messages.find(n=>n.id===e);if(r)return{id:r.id,message:r.processedText,originalMessage:r.displayText,sender:r.sender,timestamp:r.timestamp,isVisible:!1,context:r.context,contextEnvelope:r.contextEnvelope,isErrorMessage:r.isErrorMessage,sources:r.sources,content:r.content,responseMetadata:r.responseMetadata}}getLLMMessages(){return this.messages.map(e=>({id:e.id,message:e.displayText,originalMessage:e.displayText,sender:e.sender,timestamp:e.timestamp,isVisible:!1,context:e.context,contextEnvelope:e.contextEnvelope,isErrorMessage:e.isErrorMessage,sources:e.sources,content:e.content}))}getMessage(e){let r=this.messages.find(n=>n.id===e);if(r)return{id:r.id,message:r.displayText,originalMessage:r.displayText,sender:r.sender,timestamp:r.timestamp,isVisible:r.isVisible,context:r.context,contextEnvelope:r.contextEnvelope,isErrorMessage:r.isErrorMessage,sources:r.sources,content:r.content}}loadMessages(e){this.clear(),e.forEach(r=>{this.messages.push({id:r.id||this.generateId(),displayText:r.message,processedText:r.originalMessage||r.message,sender:r.sender,timestamp:r.timestamp||Mg(new Date),context:r.context,contextEnvelope:r.contextEnvelope,isVisible:r.isVisible!==!1,isErrorMessage:r.isErrorMessage,sources:r.sources,content:r.content})}),F(`[MessageRepository] Loaded ${e.length} messages`)}getDebugInfo(){return{totalMessages:this.messages.length,visibleMessages:this.messages.filter(e=>e.isVisible).length,userMessages:this.messages.filter(e=>
`}return l+u});i!==o&&await t.vault.adapter.write(e,i)}async function JSt(t,e){let n=(await t.vault.adapter.read(e)).match(/^---\n([\s\S]*?)\n---/)?.[1];if(!n)return null;let o={};for(let i of n.split(`
`)){let a=i.match(/^(\w+):\s*(.+)/);a&&(o[a[1]]=a[2].trim().replace(/^["']|["']$/g,""))}return o}async function Kon(t,e){let r=await t.vault.adapter.stat(e),n=e.split("/").pop()??"";return{path:e,name:n,basename:n.replace(/\.md$/,""),extension:"md",stat:r??{ctime:Date.now(),mtime:Date.now(),size:0},vault:t.vault,parent:null}}var C_=require("obsidian"),KSt=100;function Jwi(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var ipe=class{constructor(e,r,n){this.app=e;this.messageRepo=r;this.chainManager=n}async saveChat(e){try{let r=this.messageRepo.getDisplayMessages();if(r.length===0){new C_.Notice("No messages to save.");return}let n=te(),o=this.formatChatContent(r),i=r[0].timestamp?.epoch||Date.now();await $c(n.defaultSaveFolder);let a=await this.findFileByEpoch(i),s=a?this.app.metadataCache.getFileCache(a)?.frontmatter:void 0,u=s?.topic,l=s?.lastAccessedAt;if(a&&!s)try{let m=await JSt(this.app,a.path);m&&(m.topic&&(u=m.topic),m.lastAccessedAt&&(l=Number(m.lastAccessedAt)))}catch{}let c=a?a.path:this.generateFileName(r,i,u),d=this.generateNoteContent(o,i,e,u,l),f=a,p=a!=null&&WSt(this.app,a.path);if(a&&p)await this.app.vault.modify(a,d),F(`[ChatPersistenceManager] Updated existing chat file: ${a.path}`);else if(!WSt(this.app,c)&&await this.app.vault.adapter.exists(c))await this.app.vault.adapter.write(c,d),new C_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Updated existing chat file via adapter: ${c}`);else try{f=await this.app.vault.create(c,d),new C_.Notice(`Chat saved as note: ${c}`),F(`[ChatPersistenceManager] Created new chat file: ${c}`)}catch(m){if(this.isFileAlreadyExistsError(m)){let h=this.app.vault.getAbstractFileByPath(c);if(h&&h instanceof C_.TFile){let y=this.app.metadataCache.getFileCache(h)?.frontmatter;u=y?.topic??u;let g=y?.lastAccessedAt,b=this.generateNoteContent(o,i,e,u,g);await this.app.vault.modify(h,b),f=h,new C_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved save conflict by updating existing chat file: ${h.path}`)}else await this.app.vault.adapter.write(c,d),new C_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved save conflict via adapter: ${c}`)}else if(this.isNameTooLongError(m)){let h=Gu(),y=h?`${h.id}__`:"",g=`${n.defaultSaveFolder}/${y}chat-${i}.md`;try{f=await this.app.vault.create(g,d),new C_.Notice(`Chat saved as note: ${g}`),Te(`[ChatPersistenceManager] Used minimal filename due to length constraints: ${g}`)}catch(b){if(this.isFileAlreadyExistsError(b)){let _=this.app.vault.getAbstractFileByPath(g);if(_&&_ instanceof C_.TFile){let w=this.app.metadataCache.getFileCache(_)?.frontmatter,T=w?.lastAccessedAt,O=w?.topic,E=this.generateNoteContent(o,i,e,O,T);await this.app.vault.modify(_,E),f=_,new C_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved fallback save conflict by updating existing chat file: ${_.path}`)}else await this.app.vault.adapter.write(g,d),new C_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved fallback save conflict via adapter: ${g}`)}else throw b}}else throw m}this.generateTopicAsyncIfNeeded(r,f,u)}catch(r){ne("[ChatPersistenceManager] Error saving chat:",r),new C_.Notice("Failed to save chat as note. Check console for details.")}}async loadChat(e){try{let r;try{r=await this.app.vault.read(e)}catch{r=await this.app.vault.adapter.read(e.path)}let n=this.parseChatContent(r);return F(`[ChatPersistenceManager] Loaded ${n.length} messages from ${e.path}`),n}catch(r){return ne("[ChatPersistenceManager] Error loading chat:",r),new C_.Notice("Failed to load chat history. Check console for details."),[]}}async getChatHistoryFiles(){let e=te(),r=await tUe(this.app,e.defaultSaveFolder);if(r.length===0)return[];let n=Gu();return r.filter(o=>n?o.basename.startsWith(`${n.id}__`):!o.basename.includes("__")||!o.basename.split("__")[0])}formatChatContent(e){return e.map(r=>{let n=r.timestamp?r.timestamp.display:"Unknown time",o=r.message;if(r.sender===cw){let a=Bce(o);a&&(o=a.c
[Context: ${a.join(" | ")}]`)}return i+=`
[Timestamp: ${n}]`,i}).join(`
`)}parseChatContent(e){let r=[],n=e.match(/^---\n([\s\S]*?)\n---/),o=e;n&&(o=e.slice(n[0].length).trim());let i=/\*\*(user|ai)\*\*: ([\s\S]*?)(?=(?:\n\*\*(?:user|ai)\*\*: )|$)/g,a;for(;(a=i.exec(o))!==null;){let s=a[1]==="user"?Zs:cw,u=a[2].trim(),l=u.split(`
`),c=u,d="Unknown time",f,p=l.length;if(l[p-1]?.startsWith("[Timestamp: ")){let h=l[p-1].match(/\[Timestamp: (.*?)\]/);h&&(d=h[1],p--)}if(p>0&&l[p-1]?.startsWith("[Context: ")){let h=l[p-1].match(/\[Context: (.*?)\]/);if(h){let y=h[1];f=this.parseContextString(y),p--}}if(c=l.slice(0,p).join(`
`).trim(),s===cw){c=c.replace(/<!--TOOL_CALL_START:[^:]+:[^:]+:[^:]+:[^:]+:[^:]*:[^:]+-->[\s\S]*?<!--TOOL_CALL_END:[^:]+:[\s\S]*?-->/g,"");let h=Bce(c);h&&(c=h.contentAfter),c=c.replace(/\n{3,}/g,`
`).trim()}let m;if(d!=="Unknown time"){let h=new Date(d);isNaN(h.getTime())||(m=h.getTime())}r.push({message:c,sender:s,isVisible:!0,timestamp:m?{epoch:m,display:d,fileName:""}:null,context:f})}return r}parseContextString(e){let r={notes:[],urls:[],tags:[],folders:[],webTabs:[]},n=e.split(" | ");for(let o of n){let i=o.trim();if(i.startsWith("Notes: ")){let a=i.substring(7);a&&(r.notes=a.split(", ").map(s=>{let u=s.trim(),l=this.app.vault.getAbstractFileByPath(u);if(l instanceof C_.TFile)return l;let c=u.includes("/")?u.split("/").pop():u,d=this.app.vault.getMarkdownFiles().filter(f=>f.basename===c);return d.length===1?(F(`[ChatPersistenceManager] Resolved legacy basename "${c}" to ${d[0].path}`),d[0]):(d.length>1?Te(`[ChatPersistenceManager] Ambiguous basename "${c}", skipping. Matches: ${d.map(f=>f.path).join(", ")}`):Te(`[ChatPersistenceManager] Note not found: ${u}`),null)}).filter(s=>s!==null))}else if(i.startsWith("URLs: ")){let a=i.substring(6);a&&(r.urls=a.split(", ").map(s=>s.trim()))}else if(i.startsWith("Web Tabs: ")||i.startsWith("WebTabs: ")){let a=i.startsWith("Web Tabs: ")?i.substring(10):i.substring(9);a&&(r.webTabs=a.split(", ").map(s=>s.trim()).filter(s=>s.length>0).map(s=>({url:s})))}else if(i.startsWith("Tags: ")){let a=i.substring(6);a&&(r.tags=a.split(", ").map(s=>s.trim()))}else if(i.startsWith("Folders: ")){let a=i.substring(9);a&&(r.folders=a.split(", ").map(s=>s.trim()))}}if(r.notes.length>0||r.urls.length>0||r.tags.length>0||r.folders.length>0||r.webTabs.length>0)return r}async findFileByEpoch(e){let r=await this.getChatHistoryFiles();for(let n of r){let o=this.app.metadataCache.getFileCache(n)?.frontmatter?.epoch;if(o===void 0)try{let a=await JSt(this.app,n.path);a?.epoch&&(o=Number(a.epoch))}catch{continue}let i=typeof o=="number"?o:typeof o=="string"?Number(o):void 0;if(typeof i=="number"&&!Number.isNaN(i)&&i===e)return n}return null}async generateAITopic(e){if(this.chainManager)try{let r=this.chainManager.chatModelManager.getChatModel();if(!r)return;let n=6,o=200,a=`Generate a concise title (max 5 words) for this conversation based on its content. Return only the title without any explanation or quotes.
2026-01-05 13:03:55 +08:00
Conversation:
${e.reduce((c,d,f)=>f>=n?c:c+(c?`
2026-02-24 07:55:02 +08:00
`:"")+`${d.sender}: ${d.message.slice(0,o)}`,"")}`,s=await r.invoke(a),u=typeof s=="string"?s:s.content??s.text??s;return M4(u).trim().replace(/^["']|["']$/g,"").replace(/[\\/:*?"<>|]/g,"").slice(0,50)||void 0}catch(r){ne("[ChatPersistenceManager] Error generating AI topic:",r);return}}generateFileName(e,r,n){let o=te(),a=Mg(new Date(r)).fileName,s;if(n)s=n;else{let w=e.find(T=>T.sender===Zs);s=w&&w.message.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"").split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|\x00-\x1F]/g,"").trim()||"Untitled Chat"}let u=o.defaultConversationNoteName||"{$date}_{$time}__{$topic}",l=Gu(),c=l?`${l.id}__`:"",d=P4(".md"),f=P4(c),p=u.replace("{$topic}","").replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]),m=P4(p),h=Math.max(20,KSt-d-f-m),y=s.replace(/\s+/g,"_"),g=Tte(y,h);u=u.replace("{$topic}",g).replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]);let b=u.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"_").replace(/[\\/:*?"<>|\x00-\x1F]/g,"_"),_=`${c}${b}.md`;if(P4(_)>KSt){let w=KSt-d-f,T=Tte(b,w);return`${o.defaultSaveFolder}/${c}${T}.md`}return`${o.defaultSaveFolder}/${_}`}generateNoteContent(e,r,n,o,i){let a=te(),s=Gu();return`---
2026-01-05 13:03:55 +08:00
epoch: ${r}
2026-02-24 07:55:02 +08:00
modelKey: "${Jwi(n)}"
2026-01-05 13:03:55 +08:00
${o?`topic: "${o}"`:""}
2026-01-21 08:46:13 +08:00
${i?`lastAccessedAt: ${i}`:""}
${s?`projectId: ${s.id}`:""}
${s?`projectName: ${s.name}`:""}
2026-01-05 13:03:55 +08:00
tags:
2026-01-21 08:46:13 +08:00
- ${a.defaultConversationTag}
2026-01-05 13:03:55 +08:00
---
2026-02-24 07:55:02 +08:00
${e}`}generateTopicAsyncIfNeeded(e,r,n){!te().generateAIChatTitleOnSave||!r||n||(async()=>{try{let i=await this.generateAITopic(e);if(!i)return;await this.applyTopicToFrontmatter(r,i)}catch(i){ne("[ChatPersistenceManager] Error during async topic generation:",i)}})()}async applyTopicToFrontmatter(e,r){try{await ope(this.app,e.path,{topic:r.trim()}),F(`[ChatPersistenceManager] Applied AI topic to chat file: ${e.path}`)}catch(n){ne("[ChatPersistenceManager] Error applying AI topic to file:",n)}}isNameTooLongError(e){if(!e)return!1;let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("enametoolong")||n.includes("name too long")}isFileAlreadyExistsError(e){return e?(e instanceof Error?e.message:String(e)).toLowerCase().includes("already exists"):!1}};mr();jW();qZ();var rUe=class{constructor(e,r,n,o){this.messageRepo=e;this.chainManager=r;this.fileParserManager=n;this.plugin=o;this.projectMessageRepos=new Map;this.defaultProjectKey="defaultProjectKey";this.lastKnownProjectId=null;this.contextManager=eUe.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=new ipe(o.app,e,r)}getCurrentMessageRepo(){let e=this.plugin.projectManager.getCurrentProjectId(),r=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(F(`[ChatManager] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(r)){F(`[ChatManager] Creating new message repository for project: ${r}`);let o=new lQ;this.projectMessageRepos.set(r,o)}let n=this.projectMessageRepos.get(r);return this.persistenceManager=new ipe(this.plugin.app,n,this.chainManager),n}setOnMessageCreatedCallback(e){this.onMessageCreatedCallback=e}async processSystemPromptTemplates(e,r,n){if(!e.includes("{")||!e.includes("}"))return{processedPrompt:e,includedFiles:[]};if(!te().enableCustomPromptTemplating)return{processedPrompt:e,includedFiles:[]};try{let i=await sde(e,"",r,n,!0);return{processedPrompt:i.processedPrompt.trimEnd(),includedFiles:i.includedFiles}}catch(i){return Te("[ChatManager] Error processing system prompt templates:",i),{processedPrompt:e,includedFiles:[]}}}injectProcessedUserCustomPromptIntoSystemPrompt(e){let{systemPromptWithoutMemory:r,userCustomPrompt:n,processedUserCustomPrompt:o}=e,i=/<user_custom_instructions>\n[\s\S]*?\n<\/user_custom_instructions>/;return i.test(r)?r.replace(i,()=>`<user_custom_instructions>
2026-01-21 08:46:13 +08:00
${o}
2026-02-24 07:55:02 +08:00
</user_custom_instructions>`):r===n?o:(F("[ChatManager] Could not locate <user_custom_instructions> block for injection; returning original system prompt."),r)}replaceSystemPromptWithoutMemoryInBasePrompt(e){let{basePromptWithMemory:r,systemPromptWithoutMemory:n,processedSystemPromptWithoutMemory:o}=e;return r.endsWith(n)?`${r.slice(0,r.length-n.length)}${o}`:(F("[ChatManager] basePromptWithMemory does not end with systemPromptWithoutMemory; returning original base prompt."),r)}async getSystemPromptForMessage(e,r,n){let o=ije(),i=[],a=await T$(this.chainManager.userMemoryManager),s=x$(),u=a;if(o){let l=await this.processSystemPromptTemplates(o,r,n),c=this.injectProcessedUserCustomPromptIntoSystemPrompt({systemPromptWithoutMemory:s,userCustomPrompt:o,processedUserCustomPrompt:l.processedPrompt}),d=this.replaceSystemPromptWithoutMemoryInBasePrompt({basePromptWithMemory:a,systemPromptWithoutMemory:s,processedSystemPromptWithoutMemory:c});d!==a&&i.push(...l.includedFiles),u=d}if(e==="project"){let l=Gu();if(l){let c=await ry.instance.getProjectContext(l.id),d=await this.processSystemPromptTemplates(l.systemPrompt,r,n);i.push(...d.includedFiles);let f=`${u}
2026-01-05 13:03:55 +08:00
<project_system_prompt>
2026-01-21 08:46:13 +08:00
${d.processedPrompt}
2026-02-24 07:55:02 +08:00
</project_system_prompt>`;if(c){let m=c;c.length>24e5&&(m=c.substring(0,24e5),Te(`Project context truncated from ${Math.round(c.length/4e3)}k to ${Math.round(24e5/4e3)}k estimated tokens to stay within token budget`)),f+=`
2026-01-05 13:03:55 +08:00
<project_context>
2026-02-24 07:55:02 +08:00
${m}
</project_context>`}return{processedPrompt:f,includedFiles:i}}}return{processedPrompt:u,includedFiles:i}}buildWebTabsWithActiveSnapshot(e,r){let n=MGr(e);if(!r)return n;try{let a=_d(this.plugin.app).getActiveWebTabState().activeWebTabForMentions,s=kZ(a?.url);if(!s)return n;let u=n.map(c=>{if(c.isActive){let{isActive:d,...f}=c;return f}return c}),l=u.findIndex(c=>kZ(c.url)===s);if(l>=0){let c=u[l];return u[l]={...c,url:_b(a?.url)??c.url,title:a?.title??c.title,faviconUrl:a?.faviconUrl??c.faviconUrl,isActive:!0},u}return[...u,{url:_b(a?.url)??s,title:a?.title,faviconUrl:a?.faviconUrl,isActive:!0}]}catch(o){return Te("[ChatManager] Failed to resolve active web tab:",o),n}}async sendMessage(e,r,n,o=!1,i=!1,a,s){try{F(`[ChatManager] Sending message: "${e}"`);let u=this.plugin.app.workspace.getActiveFile(),l={...r};if(o&&u){let _=r.notes||[],w=_.some(T=>T.path===u.path);l.notes=w?_:[..._,u]}let d=!((l.selectedTextContexts||[]).length>0)&&(i||e.includes(Fte));l.webTabs=this.buildWebTabsWithActiveSnapshot(l.webTabs||[],d);let f=this.getCurrentMessageRepo(),p=f.addMessage(e,e,Zs,l,a);this.onMessageCreatedCallback&&this.onMessageCreatedCallback(p);let m=f.getMessage(p);if(!m)throw new Error(`Failed to retrieve message ${p}`);let{processedPrompt:h,includedFiles:y}=await this.getSystemPromptForMessage(n,this.plugin.app.vault,u),{processedContent:g,contextEnvelope:b}=await this.contextManager.processMessageContext(m,this.fileParserManager,this.plugin.app.vault,n,o,u,f,h,y,s);return f.updateProcessedText(p,g,b),F(`[ChatManager] Successfully sent message ${p}`),p}catch(u){throw F("[ChatManager] Error sending message:",u),u}}async editMessage(e,r,n,o=!1){try{F(`[ChatManager] Editing message ${e}: "${r}"`);let i=this.getCurrentMessageRepo();if(!i.editMessage(e,r))return!1;let s=this.plugin.app.workspace.getActiveFile(),{processedPrompt:u,includedFiles:l}=await this.getSystemPromptForMessage(n,this.plugin.app.vault,s);return await this.contextManager.reprocessMessageContext(e,i,this.fileParserManager,this.plugin.app.vault,n,o,s,u,l),await this.updateChainMemory(),F(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return F(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,r,n,o){try{F(`[ChatManager] Regenerating message ${e}`);let i=this.getCurrentMessageRepo();if(!i.getMessage(e))return F(`[ChatManager] Message not found: ${e}`),!1;let s=i.getDisplayMessages(),u=s.findIndex(f=>f.id===e);if(u<=0)return F("[ChatManager] Cannot regenerate first message or no user message found"),!1;let l=s[u-1];if(l.sender!==Zs)return F("[ChatManager] Previous message is not from user"),!1;if(i.truncateAfter(u-1),o&&o(),await this.updateChainMemory(),!l.id)return F("[ChatManager] User message has no ID for regeneration"),!1;let c=i.getLLMMessage(l.id);if(!c)return F("[ChatManager] LLM message not found for regeneration"),!1;if(!c.contextEnvelope){F("[ChatManager] Context envelope missing, reprocessing context for regeneration");let f=ex(),p=this.plugin.app.workspace.getActiveFile(),{processedPrompt:m,includedFiles:h}=await this.getSystemPromptForMessage(f,this.plugin.app.vault,p);await this.contextManager.reprocessMessageContext(l.id,i,this.fileParserManager,this.plugin.app.vault,f,!1,p,m,h),c=i.getLLMMessage(l.id)}let d=new AbortController;return await this.chainManager.runChain(c,d,r,n,{debug:te().debug}),F(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return F(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return F(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(await this.updateChainMemory(),F(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(r){return F(`[ChatManager] Error deleting message ${e}:`,r),!1}}addMessage(e){return this.getCurrentMessageRepo().addMessage(e)}clearMessages(){this.getCurrentMessageRepo().clear(),this.chainManager.memoryManager.clearChatMemory(),F("[ChatManager] Cleared all messages")}async truncateAfterMessageId(e){this.getCurrentMessageRepo().truncateAfterMessageId(e),await this.up
2026-01-05 13:03:55 +08:00
To pick up a draggable item, press the space bar.
While dragging, use the arrow keys to move the item.
Press space again to drop the item in its new position, or press escape to cancel.
2026-02-24 07:55:02 +08:00
`},eSi={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:r}=t;return r?"Draggable item "+e.id+" was moved over droppable area "+r.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:r}=t;return r?"Draggable item "+e.id+" was dropped over droppable area "+r.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function tSi(t){let{announcements:e=eSi,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=Qwi}=t,{announce:i,announcement:a}=ain(),s=E6("DndLiveRegion"),[u,l]=(0,Ge.useState)(!1);if((0,Ge.useEffect)(()=>{l(!0)},[]),Zwi((0,Ge.useMemo)(()=>({onDragStart(d){let{active:f}=d;i(e.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;e.onDragMove&&i(e.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;i(e.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;i(e.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;i(e.onDragCancel({active:f,over:p}))}}),[i,e])),!u)return null;let c=Ge.default.createElement(Ge.default.Fragment,null,Ge.default.createElement(oin,{id:n,value:o.draggable}),Ge.default.createElement(iin,{id:s,announcement:a}));return r?(0,I6.createPortal)(c,r):c}var xh;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(xh||(xh={}));function dUe(){}function pQ(t,e){return(0,Ge.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function pUe(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,Ge.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var VT=Object.freeze({x:0,y:0});function vin(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function win(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function rSi(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function sin(t){let{left:e,top:r,height:n,width:o}=t;return[{x:e,y:r},{x:e+o,y:r},{x:e,y:r+n},{x:e+o,y:r+n}]}function i0t(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function uin(t,e,r){return e===void 0&&(e=t.left),r===void 0&&(r=t.top),{x:e+t.width*.5,y:r+t.height*.5}}var mQ=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=uin(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=vin(uin(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(win)},Sin=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=sin(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=sin(u),c=o.reduce((f,p,m)=>f+vin(l[m],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(win)};function nSi(t,e){let r=Math.max(e.top,t.top),n=Math.max(e.left,t.left),o=Math.min(e.left+e.width,t.left+t.width),i=Math.min(e.top+e.height,t.top+t.height),a=o-n,s=i-r;if(n<o&&r<i){let u=e.width*e.height,l=t.width*t.height,c=a*s,d=c/(u+l-c);return Number(d.toFixed(4))}return 0}var oSi=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=[];for(let i of n){let{id:a}=i,s=r.get(a);if(s){let u=nSi(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(rSi)};function iSi(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function Cin(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:VT}function aSi(t){return function(r){for(var n=arguments.length,o=new Array(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];return o.reduce((a,s)=>({...a,top:a.top+t*s.y,bottom:a.bottom+t*s.y,left:a.left+t*s.x,right:a.right+t*s.x}),{...r})}}var sSi=aSi(1);function uSi(t){if(t.startsWith("matrix3d(")){let e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){let e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}funct
2026-01-05 13:03:55 +08:00
If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
2026-02-24 07:55:02 +08:00
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return ul.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},U0i="DialogDescriptionWarning",B0i=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${pan(U0i).contentName}}.`;return ul.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},man=Qin,han=tan,gan=nan,f0t=oan,p0t=ian,m0t=san,h0t=lan,yan=dan;Or();$r();var MUe=man,ban=han,V0i=gan;var _an=Sy.forwardRef(({className:t,...e},r)=>Sy.createElement(f0t,{ref:r,className:we("tw-fixed tw-inset-0 tw-z-modal data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0","tw-bg-overlay/50",t),...e}));_an.displayName=f0t.displayName;var _pe=Sy.forwardRef(({className:t,children:e,container:r,...n},o)=>Sy.createElement(V0i,{container:r},Sy.createElement(_an,null),Sy.createElement(p0t,{ref:o,className:we("tw-fixed tw-left-1/2 tw-top-1/2 tw-z-modal tw-grid tw-w-full tw-max-w-lg -tw-translate-x-1/2 -tw-translate-y-1/2 tw-gap-4 tw-border tw-bg-primary tw-p-6 tw-shadow-lg tw-duration-200 data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[state=closed]:tw-slide-out-to-left-1/2 data-[state=closed]:tw-slide-out-to-top-[48%] data-[state=open]:tw-slide-in-from-left-1/2 data-[state=open]:tw-slide-in-from-top-[48%] sm:tw-rounded-lg",t),...n},e,Sy.createElement(yan,{className:"clickable-icon tw-absolute tw-right-4 tw-top-4 tw-border-none tw-bg-transparent tw-text-faint tw-outline-none hover:tw-bg-transparent hover:tw-bg-opacity-100 hover:tw-text-normal focus-visible:tw-text-normal focus-visible:tw-outline-none focus-visible:tw-ring-0"},Sy.createElement(qo,{className:"tw-size-4"}),Sy.createElement("span",{className:"tw-sr-only"},"Close")))));_pe.displayName=p0t.displayName;var vpe=({className:t,...e})=>Sy.createElement("div",{className:we("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});vpe.displayName="DialogHeader";var H0i=({className:t,...e})=>Sy.createElement("div",{className:we("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});H0i.displayName="DialogFooter";var wpe=Sy.forwardRef(({className:t,...e},r)=>Sy.createElement(m0t,{ref:r,className:we("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));wpe.displayName=m0t.displayName;var Spe=Sy.forwardRef(({className:t,...e},r)=>Sy.createElement(h0t,{ref:r,className:we("tw-text-sm tw-text-muted",t),...e}));Spe.displayName=h0t.displayName;Bt();function qr(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=_z(),a="onChange"in t?t.onChange:void 0,s=(0,Nl.useMemo)(()=>{if(a)return yye(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return Nl.default.createElement(ri,{type:t.type,defaultValue:t.value,onChange:l=>{s?.(l.target.value)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"password":return Nl.default.createElement(AN,{value:t.value!==void 0?String(t.value):void 0,onChange:l=>{s?.(l)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"textarea":return Nl.default.createElement(h_,{defaultValue:t.value,onChange:l=>{s?.(l.target.value)},placeholder:t.placeholder,rows:t.rows||3,disabled:o,className:"tw-min-h-[80px] tw-w-full sm:tw-w-[300px]"});case"switch":return Nl.default.createElement(dT,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return Nl.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},Nl.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:we("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-s
detail: `+f)}return d}finally{clearTimeout(c)}},i;try{i=await o(!1)}catch(u){Te("First fetch attempt failed, trying with safeFetch...");try{i=await o(!0)}catch(l){let c=`
without CORS Error: `+zr(u)+`
with CORS Error: `+zr(l);throw new Error(c)}}let a=await i.json();return{success:!0,models:g0t(t,a)}}catch(e){return ne(`Error fetching models for ${t}:`,e),{success:!1,models:[],error:zr(e)}}}async function Oan(t,e,r){let n=r?.skipVerification??!1,i=!!e.find(c=>c.name===t.name&&c.provider===t.provider),a=t.provider==="github-copilot"?void 0:Bb(t.provider),s={name:t.name,provider:t.provider,apiKey:a,enabled:!0},u=!1,l;if(!n)try{await ry.instance.getCurrentChainManager().chatModelManager.ping(s)}catch(c){u=!0,l=zr(c),ne("Model verification failed:",c)}return{success:!0,alreadyExists:i,verificationFailed:u,verificationError:l}}function Ean(t){return{name:t.name,provider:t.provider,enabled:!0}}Bt();Or();var AL=require("obsidian"),Hu=$(J());function AUe({provider:t,isReady:e,expanded:r=!1,skipVerification:n=!1,credentialVersion:o}){let i=Br(),[a,s]=(0,Hu.useState)(null),[u,l]=(0,Hu.useState)(!1),[c,d]=(0,Hu.useState)(null),[f,p]=(0,Hu.useState)(null),[m,h]=(0,Hu.useState)(!1),y=(0,Hu.useRef)(!1),g=(0,Hu.useCallback)(async()=>{if(!(y.current||!e)){y.current=!0,l(!0),d(null);try{let w=await Tan(t);w.success?s(w.models):(d(w.error||"Failed to load models"),new AL.Notice(`Failed to load models for ${Rg(t)}: ${w.error}`,5e3))}catch(w){let T=zr(w);d(T),new AL.Notice(`Failed to load models for ${Rg(t)}: ${T}`,5e3)}finally{l(!1),y.current=!1}}},[t,e]);(0,Hu.useEffect)(()=>{s(null),p(null),d(null)},[t,o]),(0,Hu.useEffect)(()=>{r&&e&&a===null&&!u&&!c&&g()},[r,e,a,u,c,g]);let b=async()=>{if(!f){new AL.Notice("Please select a model first");return}h(!0);try{let w=await Oan({id:f.id,name:f.name,provider:t},i.activeModels,{skipVerification:n});if(w.alreadyExists)w.verificationFailed?new AL.Notice(`Model ${f.name} already exists (verification failed: ${w.verificationError})`,1e4):new AL.Notice(`Model ${f.name} verified successfully! It already exists in your models list.`);else{let T=Ean({id:f.id,name:f.name,provider:t}),O=[...i.activeModels,T];Re("activeModels",O),w.verificationFailed?new AL.Notice(`Model ${f.name} added (verification failed: ${w.verificationError})`,1e4):new AL.Notice(`Model ${f.name} verified and added to your models list!`)}}catch(w){ne("Error adding model:",w),new AL.Notice(`Failed to add model: ${zr(w)}`)}finally{h(!1)}},_=a?.filter((w,T,O)=>O.findIndex(E=>E.id===w.id)===T).sort((w,T)=>w.name.localeCompare(T.name));return Hu.default.createElement(Vo,{label:"Model",description:"Add the selected model to your models list. After adding, check the Model Tab."},Hu.default.createElement("div",null,Hu.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Hu.default.createElement("div",{className:"tw-flex-1"},Hu.default.createElement(_N,{options:_?.map(w=>({label:w.name,value:w.id}))||[],onChange:w=>{let T=w.target.value,O=a?.find(E=>E.id===T);O&&p(O)},onClick:()=>{a===null&&!u&&g()},value:f?.id||"",placeholder:"Select Model",disabled:!e||u})),Hu.default.createElement("div",{className:"tw-w-[72px]"},Hu.default.createElement(pe,{onClick:b,disabled:!f||m,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},m?Hu.default.createElement(Bs,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Add"))),Hu.default.createElement("div",{className:"tw-mt-1 tw-text-xs"},u&&Hu.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Loading models..."),c&&Hu.default.createElement("div",{className:"tw-p-1 tw-text-error"},"Failed to load models. ",c),a&&a.length===0&&Hu.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"No models available."),a===null&&!u&&!c&&Hu.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Click to load available models."))))}Or();var L6=require("obsidian"),vr=$(J());function Pan(){let t=Br(),[e]=(0,vr.useState)(()=>BU.getInstance()),[r,n]=(0,vr.useState)("idle"),[o,i]=(0,vr.useState)(null),[a,s]=(0,vr.useState)(0),[u,l]=(0,vr.useState)(null),[c,d]=(0,vr.useState)(!1),f=(0,vr.useRef)(0),p=(0,vr.useRef)(!0);(0,vr.useEffect)(()=>(p.current=!0,()=>{p.current=!1,f.current+=1,e.abortPolling()}),[e]),(0,vr.useEffect)(()=>{e.getAuthState().status==="auth
`)}async function pCi(t,e){let r=[],n=t.provider?.trim()??"",o=jUe(n),i=t.baseUrl?.trim()??"",a=xz(i||o||"https://api.example.com/v1"),s=cCi(a),u=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let l=await CQ(t.apiKey);r.push(...l.warnings);let c={"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${l.apiKey}`};return t.openAIOrgId?.trim()&&(c["OpenAI-Organization"]=t.openAIOrgId.trim()),n==="openrouterai"&&(c["HTTP-Referer"]="https://obsidiancopilot.com",c["X-Title"]="Obsidian Copilot"),e?{ok:!0,warnings:r,spec:{method:"POST",url:`${s}/embeddings`,headers:c,body:{model:u,input:DUe}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${s}/chat/completions`,headers:c,body:{model:u,messages:[{role:"user",content:SQ}],stream:!1,max_tokens:Lan}}}}function mCi(t,e,r,n){let o=[],i=t.azureOpenAIApiInstanceName?.trim()||"[instance]";t.azureOpenAIApiInstanceName?.trim()||o.push("Azure instance name is empty; using placeholder.");let a=t.baseUrl?.trim();if(a){let s=lCi(a);if(s){let u=xz(s.pathname||"");u.includes("/openai/deployments/")&&(u=u.split("/openai/deployments/")[0]);let l=`${s.origin}${u}`;return{warnings:o,url:`${l}/openai/deployments/${encodeURIComponent(e)}/${r}?api-version=${encodeURIComponent(n)}`}}}return{warnings:o,url:`https://${i}.openai.azure.com/openai/deployments/${encodeURIComponent(e)}/${r}?api-version=${encodeURIComponent(n)}`}}async function hCi(t,e){let r=[],n=await CQ(t.apiKey);r.push(...n.warnings);let o=e?t.azureOpenAIApiEmbeddingDeploymentName?.trim()||"[deployment]":t.azureOpenAIApiDeploymentName?.trim()||"[deployment]";(!o||o==="[deployment]")&&r.push("Azure deployment name is empty; using placeholder.");let i=t.azureOpenAIApiVersion?.trim()||"[api-version]";t.azureOpenAIApiVersion?.trim()||r.push("Azure api-version is empty; using placeholder.");let s=mCi(t,o,e?"embeddings":"chat/completions",i);r.push(...s.warnings);let u=e?{input:DUe}:{messages:[{role:"user",content:SQ}],stream:!1,max_tokens:Lan};return{ok:!0,warnings:r,spec:{method:"POST",url:s.url,headers:{"Content-Type":"application/json",Accept:"application/json","api-key":n.apiKey},body:u}}}async function gCi(t){let e=[],r=t.baseUrl?.trim()??"",n=jUe("anthropic"),o=xz(r||n||"https://api.anthropic.com"),i=["/v1/messages","/v1"];for(let l of i)if(o.endsWith(l)){o=o.slice(0,-l.length);break}let a=`${o}/v1/messages`,s=await CQ(t.apiKey);e.push(...s.warnings);let u=t.name?.trim()||"<MODEL_NAME>";return t.name?.trim()||e.push("Model name is empty; using placeholder."),{ok:!0,warnings:e,spec:{method:"POST",url:a,headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":s.apiKey,"anthropic-version":nCi},body:{model:u,max_tokens:iCi,messages:[{role:"user",content:SQ}]}}}}async function yCi(t,e){let r=[],n=t.baseUrl?.trim()??"",o=jUe("google"),a=dCi(n||o||"https://generativelanguage.googleapis.com"),s=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let u=s.includes("/")?s:`models/${s}`,l=await CQ(t.apiKey);r.push(...l.warnings);let c={"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":l.apiKey};return e?{ok:!0,warnings:r,spec:{method:"POST",url:`${a}/${u}:embedContent`,headers:c,body:{content:{parts:[{text:DUe}]}}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${a}/${u}:generateContent`,headers:c,body:{contents:[{role:"user",parts:[{text:SQ}]}],generationConfig:{maxOutputTokens:sCi}}}}}function bCi(t){return/(^|\.)anthropic\./.test(t)}async function _Ci(t){let e=[],r=t.name?.trim()||"<MODEL_ID>";t.name?.trim()||e.push("Model name is empty; using placeholder.");let n=t.bedrockRegion?.trim()||"us-east-1";t.bedrockRegion?.trim()||e.push("Bedrock region is empty; defaulting to us-east-1.");let o=t.baseUrl?.trim(),a=`${xz(o||`https://bedrock-runtime.${n}.amazonaws.com`)}/model/${encodeURIComponent(r)}/invoke`,s={messages:[{role:"user",content:[{type:"text",text:SQ}]}],max_tokens:aCi};bCi(r)?s.anthropic_version=oCi:e.push("Model ID does not look like Anthropic; request body may need adjust
`),warnings:e}}async function vCi(t,e){let r=[],n=t.baseUrl?.trim()??"",o=jUe("ollama"),i=fCi(xz(n||o||"http://localhost:11434")),a=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let s={"Content-Type":"application/json",Accept:"application/json"};if(t.apiKey?.trim()){let l=await CQ(t.apiKey),c=l.warnings.filter(d=>!d.includes("API key is empty"));r.push(...c),s.Authorization=`Bearer ${l.apiKey}`}return e?{ok:!0,warnings:r,spec:{method:"POST",url:`${i}/api/embed`,headers:s,body:{model:a,input:DUe,truncate:!0}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${i}/api/chat`,headers:s,body:{model:a,messages:[{role:"user",content:SQ}],stream:!1}}}}async function Fan(t){let e=[],r=t.provider?.trim();if(!r)return{ok:!1,error:"Provider is required to build a curl command.",warnings:e};let n=!!t.isEmbeddingModel;if(r==="azure openai"){let o=await hCi(t,n);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}if(r==="anthropic"){if(n)return{ok:!1,error:"Anthropic does not support embeddings.",warnings:e};let o=await gCi(t);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}if(r==="amazon-bedrock")return n?{ok:!1,error:"Bedrock embeddings are not supported by this generator.",warnings:e}:await _Ci(t);if(r==="google"||r==="google"){let o=await yCi(t,n);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}if(r==="ollama"||r==="ollama"){let o=await vCi(t,n);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}if(uCi.has(r)){let o=await pCi(t,n);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}return{ok:!1,error:`Provider "${r}" is not supported for curl generation.`,warnings:e}}Or();hF();var Tz=require("obsidian"),Ze=$(J()),y0t=({open:t,onOpenChange:e,onAdd:r,ping:n,isEmbeddingModel:o=!1})=>{let{modalContainer:i}=_z(),a=te(),s=o?"openai":"openrouterai",u=L=>L==="azure openai",[l,c]=(0,Ze.useState)(null),[d,f]=(0,Ze.useState)(u(s)),[p,m]=(0,Ze.useState)(!1),[h,y]=(0,Ze.useState)("idle"),[g,b]=(0,Ze.useState)({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1}),_=(L,W)=>{b(ie=>({...ie,[L]:W}))},w=()=>{b({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1})},T=()=>{let L=!0,W={...g};return W.name=!E.name,E.name||(L=!1),E.provider==="azure openai"&&(W.instanceName=!E.azureOpenAIApiInstanceName,W.apiVersion=!E.azureOpenAIApiVersion,o?(W.embeddingDeploymentName=!E.azureOpenAIApiEmbeddingDeploymentName,E.azureOpenAIApiEmbeddingDeploymentName||(L=!1)):(W.deploymentName=!E.azureOpenAIApiDeploymentName,E.azureOpenAIApiDeploymentName||(L=!1)),(!E.azureOpenAIApiInstanceName||!E.azureOpenAIApiVersion)&&(L=!1)),E.provider,"amazon-bedrock",W.bedrockRegion=!1,b(W),L},O=(L=s)=>{let W={name:"",provider:L,enabled:!0,isBuiltIn:!1,baseUrl:"",apiKey:Bb(L),isEmbeddingModel:o,capabilities:[]};if(!o){let ie={...W,stream:!0};return L==="amazon-bedrock"?{...ie,bedrockRegion:a.amazonBedrockRegion}:ie}return W},[E,P]=(0,Ze.useState)(O()),R=L=>{P(W=>({...W,...L})),y("idle")},I=L=>({...L,name:L.name?.trim(),baseUrl:L.baseUrl?.trim(),apiKey:L.apiKey?.trim(),openAIOrgId:L.openAIOrgId?.trim(),azureOpenAIApiInstanceName:L.azureOpenAIApiInstanceName?.trim(),azureOpenAIApiDeploymentName:L.azureOpenAIApiDeploymentName?.trim(),azureOpenAIApiEmbeddingDeploymentName:L.azureOpenAIApiEmbeddingDeploymentName?.trim(),azureOpenAIApiVersion:L.azureOpenAIApiVersion?.trim(),bedrockRegion:L.bedrockRegion?.trim()}),[N,z]=(0,Ze.useState)(d1(s)),V=()=>!!(E.name&&E.provider),k=()=>p||!V(),X=()=>{if(!T()){new Tz.Notice("Please fill in all required fields");return}let L=I(E);r(L),e(!1),P(O()),w(),y("idle"),f(!1)},B=L=>{z(d1(L)),y("idle"),P({...E,provider:L,apiKey:Bb(L),...L==="openai"?{openAIOrgId:a.openAIOrgId}:{},...L==="azure openai"?{azureOpenAIApiInstanceName:a.azureOpenAIApiInstanceName,azureOpenAIApiDeploymentName:a.azureOpenAIApiDeploymentName,azureOpenAIApiVersion:a.azureOpenAIApiVersion,azureOpenAIApiEmbeddingDeploymentName:a.azureOpenAIApiEmbeddingDeploymentName
2026-01-05 13:03:55 +08:00
/*! Bundled license information:
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*)
@langchain/core/dist/utils/sax-js/sax.js:
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
mustache/mustache.mjs:
(*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*)
react/cjs/react.production.min.js:
(**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
moment/moment.js:
(*! moment.js *)
(*! version : 2.29.4 *)
(*! authors : Tim Wood, Iskren Chernev, Moment.js contributors *)
(*! license : MIT *)
(*! momentjs.com *)
ieee754/index.js:
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
buffer/index.js:
(*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/shared/src/utils.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/defaultAttributes.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/Icon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/createLucideIcon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/brain.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-down.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-check-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-21 08:46:13 +08:00
lucide-react/dist/esm/icons/circle-check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-05 13:03:55 +08:00
lucide-react/dist/esm/icons/circle-dashed.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-help.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-stop.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-02-24 07:55:02 +08:00
lucide-react/dist/esm/icons/clipboard-paste.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-05 13:03:55 +08:00
lucide-react/dist/esm/icons/cog.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/coins.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/command.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/copy.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/corner-down-left.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cpu.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/database.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/download.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/external-link.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye-off.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-audio.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-clock.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-output.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-text.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-video.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/globe.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/grip-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/hash.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/history.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-21 08:46:13 +08:00
lucide-react/dist/esm/icons/info.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-05 13:03:55 +08:00
lucide-react/dist/esm/icons/key.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/library-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/lightbulb.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/loader-circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-02-24 07:55:02 +08:00
lucide-react/dist/esm/icons/message-square-x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-05 13:03:55 +08:00
lucide-react/dist/esm/icons/message-square.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-02-24 07:55:02 +08:00
lucide-react/dist/esm/icons/pause.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-05 13:03:55 +08:00
lucide-react/dist/esm/icons/pen-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-02-24 07:55:02 +08:00
lucide-react/dist/esm/icons/play.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-05 13:03:55 +08:00
lucide-react/dist/esm/icons/plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-ccw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-02-24 07:55:02 +08:00
lucide-react/dist/esm/icons/replace.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-05 13:03:55 +08:00
lucide-react/dist/esm/icons/rotate-ccw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/rotate-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/search.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-02-24 07:55:02 +08:00
lucide-react/dist/esm/icons/send.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-21 08:46:13 +08:00
lucide-react/dist/esm/icons/settings.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-05 13:03:55 +08:00
lucide-react/dist/esm/icons/sparkles.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-arrow-out-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-02-24 07:55:02 +08:00
lucide-react/dist/esm/icons/square.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2026-01-05 13:03:55 +08:00
lucide-react/dist/esm/icons/tag.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/text-cursor-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/trash-2.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/triangle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/wrench.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/zap-off.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/zap.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/lucide-react.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
safe-buffer/index.js:
(*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
crypto-js/ripemd160.js:
(** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
crypto-js/mode-ctr-gladman.js:
(** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*)
*/
/* nosourcemap */